<commit_before>#include <sol.hpp>
#include <iostream>
#include <cassert>
#include <cmath>

struct foo {
private:
    std::string name;
public:
    foo(std::string name): name(std::string(name)) {}

    void print() {
        std::cout << name << '\n';
    }

    int test(int x) {
        return name.length() + x;
    }
};

struct vector {
private:
    float x = 0;
    float y = 0;
public:
    vector() = default;
    vector(float x): x(x) {}
    vector(float x, float y): x(x), y(y) {}

    bool is_unit() const {
        return (x * x + y * y) == 1.f;
    }
};

struct variables {
    bool low_gravity = false;
    int boost_level = 0;

};

int main() {
    sol::state lua;
    lua.open_libraries(sol::lib::base, sol::lib::math);

    // the simplest way to create a class is through
    // sol::state::new_userdata
    // the first template is the class type
    // the rest are the constructor parameters
    // using new_userdata you can only have one constructor

    // you must make sure that the name of the function
    // goes before the member function pointer
    lua.new_userdata<foo, std::string>("foo", "print", &foo::print, "test", &foo::test);

    // making the class from lua is simple
    // same with calling member functions
    lua.script("x = foo.new('test')\n"
               "x:print()\n"
               "y = x:test(10)");

    auto y = lua.get<int>("y");
    assert(y == 14);

    // if you want a class to have more than one constructor
    // the way to do so is through set_userdata and creating
    // a userdata yourself with constructor types

    {
        // Notice the brace: this means we're in a new scope
        // first, define the different types of constructors
        sol::constructors<sol::types<>, sol::types<float>, sol::types<float, float>> ctor;

        // the only template parameter is the class type
        // the first argument of construction is the name
        // second is the constructor types
        // then the rest are function name and member function pointer pairs
        sol::userdata<vector> udata("vector", ctor, "is_unit", &vector::is_unit);

        // then you must register it
        lua.set_usertype("vector", udata);
        // You can throw away the usertype after you set it: you do NOT
        // have to keep it around
        // cleanup happens automagically
    }
    // calling it is the same as new_userdata

    lua.script("v = vector.new()\n"
               "v = vector.new(12)\n"
               "v = vector.new(10, 10)\n"
               "assert(not v:is_unit())\n");

    // You can even have C++-like member-variable-access
    // just pass is public member variables in the same style as functions
    lua.new_userdata<variables>("variables", "low_gravity", &variables::low_gravity, "boost_level", &variables::boost_level);

    // making the class from lua is simple
    // same with calling member functions/variables
    lua.script("local vars = variables.new()\n"
               "assert(not vars.low_gravity)\n"
               "vars.low_gravity = true\n"
               "local x = vars.low_gravity\n"
               "assert(x)");
}
<commit_msg>Fix examples, closes #26<commit_after>#include <sol.hpp>
#include <iostream>
#include <cassert>
#include <cmath>

struct foo {
private:
    std::string name;
public:
    foo(std::string name): name(std::string(name)) {}

    void print() {
        std::cout << name << '\n';
    }

    int test(int x) {
        return name.length() + x;
    }
};

struct vector {
private:
    float x = 0;
    float y = 0;
public:
    vector() = default;
    vector(float x): x(x) {}
    vector(float x, float y): x(x), y(y) {}

    bool is_unit() const {
        return (x * x + y * y) == 1.f;
    }
};

struct variables {
    bool low_gravity = false;
    int boost_level = 0;

};

int main() {
    sol::state lua;
    lua.open_libraries(sol::lib::base, sol::lib::math);

    // the simplest way to create a class is through
    // sol::state::new_userdata
    // the first template is the class type
    // the rest are the constructor parameters
    // using new_userdata you can only have one constructor

    // you must make sure that the name of the function
    // goes before the member function pointer
    lua.new_usertype<foo, std::string>("foo", "print", &foo::print, "test", &foo::test);

    // making the class from lua is simple
    // same with calling member functions
    lua.script("x = foo.new('test')\n"
               "x:print()\n"
               "y = x:test(10)");

    auto y = lua.get<int>("y");
    assert(y == 14);

    // if you want a class to have more than one constructor
    // the way to do so is through set_userdata and creating
    // a userdata yourself with constructor types

    {
        // Notice the brace: this means we're in a new scope
        // first, define the different types of constructors
        sol::constructors<sol::types<>, sol::types<float>, sol::types<float, float>> ctor;

        // the only template parameter is the class type
        // the first argument of construction is the name
        // second is the constructor types
        // then the rest are function name and member function pointer pairs
        sol::usertype<vector> udata("vector", ctor, "is_unit", &vector::is_unit);

        // then you must register it
        lua.set_usertype("vector", udata);
        // You can throw away the usertype after you set it: you do NOT
        // have to keep it around
        // cleanup happens automagically
    }
    // calling it is the same as new_userdata

    lua.script("v = vector.new()\n"
               "v = vector.new(12)\n"
               "v = vector.new(10, 10)\n"
               "assert(not v:is_unit())\n");

    // You can even have C++-like member-variable-access
    // just pass is public member variables in the same style as functions
    lua.new_usertype<variables>("variables", "low_gravity", &variables::low_gravity, "boost_level", &variables::boost_level);

    // making the class from lua is simple
    // same with calling member functions/variables
    lua.script("local vars = variables.new()\n"
               "assert(not vars.low_gravity)\n"
               "vars.low_gravity = true\n"
               "local x = vars.low_gravity\n"
               "assert(x)");
}
<|endoftext|>


<commit_before>/*!
	@file
	@author		Georgiy Evmenov
	@date		08/2008
*/

#include "precompiled.h"
#include "EditorToolTip.h"
#include "MyGUI_SkinManager.h"

namespace tools
{
	EditorToolTip::EditorToolTip() :
		BaseLayout("EditorToolTip.layout")
	{
		assignWidget(mText, "Text");

		mMinWidth = MyGUI::utility::parseInt(mMainWidget->getUserString("mMinWidth"));
		mMinHeight = MyGUI::utility::parseInt(mMainWidget->getUserString("mMinHeight"));
		mLastWidget = nullptr;
	}

	void EditorToolTip::show(MyGUI::Widget* _sender)
	{
		static const MyGUI::UString colour_error = MyGUI::LanguageManager::getInstance().getTag("ColourError");
		static const MyGUI::UString colour_success = MyGUI::LanguageManager::getInstance().getTag("ColourSuccess");

		std::string widget = _sender->getUserString("widget");
		bool exist = MyGUI::WidgetManager::getInstance().isFactoryExist(widget);
		std::string skin = _sender->getUserString("skin");
		std::string text = "Widget: " + (exist ? colour_success : colour_error) + widget + colour_success +
			"\nSkin: " + skin +
			"\nDefaultSize: " + _sender->getUserString("width") + " x " + _sender->getUserString("height")
			;

		mText->setCaption(text);

		int width = MyGUI::utility::parseInt(_sender->getUserString("width"));
		int height = MyGUI::utility::parseInt(_sender->getUserString("height"));

		const int MARGIN = 5;
		const int LINE_HEIGHT = 22;
		const int LINES = 3;

		MyGUI::SkinManager & manager = MyGUI::SkinManager::getInstance();
		if (manager.isExist(skin))
		{
			MyGUI::IntSize max_size;

			MyGUI::ResourceSkin* info = manager.getByName(skin);
			if (info != nullptr)
			{
				const MyGUI::VectorChildSkinInfo & child = info->getChild();
				for (size_t pos=0; pos<child.size(); ++pos)
				{
					const std::string& child_skin = child[pos].skin;
					if (!manager.isExist(child_skin)) continue;
					const MyGUI::ResourceSkin * child_info = manager.getByName(child_skin);
					const MyGUI::IntSize & child_size = child[pos].coord.size();
					MyGUI::IntSize dif_size = child_info->getSize() - child_size;

					if (max_size.width < dif_size.width) max_size.width = dif_size.width;
					if (max_size.height < dif_size.height) max_size.height = dif_size.height;
				}
			}

			width += max_size.width;
			height += max_size.height;
		}

		mMainWidget->setSize(std::max(mMinWidth, width + 2*MARGIN), std::max(mMinHeight, height + LINE_HEIGHT*LINES + 2*MARGIN));
		if (mLastWidget)
			MyGUI::Gui::getInstance().destroyWidget(mLastWidget);
		mLastWidget = mMainWidget->createWidgetT("StaticText", skin, MARGIN, MARGIN + LINE_HEIGHT*LINES, width, height, MyGUI::Align::Default);
		mLastWidget->castType<MyGUI::StaticText>()->setCaption(skin);

		mMainWidget->setVisible(true);
	}

	void EditorToolTip::hide()
	{
		mMainWidget->setVisible(false);
	}

	void EditorToolTip::move(const MyGUI::IntPoint & _point)
	{
		setPosition(_point);
	}

	void EditorToolTip::setPosition(const MyGUI::IntPoint & _point)
	{
		const MyGUI::IntPoint offset(10, 10);

		MyGUI::IntPoint point = _point + offset;

		const MyGUI::IntSize& size = mMainWidget->getSize();
		const MyGUI::IntSize& view_size = mMainWidget->getParentSize();

		if ((point.left + size.width) > view_size.width)
		{
			point.left -= offset.left + offset.left + size.width;
		}
		if ((point.top + size.height) > view_size.height)
		{
			point.top -= offset.top + offset.top + size.height;
		}

		mMainWidget->setPosition(point);
	}

} // namespace tools
<commit_msg>LE: fix tooltip<commit_after>/*!
	@file
	@author		Georgiy Evmenov
	@date		08/2008
*/

#include "precompiled.h"
#include "EditorToolTip.h"
#include "MyGUI_SkinManager.h"

namespace tools
{
	EditorToolTip::EditorToolTip() :
		BaseLayout("EditorToolTip.layout")
	{
		assignWidget(mText, "Text");

		mMinWidth = MyGUI::utility::parseInt(mMainWidget->getUserString("minWidth"));
		mMinHeight = MyGUI::utility::parseInt(mMainWidget->getUserString("minHeight"));
		mLastWidget = nullptr;
	}

	void EditorToolTip::show(MyGUI::Widget* _sender)
	{
		static const MyGUI::UString colour_error = MyGUI::LanguageManager::getInstance().getTag("ColourError");
		static const MyGUI::UString colour_success = MyGUI::LanguageManager::getInstance().getTag("ColourSuccess");

		std::string widget = _sender->getUserString("widget");
		bool exist = MyGUI::WidgetManager::getInstance().isFactoryExist(widget);
		std::string skin = _sender->getUserString("skin");
		std::string text = "Widget: " + (exist ? colour_success : colour_error) + widget + colour_success +
			"\nSkin: " + skin +
			"\nDefaultSize: " + _sender->getUserString("width") + " x " + _sender->getUserString("height")
			;

		mText->setCaption(text);

		int width = MyGUI::utility::parseInt(_sender->getUserString("width"));
		int height = MyGUI::utility::parseInt(_sender->getUserString("height"));

		const int MARGIN = 5;
		const int LINE_HEIGHT = 22;
		const int LINES = 3;

		MyGUI::SkinManager & manager = MyGUI::SkinManager::getInstance();
		if (manager.isExist(skin))
		{
			MyGUI::IntSize max_size;

			MyGUI::ResourceSkin* info = manager.getByName(skin);
			if (info != nullptr)
			{
				const MyGUI::VectorChildSkinInfo & child = info->getChild();
				for (size_t pos=0; pos<child.size(); ++pos)
				{
					const std::string& child_skin = child[pos].skin;
					if (!manager.isExist(child_skin)) continue;
					const MyGUI::ResourceSkin * child_info = manager.getByName(child_skin);
					const MyGUI::IntSize & child_size = child[pos].coord.size();
					MyGUI::IntSize dif_size = child_info->getSize() - child_size;

					if (max_size.width < dif_size.width) max_size.width = dif_size.width;
					if (max_size.height < dif_size.height) max_size.height = dif_size.height;
				}
			}

			width += max_size.width;
			height += max_size.height;
		}

		mMainWidget->setSize(std::max(mMinWidth, width + 2*MARGIN), std::max(mMinHeight, height + LINE_HEIGHT*LINES + 2*MARGIN));
		if (mLastWidget)
			MyGUI::Gui::getInstance().destroyWidget(mLastWidget);
		mLastWidget = mMainWidget->createWidgetT("StaticText", skin, MARGIN, MARGIN + LINE_HEIGHT*LINES, width, height, MyGUI::Align::Default);
		mLastWidget->castType<MyGUI::StaticText>()->setCaption(skin);

		mMainWidget->setVisible(true);
	}

	void EditorToolTip::hide()
	{
		mMainWidget->setVisible(false);
	}

	void EditorToolTip::move(const MyGUI::IntPoint & _point)
	{
		setPosition(_point);
	}

	void EditorToolTip::setPosition(const MyGUI::IntPoint & _point)
	{
		const MyGUI::IntPoint offset(10, 10);

		MyGUI::IntPoint point = _point + offset;

		const MyGUI::IntSize& size = mMainWidget->getSize();
		const MyGUI::IntSize& view_size = mMainWidget->getParentSize();

		if ((point.left + size.width) > view_size.width)
		{
			point.left -= offset.left + offset.left + size.width;
		}
		if ((point.top + size.height) > view_size.height)
		{
			point.top -= offset.top + offset.top + size.height;
		}

		mMainWidget->setPosition(point);
	}

} // namespace tools
<|endoftext|>


<commit_before>/** YDA **/
#include "YMain.h"
#include "YSpriteManager.h"
#include "YFileSystem.h"
#include "YSprite.h"
#include "YSpriteSheet.h"
#include "YObject.h"
#include "YObjectManager.h"
#include "Bird.h"
#include "Cloud.h"

/** STL **/
#include <array>
#include <algorithm>

const char* kCloud01 = "cloud_01";
const char* kCloud02 = "cloud_02";
const char* kRedBird = "red_bird";

void createClouds(std::vector<Cloud*>&& a_clouds,
                  int a_size,
                  YSpriteManager* a_manager)
{
    a_clouds.reserve(a_size);

    for (int i = 0; i < a_size; ++i)
    {
        const char* name = (i % 2 == 0) ? kCloud01 : kCloud02;
        float z = (i % 2 == 0) ? 0.f : 2.f;
        YSprite* cloudSprite = new YSprite(a_manager->findByName(name));
        Cloud* cloud01 = new Cloud(cloudSprite);
        YPoint position = cloud01->position();

        position.z(z);
        cloud01->position(position);
        a_clouds.push_back(cloud01);
    }
}

int main(int argc, char** argv)
{
    typedef struct
    {
        std::string key;
        std::string value;
    } KeyValue;

    YMain* game = new YMain("Z-Order - sergiosvieira@gmail.com", 640, 480);
    YObjectManager* objectManager = new YObjectManager();

    /** Load Resources **/
    YSpriteManager* manager = new YSpriteManager(game->renderer());
    std::array<KeyValue, 3> images = {
      {
          {kCloud01, "cloud_01.png"},
          {kCloud02, "cloud_02.png"},
          {kRedBird, "red_bird_set.png"}
      }
    };

    for (const KeyValue& kv: images)
    {
        manager->add(kv.key.c_str(),
                     YFileSystem::fullPathName({"gfx"},
                                               kv.value.c_str()));
    }

    /** Creates Clouds **/
    std::vector<Cloud*> clouds;
    createClouds(std::move(clouds),
                 100,
                 manager);

    /** Creates Bird **/
    YSpriteSheet* birdSprite = new YSpriteSheet(manager->findByName("red_bird"),
                                                YFrame(0, 0, 5),
                                                64,
                                                40,
                                                20);
    Bird* bird = new Bird(birdSprite);

    /** Update/Render Objects **/
    for (Cloud* cloud: clouds)
    {
        objectManager->add(cloud);
    }

    objectManager->add(bird);
    objectManager->updateRender();

    game->start(objectManager->updater(),
                objectManager->renderer(),
                25,
                5);

    return 0;
}<commit_msg>Removed UpdateRender from main.cpp ZOrder sample game<commit_after>/** YDA **/
#include "YMain.h"
#include "YSpriteManager.h"
#include "YFileSystem.h"
#include "YSprite.h"
#include "YSpriteSheet.h"
#include "YObject.h"
#include "YObjectManager.h"
#include "Bird.h"
#include "Cloud.h"

/** STL **/
#include <array>
#include <algorithm>

const char* kCloud01 = "cloud_01";
const char* kCloud02 = "cloud_02";
const char* kRedBird = "red_bird";

void createClouds(std::vector<Cloud*>&& a_clouds,
                  int a_size,
                  YSpriteManager* a_manager)
{
    a_clouds.reserve(a_size);

    for (int i = 0; i < a_size; ++i)
    {
        const char* name = (i % 2 == 0) ? kCloud01 : kCloud02;
        float z = (i % 2 == 0) ? 0.f : 2.f;
        YSprite* cloudSprite = new YSprite(a_manager->findByName(name));
        Cloud* cloud01 = new Cloud(cloudSprite);
        YPoint position = cloud01->position();

        position.z(z);
        cloud01->position(position);
        a_clouds.push_back(cloud01);
    }
}

int main(int argc, char** argv)
{
    typedef struct
    {
        std::string key;
        std::string value;
    } KeyValue;

    YMain* game = new YMain("Z-Order - sergiosvieira@gmail.com", 640, 480);
    YObjectManager* objectManager = new YObjectManager();

    /** Load Resources **/
    YSpriteManager* manager = new YSpriteManager(game->renderer());
    std::array<KeyValue, 3> images = {
      {
          {kCloud01, "cloud_01.png"},
          {kCloud02, "cloud_02.png"},
          {kRedBird, "red_bird_set.png"}
      }
    };

    for (const KeyValue& kv: images)
    {
        manager->add(kv.key.c_str(),
                     YFileSystem::fullPathName({"gfx"},
                                               kv.value.c_str()));
    }

    /** Creates Clouds **/
    std::vector<Cloud*> clouds;
    createClouds(std::move(clouds),
                 100,
                 manager);

    /** Creates Bird **/
    YSpriteSheet* birdSprite = new YSpriteSheet(manager->findByName("red_bird"),
                                                YFrame(0, 0, 5),
                                                64,
                                                40,
                                                20);
    Bird* bird = new Bird(birdSprite);

    /** Update/Render Objects **/
    for (Cloud* cloud: clouds)
    {
        objectManager->add(cloud);
    }

    objectManager->add(bird);

    game->start(objectManager->updater(),
                objectManager->renderer(),
                25,
                5);

    return 0;
}<|endoftext|>


<commit_before>#include "database.hpp"
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/tail.hpp>
#include <boost/progress.hpp>
#include <cmath>
#include <fstream>
#include <stdexcept>
#include <boost/format.hpp>

namespace openMVG{
namespace voctree{

std::ostream& operator<<(std::ostream& os, const SparseHistogram &dv)
{
	for( const auto &e : dv )
	{
		os << e.first << ", " << e.second.size() << "; ";
	}
	os << "\n";
	return os;
}

Database::Database(uint32_t num_words)
: word_files_(num_words),
word_weights_( num_words, 1.0f ) { }

DocId Database::insert(DocId doc_id, const SparseHistogram& document)
{
  // Ensure that the new document to insert is not already there.
  assert(database_.find(doc_id) == database_.end());

  // For each word, retrieve its inverted file and increment the count for doc_id.
  for(SparseHistogram::const_iterator it = document.begin(), end = document.end(); it != end; ++it)
  {
    Word word = it->first;
    InvertedFile& file = word_files_[word];
    if(file.empty() || file.back().id != doc_id)
      file.push_back(WordFrequency(doc_id, it->second.size()));
    else
      file.back().count += it->second.size();
  }

  database_[doc_id] = document;

  return doc_id;
}

void Database::sanityCheck(size_t N, std::map<size_t, DocMatches>& matches) const
{
  // if N is equal to zero
  if(N == 0)
  {
    // retrieve all the matchings
    N = this->size();
  }
  else
  {
    // otherwise always take the min between N and the number of documents
    // in the database
    N = std::min(N, this->size());
  }

  matches.clear();
  // since we already know the size of the vectors, in order to parallelize the
  // query allocate the whole memory
  boost::progress_display display(database_.size());

  //#pragma omp parallel for default(none) shared(database_)
  for(const auto &doc : database_)
  {
    std::vector<DocMatch> m;
    find(doc.second, N, m);
    //		matches.emplace_back( m );
    matches[doc.first] = m;
    ++display;
  }
}

/**
 * @brief Find the top N matches in the database for the query document.
 *
 * @param[in]  document The query document, a set of quantized words.
 * @param[in]  N        The number of matches to return.
 * @param[out] matches  IDs and scores for the top N matching database documents.
 * @param[in] distanceMethod the method used to compute distance between histograms.
 */
void Database::find(const std::vector<Word>& document, size_t N, std::vector<DocMatch>& matches, const std::string &distanceMethod) const
{
  SparseHistogram query;
  // from the list of visual words associated with each feature in the document/image
  // generate the (sparse) histogram of the visual words
  computeSparseHistogram(document, query);

  find( query, N, matches, distanceMethod);
}

/**
 * @brief Find the top N matches in the database for the query document.
 *
 * @param      query The query document, a normalized set of quantized words.
 * @param      N        The number of matches to return.
 * @param[out] matches  IDs and scores for the top N matching database documents.
 * @param[in] distanceMethod the method used to compute distance between histograms.
 */
void Database::find( const SparseHistogram& query, size_t N, std::vector<DocMatch>& matches, const std::string &distanceMethod) const
{
  // Accumulate the best N matches
  using namespace boost::accumulators;
  typedef tag::tail<left> bestN_tag;
  accumulator_set<DocMatch, features<bestN_tag> > acc(bestN_tag::cache_size = N);

  /// @todo Try only computing distances against documents sharing at least one word
  for(const auto& document: database_)
  {
    // for each document/image in the database compute the distance between the
    // histograms of the query image and the others
    float distance = sparseDistance(query, document.second, distanceMethod);
    acc(DocMatch(document.first, distance));
  }

  // extract the best N
  extractor<bestN_tag> bestN;
  matches.resize(std::min(N, database_.size()));
  std::copy(bestN(acc).begin(), bestN(acc).end(), matches.begin());
}

/**
 * @brief Compute the TF-IDF weights of all the words. To be called after inserting a corpus of
 * training examples into the database.
 *
 * @param default_weight The default weight of a word that appears in none of the training documents.
 */
void Database::computeTfIdfWeights(float default_weight)
{
  float N = (float) database_.size();
  size_t num_words = word_files_.size();
  for(size_t i = 0; i < num_words; ++i)
  {
    size_t Ni = word_files_[i].size();
    if(Ni != 0)
      word_weights_[i] = std::log(N / Ni);
    else
      word_weights_[i] = default_weight;
  }
}

void Database::saveWeights(const std::string& file) const
{
  std::ofstream out(file.c_str(), std::ios_base::binary);
  uint32_t num_words = word_weights_.size();
  out.write((char*) (&num_words), sizeof (uint32_t));
  out.write((char*) (&word_weights_[0]), num_words * sizeof (float));
}

void Database::loadWeights(const std::string& file)
{
  std::ifstream in;
  in.exceptions(std::ifstream::eofbit | std::ifstream::failbit | std::ifstream::badbit);

  try
  {
    in.open(file.c_str(), std::ios_base::binary);
    uint32_t num_words = 0;
    in.read((char*) (&num_words), sizeof (uint32_t));
    word_files_.resize(num_words); // Inverted files start out empty
    word_weights_.resize(num_words);
    in.read((char*) (&word_weights_[0]), num_words * sizeof (float));
  }
  catch(std::ifstream::failure& e)
  {
    throw std::runtime_error((boost::format("Failed to load vocabulary weights file '%s'") % file).str());
  }
}

///**
// * Normalize a document vector representing the histogram of visual words for a given image
// *
// * @param[in/out] v the unnormalized histogram of visual words
// */
//void Database::normalize(SparseHistogram& v) const
//{
//  float sum = 0.0f;
//  for(SparseHistogram::iterator i = v.begin(), ie = v.end(); i != ie; ++i)
//    sum += i->second;
//  float inv_sum = 1.0f / sum;
//  for(SparseHistogram::iterator i = v.begin(), ie = v.end(); i != ie; ++i)
//    i->second *= inv_sum;
//}

/**
 * Compute the distance between two histograms
 *
 * @param[in] v1 the first histogram
 * @param[in] v2 the second histogram
 * @param[in] distanceMethod the method used to compute distance between histograms
 */
float Database::sparseDistance(const SparseHistogram& v1, const SparseHistogram& v2, const std::string &distanceMethod) const
{

  float distance = 0.0f;
  float epsilon = 0.001;

  SparseHistogram::const_iterator i1 = v1.begin(), i1e = v1.end();
  SparseHistogram::const_iterator i2 = v2.begin(), i2e = v2.end();

  if(distanceMethod.compare("classic") == 0)
  {
    while(i1 != i1e && i2 != i2e)
    {
      if(i2->first < i1->first)
      {
        distance += i2->second.size();
        ++i2;
      }
      else if(i1->first < i2->first)
      {
        distance += i1->second.size();
        ++i1;
      }
      else
      {
        distance += fabs(i1->second.size() - i2->second.size());
        ++i1;
        ++i2;
      }
    }

    while(i1 != i1e)
    {
      distance += i1->second.size();
      ++i1;
    }

    while(i2 != i2e)
    {
      distance += i2->second.size();
      ++i2;
    }
  }

  else if(distanceMethod.compare("commonPoints") == 0)
  {
    double score = 0.0;
    double N1 = 0.0;
    double N2 = 0.0;

    while(i1 != i1e && i2 != i2e)
    {
      if(i2->first < i1->first)
      {
        N2 += i2->second.size();
        ++i2;
      }
      else if(i1->first < i2->first)
      {
        N1 += i1->second.size();
         ++i1;
      }
      else
      {
        score += std::min(i1->second.size(), i2->second.size());
        N1 += i1->second.size();
        N2 += i2->second.size();
        ++i1;
        ++i2;
      }
    }

    while(i1 != i1e)
    {
      N1 += i1->second.size();
      ++i1;
    }

    while(i2 != i2e)
    {
      N2 += i2->second.size();
      ++i2;
    }

    distance = - score;
  }

  else if(distanceMethod.compare("strongCommonPoints") == 0)
  {
    double score = 0.0;
    double N1 = 0.0;
    double N2 = 0.0;

    while(i1 != i1e && i2 != i2e)
    {
      if(i2->first < i1->first)
      {
        N2 += i2->second.size();
        ++i2;
      }
      else if(i1->first < i2->first)
      {
        N1 += i1->second.size();
        ++i1;
      }
      else
      {
        if( ( fabs(i1->second.size() - 1.0) < epsilon ) && ( fabs(i2->second.size() - 1.0) < epsilon) )
        {
          score += 1;
          N1 += 1;
          N2 += 1;
        }
        ++i1;
        ++i2;
      }
    }

    while(i1 != i1e)
    {
      N1 += i1->second.size();
      ++i1;
    }

    while(i2 != i2e)
    {
      N2 += i2->second.size();
      ++i2;
    }

    distance = - score;
  }

  else if(distanceMethod.compare("weightedStrongCommonPoints") == 0)
  {
    double score = 0.0;
    double N1 = 0.0;
    double N2 = 0.0;

    while(i1 != i1e && i2 != i2e)
    {
      if(i2->first < i1->first)
      {
        N2 += i2->second.size()*word_weights_[i2->first];
        ++i2;
      }
      else if(i1->first < i2->first)
      {
        N1 += i1->second.size()*word_weights_[i1->first];
         ++i1;
      }
        if( ( fabs(i1->second.size() - 1.0) < epsilon ) && ( fabs(i2->second.size() - 1.0) < epsilon) )
        {
          score += word_weights_[i1->first];
          N1 += word_weights_[i1->first];
          N2 += word_weights_[i2->first];
        }
        ++i1;
        ++i2;
    }

    while(i1 != i1e)
    {
      N1 += i1->second.size()*word_weights_[i1->first];
      ++i1;
    }

    while(i2 != i2e)
    {
      N2 += i2->second.size()*word_weights_[i2->first];
      ++i2;
    }

    distance = - score;
  }

  else if(distanceMethod.compare("inversedWeightedCommonPoints") == 0)
  {
    double score = 0.0;
    double N1 = 0.0;
    double N2 = 0.0;
    std::map<int,int> compteur;

    while(i1 != i1e && i2 != i2e)
    {
      if(i2->first < i1->first)
      {
        N2 += i2->second.size() / word_weights_[i2->first];
        ++i2;
      }
      else if(i1->first < i2->first)
      {
        N1 += i1->second.size() / word_weights_[i1->first];
         ++i1;
      }
      else
      {
        compteur[i1->first] += std::min(i1->second.size(), i2->second.size());
        N1 += i1->second.size() / word_weights_[i1->first];
        N2 += i2->second.size() / word_weights_[i2->first];
        ++i1;
        ++i2;
      }
    }

    while(i1 != i1e)
    {
      N1 += i1->second.size() / word_weights_[i1->first];
      ++i1;
    }

    while(i2 != i2e)
    {
      N2 += i2->second.size() / word_weights_[i2->first];;
      ++i2;
    }

    for(auto iCompteur = compteur.begin(); iCompteur != compteur.end(); iCompteur++)
      score += (1.0/iCompteur->second) * word_weights_[iCompteur->first];

    distance = - score;
  }
  else
  {
    std::cout << "Unknown distanceMethod" << std::endl;
    exit(-1);
  }

  return distance;

}

/**
 * @brief Return the size of the database in terms of number of documents
 * @return the number of documents
 */
size_t Database::size() const
{
  return database_.size();
}

} //namespace voctree
} //namespace openMVG
<commit_msg>[voctree] use exception instead of exit<commit_after>#include "database.hpp"
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/tail.hpp>
#include <boost/progress.hpp>
#include <cmath>
#include <fstream>
#include <stdexcept>
#include <boost/format.hpp>

namespace openMVG{
namespace voctree{

std::ostream& operator<<(std::ostream& os, const SparseHistogram &dv)
{
	for( const auto &e : dv )
	{
		os << e.first << ", " << e.second.size() << "; ";
	}
	os << "\n";
	return os;
}

Database::Database(uint32_t num_words)
: word_files_(num_words),
word_weights_( num_words, 1.0f ) { }

DocId Database::insert(DocId doc_id, const SparseHistogram& document)
{
  // Ensure that the new document to insert is not already there.
  assert(database_.find(doc_id) == database_.end());

  // For each word, retrieve its inverted file and increment the count for doc_id.
  for(SparseHistogram::const_iterator it = document.begin(), end = document.end(); it != end; ++it)
  {
    Word word = it->first;
    InvertedFile& file = word_files_[word];
    if(file.empty() || file.back().id != doc_id)
      file.push_back(WordFrequency(doc_id, it->second.size()));
    else
      file.back().count += it->second.size();
  }

  database_[doc_id] = document;

  return doc_id;
}

void Database::sanityCheck(size_t N, std::map<size_t, DocMatches>& matches) const
{
  // if N is equal to zero
  if(N == 0)
  {
    // retrieve all the matchings
    N = this->size();
  }
  else
  {
    // otherwise always take the min between N and the number of documents
    // in the database
    N = std::min(N, this->size());
  }

  matches.clear();
  // since we already know the size of the vectors, in order to parallelize the
  // query allocate the whole memory
  boost::progress_display display(database_.size());

  //#pragma omp parallel for default(none) shared(database_)
  for(const auto &doc : database_)
  {
    std::vector<DocMatch> m;
    find(doc.second, N, m);
    //		matches.emplace_back( m );
    matches[doc.first] = m;
    ++display;
  }
}

/**
 * @brief Find the top N matches in the database for the query document.
 *
 * @param[in]  document The query document, a set of quantized words.
 * @param[in]  N        The number of matches to return.
 * @param[out] matches  IDs and scores for the top N matching database documents.
 * @param[in] distanceMethod the method used to compute distance between histograms.
 */
void Database::find(const std::vector<Word>& document, size_t N, std::vector<DocMatch>& matches, const std::string &distanceMethod) const
{
  SparseHistogram query;
  // from the list of visual words associated with each feature in the document/image
  // generate the (sparse) histogram of the visual words
  computeSparseHistogram(document, query);

  find( query, N, matches, distanceMethod);
}

/**
 * @brief Find the top N matches in the database for the query document.
 *
 * @param      query The query document, a normalized set of quantized words.
 * @param      N        The number of matches to return.
 * @param[out] matches  IDs and scores for the top N matching database documents.
 * @param[in] distanceMethod the method used to compute distance between histograms.
 */
void Database::find( const SparseHistogram& query, size_t N, std::vector<DocMatch>& matches, const std::string &distanceMethod) const
{
  // Accumulate the best N matches
  using namespace boost::accumulators;
  typedef tag::tail<left> bestN_tag;
  accumulator_set<DocMatch, features<bestN_tag> > acc(bestN_tag::cache_size = N);

  /// @todo Try only computing distances against documents sharing at least one word
  for(const auto& document: database_)
  {
    // for each document/image in the database compute the distance between the
    // histograms of the query image and the others
    float distance = sparseDistance(query, document.second, distanceMethod);
    acc(DocMatch(document.first, distance));
  }

  // extract the best N
  extractor<bestN_tag> bestN;
  matches.resize(std::min(N, database_.size()));
  std::copy(bestN(acc).begin(), bestN(acc).end(), matches.begin());
}

/**
 * @brief Compute the TF-IDF weights of all the words. To be called after inserting a corpus of
 * training examples into the database.
 *
 * @param default_weight The default weight of a word that appears in none of the training documents.
 */
void Database::computeTfIdfWeights(float default_weight)
{
  float N = (float) database_.size();
  size_t num_words = word_files_.size();
  for(size_t i = 0; i < num_words; ++i)
  {
    size_t Ni = word_files_[i].size();
    if(Ni != 0)
      word_weights_[i] = std::log(N / Ni);
    else
      word_weights_[i] = default_weight;
  }
}

void Database::saveWeights(const std::string& file) const
{
  std::ofstream out(file.c_str(), std::ios_base::binary);
  uint32_t num_words = word_weights_.size();
  out.write((char*) (&num_words), sizeof (uint32_t));
  out.write((char*) (&word_weights_[0]), num_words * sizeof (float));
}

void Database::loadWeights(const std::string& file)
{
  std::ifstream in;
  in.exceptions(std::ifstream::eofbit | std::ifstream::failbit | std::ifstream::badbit);

  try
  {
    in.open(file.c_str(), std::ios_base::binary);
    uint32_t num_words = 0;
    in.read((char*) (&num_words), sizeof (uint32_t));
    word_files_.resize(num_words); // Inverted files start out empty
    word_weights_.resize(num_words);
    in.read((char*) (&word_weights_[0]), num_words * sizeof (float));
  }
  catch(std::ifstream::failure& e)
  {
    throw std::runtime_error((boost::format("Failed to load vocabulary weights file '%s'") % file).str());
  }
}

///**
// * Normalize a document vector representing the histogram of visual words for a given image
// *
// * @param[in/out] v the unnormalized histogram of visual words
// */
//void Database::normalize(SparseHistogram& v) const
//{
//  float sum = 0.0f;
//  for(SparseHistogram::iterator i = v.begin(), ie = v.end(); i != ie; ++i)
//    sum += i->second;
//  float inv_sum = 1.0f / sum;
//  for(SparseHistogram::iterator i = v.begin(), ie = v.end(); i != ie; ++i)
//    i->second *= inv_sum;
//}

/**
 * Compute the distance between two histograms
 *
 * @param[in] v1 the first histogram
 * @param[in] v2 the second histogram
 * @param[in] distanceMethod the method used to compute distance between histograms
 */
float Database::sparseDistance(const SparseHistogram& v1, const SparseHistogram& v2, const std::string &distanceMethod) const
{

  float distance = 0.0f;
  float epsilon = 0.001;

  SparseHistogram::const_iterator i1 = v1.begin(), i1e = v1.end();
  SparseHistogram::const_iterator i2 = v2.begin(), i2e = v2.end();

  if(distanceMethod.compare("classic") == 0)
  {
    while(i1 != i1e && i2 != i2e)
    {
      if(i2->first < i1->first)
      {
        distance += i2->second.size();
        ++i2;
      }
      else if(i1->first < i2->first)
      {
        distance += i1->second.size();
        ++i1;
      }
      else
      {
        distance += fabs(i1->second.size() - i2->second.size());
        ++i1;
        ++i2;
      }
    }

    while(i1 != i1e)
    {
      distance += i1->second.size();
      ++i1;
    }

    while(i2 != i2e)
    {
      distance += i2->second.size();
      ++i2;
    }
  }

  else if(distanceMethod.compare("commonPoints") == 0)
  {
    double score = 0.0;
    double N1 = 0.0;
    double N2 = 0.0;

    while(i1 != i1e && i2 != i2e)
    {
      if(i2->first < i1->first)
      {
        N2 += i2->second.size();
        ++i2;
      }
      else if(i1->first < i2->first)
      {
        N1 += i1->second.size();
         ++i1;
      }
      else
      {
        score += std::min(i1->second.size(), i2->second.size());
        N1 += i1->second.size();
        N2 += i2->second.size();
        ++i1;
        ++i2;
      }
    }

    while(i1 != i1e)
    {
      N1 += i1->second.size();
      ++i1;
    }

    while(i2 != i2e)
    {
      N2 += i2->second.size();
      ++i2;
    }

    distance = - score;
  }

  else if(distanceMethod.compare("strongCommonPoints") == 0)
  {
    double score = 0.0;
    double N1 = 0.0;
    double N2 = 0.0;

    while(i1 != i1e && i2 != i2e)
    {
      if(i2->first < i1->first)
      {
        N2 += i2->second.size();
        ++i2;
      }
      else if(i1->first < i2->first)
      {
        N1 += i1->second.size();
        ++i1;
      }
      else
      {
        if( ( fabs(i1->second.size() - 1.0) < epsilon ) && ( fabs(i2->second.size() - 1.0) < epsilon) )
        {
          score += 1;
          N1 += 1;
          N2 += 1;
        }
        ++i1;
        ++i2;
      }
    }

    while(i1 != i1e)
    {
      N1 += i1->second.size();
      ++i1;
    }

    while(i2 != i2e)
    {
      N2 += i2->second.size();
      ++i2;
    }

    distance = - score;
  }

  else if(distanceMethod.compare("weightedStrongCommonPoints") == 0)
  {
    double score = 0.0;
    double N1 = 0.0;
    double N2 = 0.0;

    while(i1 != i1e && i2 != i2e)
    {
      if(i2->first < i1->first)
      {
        N2 += i2->second.size()*word_weights_[i2->first];
        ++i2;
      }
      else if(i1->first < i2->first)
      {
        N1 += i1->second.size()*word_weights_[i1->first];
         ++i1;
      }
        if( ( fabs(i1->second.size() - 1.0) < epsilon ) && ( fabs(i2->second.size() - 1.0) < epsilon) )
        {
          score += word_weights_[i1->first];
          N1 += word_weights_[i1->first];
          N2 += word_weights_[i2->first];
        }
        ++i1;
        ++i2;
    }

    while(i1 != i1e)
    {
      N1 += i1->second.size()*word_weights_[i1->first];
      ++i1;
    }

    while(i2 != i2e)
    {
      N2 += i2->second.size()*word_weights_[i2->first];
      ++i2;
    }

    distance = - score;
  }

  else if(distanceMethod.compare("inversedWeightedCommonPoints") == 0)
  {
    double score = 0.0;
    double N1 = 0.0;
    double N2 = 0.0;
    std::map<int,int> compteur;

    while(i1 != i1e && i2 != i2e)
    {
      if(i2->first < i1->first)
      {
        N2 += i2->second.size() / word_weights_[i2->first];
        ++i2;
      }
      else if(i1->first < i2->first)
      {
        N1 += i1->second.size() / word_weights_[i1->first];
         ++i1;
      }
      else
      {
        compteur[i1->first] += std::min(i1->second.size(), i2->second.size());
        N1 += i1->second.size() / word_weights_[i1->first];
        N2 += i2->second.size() / word_weights_[i2->first];
        ++i1;
        ++i2;
      }
    }

    while(i1 != i1e)
    {
      N1 += i1->second.size() / word_weights_[i1->first];
      ++i1;
    }

    while(i2 != i2e)
    {
      N2 += i2->second.size() / word_weights_[i2->first];;
      ++i2;
    }

    for(auto iCompteur = compteur.begin(); iCompteur != compteur.end(); iCompteur++)
      score += (1.0/iCompteur->second) * word_weights_[iCompteur->first];

    distance = - score;
  }
  else
  {
    throw std::invalid_argument("distance method "+ distanceMethod +" unknown!");
  }

  return distance;

}

/**
 * @brief Return the size of the database in terms of number of documents
 * @return the number of documents
 */
size_t Database::size() const
{
  return database_.size();
}

} //namespace voctree
} //namespace openMVG
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_vas_scom.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9_vas_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr auto literal_0x000001000001FFFF = 0x000001000001FFFF;
constexpr auto literal_0xFF00FDFC0003FFFF = 0xFF00FDFC0003FFFF;
constexpr auto literal_0xFFFFFEFFFFFF8000 = 0xFFFFFEFFFFFF8000;
constexpr auto literal_0x1 = 0x1;

fapi2::ReturnCode p9_vas_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0,
                              const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)
{
    fapi2::ReturnCode l_rc = 0;

    do
    {
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            l_rc = fapi2::getScom( TGT0, 0x3011803ull, l_scom_buffer );

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: getScom (0x3011803ull)");
                break;
            }

            {
                l_scom_buffer.insert<uint64_t> (literal_0x000001000001FFFF, 0, 54, 0 );
            }

            l_rc = fapi2::putScom(TGT0, 0x3011803ull, l_scom_buffer);

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: putScom (0x3011803ull)");
                break;
            }
        }
        {
            l_rc = fapi2::getScom( TGT0, 0x3011806ull, l_scom_buffer );

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: getScom (0x3011806ull)");
                break;
            }

            {
                l_scom_buffer.insert<uint64_t> (literal_0xFF00FDFC0003FFFF, 0, 54, 0 );
            }

            l_rc = fapi2::putScom(TGT0, 0x3011806ull, l_scom_buffer);

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: putScom (0x3011806ull)");
                break;
            }
        }
        {
            l_rc = fapi2::getScom( TGT0, 0x3011807ull, l_scom_buffer );

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: getScom (0x3011807ull)");
                break;
            }

            {
                l_scom_buffer.insert<uint64_t> (literal_0xFFFFFEFFFFFF8000, 0, 54, 0 );
            }

            l_rc = fapi2::putScom(TGT0, 0x3011807ull, l_scom_buffer);

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: putScom (0x3011807ull)");
                break;
            }
        }
        fapi2::ATTR_PROC_FABRIC_ADDR_BAR_MODE_Type l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE;
        l_rc = FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_ADDR_BAR_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE);

        if (l_rc)
        {
            FAPI_ERR("ERROR executing: FAPI_ATTR_GET (ATTR_PROC_FABRIC_ADDR_BAR_MODE)");
            break;
        }

        {
            l_rc = fapi2::getScom( TGT0, 0x301184eull, l_scom_buffer );

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: getScom (0x301184eull)");
                break;
            }

            {
                if ((l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_ADDR_BAR_MODE_SMALL_SYSTEM))
                {
                    constexpr auto l_scom_buffer_ON = 0x1;
                    l_scom_buffer.insert<uint64_t> (l_scom_buffer_ON, 13, 1, 63 );
                }
                else if ((l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_ADDR_BAR_MODE_LARGE_SYSTEM))
                {
                    constexpr auto l_scom_buffer_OFF = 0x0;
                    l_scom_buffer.insert<uint64_t> (l_scom_buffer_OFF, 13, 1, 63 );
                }
            }

            l_rc = fapi2::putScom(TGT0, 0x301184eull, l_scom_buffer);

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: putScom (0x301184eull)");
                break;
            }
        }

        {
            l_rc = fapi2::getScom( TGT0, 0x301184full, l_scom_buffer );

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: getScom (0x301184full)");
                break;
            }

            {
                l_scom_buffer.insert<uint64_t> (literal_0x1, 0, 1, 63 );
            }

            l_rc = fapi2::putScom(TGT0, 0x301184full, l_scom_buffer);

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: putScom (0x301184full)");
                break;
            }
        }
    }
    while (0);

    return l_rc;
}
<commit_msg>Fix paranthesis syntax in scom initfiles<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_vas_scom.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9_vas_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr auto literal_0x000001000001FFFF = 0x000001000001FFFF;
constexpr auto literal_0xFF00FDFC0003FFFF = 0xFF00FDFC0003FFFF;
constexpr auto literal_0xFFFFFEFFFFFF8000 = 0xFFFFFEFFFFFF8000;
constexpr auto literal_0x1 = 0x1;

fapi2::ReturnCode p9_vas_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0,
                              const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)
{
    fapi2::ReturnCode l_rc = 0;

    do
    {
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            l_rc = fapi2::getScom( TGT0, 0x3011803ull, l_scom_buffer );

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: getScom (0x3011803ull)");
                break;
            }

            {
                l_scom_buffer.insert<uint64_t> (literal_0x000001000001FFFF, 0, 54, 0 );
            }

            l_rc = fapi2::putScom(TGT0, 0x3011803ull, l_scom_buffer);

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: putScom (0x3011803ull)");
                break;
            }
        }
        {
            l_rc = fapi2::getScom( TGT0, 0x3011806ull, l_scom_buffer );

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: getScom (0x3011806ull)");
                break;
            }

            {
                l_scom_buffer.insert<uint64_t> (literal_0xFF00FDFC0003FFFF, 0, 54, 0 );
            }

            l_rc = fapi2::putScom(TGT0, 0x3011806ull, l_scom_buffer);

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: putScom (0x3011806ull)");
                break;
            }
        }
        {
            l_rc = fapi2::getScom( TGT0, 0x3011807ull, l_scom_buffer );

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: getScom (0x3011807ull)");
                break;
            }

            {
                l_scom_buffer.insert<uint64_t> (literal_0xFFFFFEFFFFFF8000, 0, 54, 0 );
            }

            l_rc = fapi2::putScom(TGT0, 0x3011807ull, l_scom_buffer);

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: putScom (0x3011807ull)");
                break;
            }
        }
        fapi2::ATTR_PROC_FABRIC_ADDR_BAR_MODE_Type l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE;
        l_rc = FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_ADDR_BAR_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE);

        if (l_rc)
        {
            FAPI_ERR("ERROR executing: FAPI_ATTR_GET (ATTR_PROC_FABRIC_ADDR_BAR_MODE)");
            break;
        }

        {
            l_rc = fapi2::getScom( TGT0, 0x301184eull, l_scom_buffer );

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: getScom (0x301184eull)");
                break;
            }

            {
                if ((l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_ADDR_BAR_MODE_SMALL_SYSTEM))
                {
                    constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_ON = 0x1;
                    l_scom_buffer.insert<uint64_t> (l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_ON, 13, 1, 63 );
                }
                else if ((l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_ADDR_BAR_MODE_LARGE_SYSTEM))
                {
                    constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF = 0x0;
                    l_scom_buffer.insert<uint64_t> (l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF, 13, 1, 63 );
                }
            }

            l_rc = fapi2::putScom(TGT0, 0x301184eull, l_scom_buffer);

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: putScom (0x301184eull)");
                break;
            }
        }

        {
            l_rc = fapi2::getScom( TGT0, 0x301184full, l_scom_buffer );

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: getScom (0x301184full)");
                break;
            }

            {
                l_scom_buffer.insert<uint64_t> (literal_0x1, 0, 1, 63 );
            }

            l_rc = fapi2::putScom(TGT0, 0x301184full, l_scom_buffer);

            if (l_rc)
            {
                FAPI_ERR("ERROR executing: putScom (0x301184full)");
                break;
            }
        }
    }
    while (0);

    return l_rc;
}
<|endoftext|>


<commit_before>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5cpp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA  02110-1301 USA
// ===========================================================================
//
// Author: Eugen Wintersberger <eugen.wintersberger@desy.de>
// Created on: Aug 28, 2017
//
#pragma once

#include <h5cpp/datatype/datatype.hpp>
#include <h5cpp/datatype/integer.hpp>
#include <h5cpp/datatype/float.hpp>
#include <h5cpp/datatype/string.hpp>

#include <vector>
#include <array>
#include <string>
#include <type_traits>

namespace hdf5 {
namespace datatype {

//!
//! \brief trait to create HDF5 datatypes
//!
//! This trait provides a static function which creates a new HDF5 data type
//! for a particular C++ type.
//!
//! Specializations for this template exist for the following native types
//!
//! \list \c char, \c unsigned char, \c singed char
//! \list \c double
//!
//! \tparam T type for which to create a new HDF5 data type
template<typename T>
class TypeTrait {
 public:
  //!
  //! \brief subtype of Datatype which will be used
  //!
  using TypeClass = Datatype;

  //!
  //! \brief create the new type instance
  //!
  static TypeClass create(const T & = T());
};

template<>
class TypeTrait<char> {
 public:
  using TypeClass = Integer;
  static TypeClass create(const char & = char()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_CHAR)));
  }
};

template<>
class TypeTrait<unsigned char> {
 public:
  using Type = unsigned char;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_UCHAR)));
  }
};

template<>
class TypeTrait<signed char> {
 public:
  using Type = signed char;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_SCHAR)));
  }
};

template<>
class TypeTrait<short> {
 public:
  using Type = short;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_SHORT)));
  }
};

template<>
class TypeTrait<unsigned short> {
 public:
  using Type = unsigned short;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_USHORT)));
  }
};

template<>
class TypeTrait<int> {
 public:
  using TypeClass = Integer;
  static TypeClass create(const int & = int()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_INT)));
  }
};

template<>
class TypeTrait<unsigned int> {
 public:
  using Type = unsigned int;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_UINT)));
  }
};

template<>
class TypeTrait<long> {
 public:
  using Type = long;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_LONG)));
  }
};

template<>
class TypeTrait<unsigned long> {
 public:
  using Type = unsigned long;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_ULONG)));
  }
};

template<>
class TypeTrait<long long> {
 public:
  using Type = long long;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_LLONG)));
  }
};

template<>
class TypeTrait<unsigned long long> {
 public:
  using Type = unsigned long long;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_ULLONG)));
  }
};

template<>
class TypeTrait<float> {
 public:
  using TypeClass = Float;
  static TypeClass create(const float & = float()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_FLOAT)));
  }
};

template<>
class TypeTrait<double> {
 public:
  using TypeClass = Float;
  static TypeClass create(const double & = double()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_DOUBLE)));
  }
};

template<>
class TypeTrait<long double> {
 public:
  using Type = long double;
  using TypeClass = Float;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_LDOUBLE)));
  }
};

template<>
class TypeTrait<std::string> {
 public:
  using TypeClass = String;
  static TypeClass create(const std::string & = std::string()) {
    return datatype::String::variable();
  }
};

template<typename T>
class TypeTrait<std::vector<T>> {
 public:
  using Type = std::vector<T>;
  using TypeClass = typename TypeTrait<T>::TypeClass;
  static TypeClass create(const Type & = Type()) {
    return TypeTrait<typename std::remove_const<T>::type>::create();
  }
};

template<typename T, size_t N>
class TypeTrait<std::array<T, N>> {
 public:
  using Type = std::array<T, N>;
  using TypeClass = typename TypeTrait<T>::TypeClass;
  static TypeClass create(const Type & = Type()) {
    return TypeTrait<typename std::remove_const<T>::type>::create();
  }
};

template<typename CharT>
class TypeTrait<std::basic_string<CharT>> {
 private:

 public:
  using Type = std::basic_string<CharT>;
  using TypeClass = String;

  static TypeClass create(const Type & = Type()) {
    static_assert(std::is_same<CharT, char>::value, "Only support 8Bit characters");

    String type = String::variable();
    type.encoding(CharacterEncoding::UTF8);
    return type;

  }

};

template<>
class TypeTrait<bool> {
 public:
  using Type = bool;
  using TypeClass = Integer;

  static TypeClass create(const Type & = Type()) {
    return Integer(ObjectHandle(H5Tcopy(H5T_NATIVE_HBOOL)));
  }
};

} // namespace datatype
} // namespace hdf5
<commit_msg>Add traits for std::complex<T> datatype<commit_after>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5cpp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA  02110-1301 USA
// ===========================================================================
//
// Authors: Eugen Wintersberger <eugen.wintersberger@desy.de>
//          Sebastian Koenig <skoenig@ncsu.edu>
// Created on: Aug 28, 2017
//
#pragma once

#include <h5cpp/datatype/datatype.hpp>
#include <h5cpp/datatype/integer.hpp>
#include <h5cpp/datatype/float.hpp>
#include <h5cpp/datatype/string.hpp>
#include <h5cpp/datatype/compound.hpp>

#include <vector>
#include <array>
#include <string>
#include <complex>
#include <type_traits>

namespace hdf5 {
namespace datatype {

//!
//! \brief trait to create HDF5 datatypes
//!
//! This trait provides a static function which creates a new HDF5 data type
//! for a particular C++ type.
//!
//! Specializations for this template exist for the following native types
//!
//! \list \c char, \c unsigned char, \c singed char
//! \list \c double
//!
//! \tparam T type for which to create a new HDF5 data type
template<typename T>
class TypeTrait {
 public:
  //!
  //! \brief subtype of Datatype which will be used
  //!
  using TypeClass = Datatype;

  //!
  //! \brief create the new type instance
  //!
  static TypeClass create(const T & = T());
};

template<>
class TypeTrait<char> {
 public:
  using TypeClass = Integer;
  static TypeClass create(const char & = char()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_CHAR)));
  }
};

template<>
class TypeTrait<unsigned char> {
 public:
  using Type = unsigned char;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_UCHAR)));
  }
};

template<>
class TypeTrait<signed char> {
 public:
  using Type = signed char;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_SCHAR)));
  }
};

template<>
class TypeTrait<short> {
 public:
  using Type = short;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_SHORT)));
  }
};

template<>
class TypeTrait<unsigned short> {
 public:
  using Type = unsigned short;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_USHORT)));
  }
};

template<>
class TypeTrait<int> {
 public:
  using TypeClass = Integer;
  static TypeClass create(const int & = int()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_INT)));
  }
};

template<>
class TypeTrait<unsigned int> {
 public:
  using Type = unsigned int;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_UINT)));
  }
};

template<>
class TypeTrait<long> {
 public:
  using Type = long;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_LONG)));
  }
};

template<>
class TypeTrait<unsigned long> {
 public:
  using Type = unsigned long;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_ULONG)));
  }
};

template<>
class TypeTrait<long long> {
 public:
  using Type = long long;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_LLONG)));
  }
};

template<>
class TypeTrait<unsigned long long> {
 public:
  using Type = unsigned long long;
  using TypeClass = Integer;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_ULLONG)));
  }
};

template<>
class TypeTrait<float> {
 public:
  using TypeClass = Float;
  static TypeClass create(const float & = float()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_FLOAT)));
  }
};

template<>
class TypeTrait<double> {
 public:
  using TypeClass = Float;
  static TypeClass create(const double & = double()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_DOUBLE)));
  }
};

template<>
class TypeTrait<long double> {
 public:
  using Type = long double;
  using TypeClass = Float;
  static TypeClass create(const Type & = Type()) {
    return TypeClass(ObjectHandle(H5Tcopy(H5T_NATIVE_LDOUBLE)));
  }
};

template<>
class TypeTrait<std::string> {
 public:
  using TypeClass = String;
  static TypeClass create(const std::string & = std::string()) {
    return datatype::String::variable();
  }
};

template<typename T>
class TypeTrait<std::vector<T>> {
 public:
  using Type = std::vector<T>;
  using TypeClass = typename TypeTrait<T>::TypeClass;
  static TypeClass create(const Type & = Type()) {
    return TypeTrait<typename std::remove_const<T>::type>::create();
  }
};

template<typename T, size_t N>
class TypeTrait<std::array<T, N>> {
 public:
  using Type = std::array<T, N>;
  using TypeClass = typename TypeTrait<T>::TypeClass;
  static TypeClass create(const Type & = Type()) {
    return TypeTrait<typename std::remove_const<T>::type>::create();
  }
};

template<typename CharT>
class TypeTrait<std::basic_string<CharT>> {
 private:

 public:
  using Type = std::basic_string<CharT>;
  using TypeClass = String;

  static TypeClass create(const Type & = Type()) {
    static_assert(std::is_same<CharT, char>::value, "Only support 8Bit characters");

    String type = String::variable();
    type.encoding(CharacterEncoding::UTF8);
    return type;

  }

};

template<>
class TypeTrait<bool> {
 public:
  using Type = bool;
  using TypeClass = Integer;

  static TypeClass create(const Type & = Type()) {
    return Integer(ObjectHandle(H5Tcopy(H5T_NATIVE_HBOOL)));
  }
};

template<typename T>
class TypeTrait<std::complex<T>>
{
  private:
    using element_type = TypeTrait<T>;

  public:
    using Type = std::complex<T>;
    using TypeClass = Compound;

    static TypeClass create(const Type & = Type())
    {
      datatype::Compound type = datatype::Compound::create(
        sizeof(std::complex<T>));

      type.insert("real", 0, element_type::create(T()));
      type.insert("imag", alignof(T), element_type::create(T()));

      return type;
    }
};

} // namespace datatype
} // namespace hdf5
<|endoftext|>


<commit_before>#include "ViewRobot.h"
#include <KrisLibrary/GLdraw/drawextra.h>
#include <KrisLibrary/Timer.h>
using namespace GLDraw;

const static GLColor grey(0.5,0.5,0.5);
const static GLColor red(1,0,0);
const static GLColor orange(1,0.5,0);
const static GLColor yellow(1,1,0);
const static GLColor purple(0.5,0,1);
const static GLColor lightpurple(0.75,0.5,1);
const static GLColor blue(0,0,1);

struct GLCheckeredSphere
{
  GLCheckeredSphere();
  void Draw();

  Real radius;
  Vector3 center;
  GLColor c1,c2;
  int numSlices,numStacks;
};

GLCheckeredSphere::GLCheckeredSphere()
  :radius(1),center(Zero),numSlices(16),numStacks(8)
{
  c1.set(1,1,1);
  c2.set(0,0,0);
}

//theta is the vertical range, phi is the rotational range
void DrawSphereArc(Real r,Real theta0,Real theta1,Real phi0,Real phi1,int numSlices,int numStacks)
{
  Real thetaInc = (theta1-theta0)/Real(numStacks);
  Real phiInc = (phi1-phi0)/Real(numSlices);
  Real phi=phi0;
  Real theta;
  for(int i=0;i<numSlices;i++,phi+=phiInc) {
    Real x1=Cos(phi);
    Real x2=Cos(phi+phiInc);
    Real y1=Sin(phi);
    Real y2=Sin(phi+phiInc);
    theta=theta0;
    glBegin(GL_TRIANGLE_STRIP);
    for(int j=0;j<=numStacks;j++,theta+=thetaInc) {
      Real cz=Cos(theta);
      Real sz=Sin(theta);
      glNormal3f(x2*sz,y2*sz,cz);
      glVertex3f(r*x2*sz,r*y2*sz,r*cz);
      glNormal3f(x1*sz,y1*sz,cz);
      glVertex3f(r*x1*sz,r*y1*sz,r*cz);
    }
    glEnd();
  }
}

void GLCheckeredSphere::Draw()
{
  glEnable(GL_LIGHTING);
  glPushMatrix();
  {
    glTranslate(center);
    glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,c1.rgba);
    DrawSphereArc(radius, 0,Pi_2,  0,Pi_2,    numSlices/4,numStacks/2);
    DrawSphereArc(radius, 0,Pi_2,  Pi,3*Pi_2, numSlices/4,numStacks/2);
    DrawSphereArc(radius, Pi_2,Pi, Pi_2,Pi,   numSlices/4,numStacks/2);
    DrawSphereArc(radius, Pi_2,Pi, 3*Pi_2,TwoPi,numSlices/4,numStacks/2);
    glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,c2.rgba);
    DrawSphereArc(radius, 0,Pi_2,  Pi_2,Pi,   numSlices/4,numStacks/2);
    DrawSphereArc(radius, 0,Pi_2,  3*Pi_2,TwoPi,numSlices/4,numStacks/2);
    DrawSphereArc(radius, Pi_2,Pi, 0,Pi_2,    numSlices/4,numStacks/2);
    DrawSphereArc(radius, Pi_2,Pi, Pi,3*Pi_2, numSlices/4,numStacks/2);
  }
  glPopMatrix();
}

ViewRobot::ViewRobot(Robot* _robot)
  :robot(_robot)
{
}

ViewRobot::~ViewRobot()
{
}

void ViewRobot::Draw(Robot* _robot)
{
  robot = _robot;
  if(!robot) return;
  Draw();
}

void ViewRobot::SetColors(const GLColor& c)
{
  if(robot) {
    for(size_t i=0;i<robot->links.size();i++) {
      GLDraw::GeometryAppearance& a = Appearance(i);
      a.SetColor(c);
    }
  }
}

void ViewRobot::SetColor(int link,const GLColor& c)
{
  if(robot) {
    GLDraw::GeometryAppearance& a = Appearance(link);
    a.SetColor(c);
  }
}

void ViewRobot::SetGrey() { SetColors(grey); }

void ViewRobot::Draw()
{
  if(!robot) return;

  for(size_t i=0;i<robot->links.size();i++) {
    if(robot->IsGeometryEmpty(i)) continue;
    Matrix4 mat = robot->links[i].T_World;
    glPushMatrix();
    glMultMatrix(mat);
    GLDraw::GeometryAppearance& a = Appearance(i);
    if(a.geom != robot->geometry[i].get()) {
      a.Set(*robot->geometry[i]);
    }
    a.DrawGL();
    glPopMatrix();
  }
}

void ViewRobot::DrawOpaque(bool opaque)
{
  if(!robot) return;

  GLDraw::GeometryAppearance::Element e = (opaque ? GLDraw::GeometryAppearance::ALL_OPAQUE : GLDraw::GeometryAppearance::ALL_TRANSPARENT);
  for(size_t i=0;i<robot->links.size();i++) {
    if(robot->IsGeometryEmpty(i)) continue;
    Matrix4 mat = robot->links[i].T_World;
    glPushMatrix();
    glMultMatrix(mat);
    GLDraw::GeometryAppearance& a = Appearance(i);
    if(a.geom != robot->geometry[i].get()) {
      a.Set(*robot->geometry[i]);
    }
    a.DrawGL(e);
    glPopMatrix();
  }
}

void ViewRobot::DrawLink_Local(int i,bool keepAppearance)
{
  if(!robot || robot->IsGeometryEmpty(i)) return;
  if(keepAppearance) {
    GLDraw::GeometryAppearance& a = Appearance(i);
    if(a.geom != robot->geometry[i].get())
      a.Set(*robot->geometry[i]);
    a.DrawGL();
  }
  else
    draw(*robot->geometry[i]);
}

void ViewRobot::DrawLink_World(int i,bool keepAppearance)
{
  if(!robot) return;
  Matrix4 mat = robot->links[i].T_World;
  glPushMatrix();
  glMultMatrix(mat);
  DrawLink_Local(i,keepAppearance);
  glPopMatrix();
}

void ViewRobot::DrawCenterOfMass(Real radius)
{
  if(!robot) return;
  Vector3 com = robot->GetCOM();

  GLCheckeredSphere sph;
  sph.center = com;
  sph.radius = radius;
  sph.c1.set(1,0,0);
  sph.c2.set(0,0,1);
  sph.Draw();

  glDisable(GL_LIGHTING);
  glColor3f(0,0,1);
  glBegin(GL_LINES);
  glVertex3f(com.x,com.y,com.z);
  glVertex3f(com.x,com.y,0);
  glEnd();
}

void ViewRobot::DrawLinkCenterOfMass(int i,Real radius)
{
  Vector3 com = robot->links[i].T_World*robot->links[i].com;
  GLCheckeredSphere sph;
  sph.center = com;
  sph.radius = radius;
  sph.c1.set(1,0,0);
  sph.c2.set(0,0,1);
  sph.Draw();
}

void ViewRobot::DrawLinkFrames(Real size)
{
  if(!robot) return;
  glDisable(GL_LIGHTING);
  for(size_t i=0;i<robot->links.size();i++) {
    glPushMatrix();
    glMultMatrix((Matrix4)robot->links[i].T_World);
    drawCoords(size);
    glPopMatrix();
  }
}

void ViewRobot::DrawLinkSkeleton()
{
  if(!robot) return;
  glDisable(GL_LIGHTING);
  glColor3f(1,0.5,0);
  glLineWidth(3.0);
  glBegin(GL_LINES);
  for(size_t i=0;i<robot->links.size();i++) {
    if(robot->parents[i] >= 0) {
      glVertex3v(robot->links[robot->parents[i]].T_World.t);
      glVertex3v(robot->links[i].T_World.t);
    }
  }
  glEnd();
  glLineWidth(1.0);
}

void ViewRobot::DrawTorques(const Vector& T)
{
  SetTorqueColors(T);
  Draw();
}

inline void GetTorqueColor(Real t,GLColor& color)
{
  if(t < 0.5) color.set(0.5+t,0.5+t,0.5-t);
  else if(t < 0.75) color.set(1,2-2*t,0);
  else if(t < 1) color.set(1,2-2*t,0);
  else color.set(0.5,0,0);
}

inline bool EqualColor(const GLColor& a,const GLColor& b)
{
  for(int i=0;i<4;i++)
    if(a.rgba[i] != b.rgba[i]) return false;
  return true;
}

void ViewRobot::SetTorqueColors(const Vector& T)
{
  if(T.empty()) {
    SetColors(GLColor(1,0,1));
    return;
  }
  //draw torques
  Assert(T.n == (int)robot->links.size() || T.n == (int)robot->drivers.size());
  if(T.n == (int)robot->links.size()) {
    for(int i=0;i<T.n;i++) {
      GetTorqueColor(T[i],Appearance(i).faceColor);
    }
  }
  else {
    for(int i=0;i<T.n;i++) {
      GLColor c;
      GetTorqueColor(T[i],c);
      for(size_t k=0;k<robot->drivers[i].linkIndices.size();k++)
	Appearance(robot->drivers[i].linkIndices[k]).faceColor = c;
    }
  }
}

GLDraw::GeometryAppearance& ViewRobot::Appearance(int link)
{
  Assert(robot!=NULL);
  if(appearanceStack.empty()) {
    if(robot->geomManagers[link].IsAppearanceShared()) {
      robot->geomManagers[link].SetUniqueAppearance();
    }
    return *robot->geomManagers[link].Appearance();
  }
  return appearanceStack.back()[link];
}

void ViewRobot::PushAppearance()
{
  if(robot==NULL) return;
  vector<GLDraw::GeometryAppearance> app(robot->links.size());
  for(size_t i=0;i<robot->links.size();i++) {
    app[i] = Appearance(i);
    if(Appearance(i).faceDisplayList)
      Assert(app[i].faceDisplayList);
  }
  appearanceStack.push_back(app);
}

void ViewRobot::PopAppearance()
{
  if(!appearanceStack.empty()) {
    //may want to copy back face display lists up the stack
    if(appearanceStack.size()==1) {
      for(size_t i=0;i<robot->links.size();i++) {
        if(!robot->geomManagers[i].Appearance()->faceDisplayList)
          robot->geomManagers[i].Appearance()->faceDisplayList = appearanceStack.back()[i].faceDisplayList;
        if(!robot->geomManagers[i].Appearance()->edgeDisplayList)
          robot->geomManagers[i].Appearance()->edgeDisplayList = appearanceStack.back()[i].edgeDisplayList;
        if(!robot->geomManagers[i].Appearance()->vertexDisplayList)
          robot->geomManagers[i].Appearance()->vertexDisplayList = appearanceStack.back()[i].vertexDisplayList;
        if(!robot->geomManagers[i].Appearance()->silhouetteDisplayList)
          robot->geomManagers[i].Appearance()->silhouetteDisplayList = appearanceStack.back()[i].silhouetteDisplayList;
        if(!robot->geomManagers[i].Appearance()->tempMesh)
          robot->geomManagers[i].Appearance()->tempMesh = appearanceStack.back()[i].tempMesh;
        if(!robot->geomManagers[i].Appearance()->tempMesh2)
          robot->geomManagers[i].Appearance()->tempMesh2 = appearanceStack.back()[i].tempMesh2;
      }
    }
    else {
      size_t n=appearanceStack.size()-2;
      for(size_t i=0;i<robot->links.size();i++) {
        if(!appearanceStack[n][i].faceDisplayList)
          appearanceStack[n][i].faceDisplayList = appearanceStack.back()[i].faceDisplayList;
        if(!appearanceStack[n][i].edgeDisplayList)
          appearanceStack[n][i].edgeDisplayList = appearanceStack.back()[i].edgeDisplayList;
        if(!appearanceStack[n][i].vertexDisplayList)
          appearanceStack[n][i].vertexDisplayList = appearanceStack.back()[i].vertexDisplayList;
        if(!appearanceStack[n][i].silhouetteDisplayList)
          appearanceStack[n][i].silhouetteDisplayList = appearanceStack.back()[i].silhouetteDisplayList;
        if(!appearanceStack[n][i].tempMesh)
          appearanceStack[n][i].tempMesh = appearanceStack.back()[i].tempMesh;
        if(!appearanceStack[n][i].tempMesh2)
          appearanceStack[n][i].tempMesh2 = appearanceStack.back()[i].tempMesh2;
      }
    }
    appearanceStack.resize(appearanceStack.size()-1);
  }
}
void ViewRobot::RestoreAppearance()

{
  appearanceStack.resize(0);
}

vector<GLDraw::GeometryAppearance> ViewRobot::GetAppearance()
{
  vector<GLDraw::GeometryAppearance> res;
  if(!robot) return res;
  res.resize(robot->links.size());
  for(size_t i=0;i<res.size();i++)
    res[i] = Appearance(i);
  return res;
}

void ViewRobot::SetAppearance(const vector<GLDraw::GeometryAppearance>& app)
{
  if(!robot) return;
  Assert(app.size()==robot->links.size());
  for(size_t i=0;i<app.size();i++) {
    Appearance(i) = app[i];
  }
}
<commit_msg>Fixed some performance issues... need to update KrisLibrary for new GeometryAppearance::CopyCache function<commit_after>#include "ViewRobot.h"
#include <KrisLibrary/GLdraw/drawextra.h>
#include <KrisLibrary/Timer.h>
using namespace GLDraw;

const static GLColor grey(0.5,0.5,0.5);
const static GLColor red(1,0,0);
const static GLColor orange(1,0.5,0);
const static GLColor yellow(1,1,0);
const static GLColor purple(0.5,0,1);
const static GLColor lightpurple(0.75,0.5,1);
const static GLColor blue(0,0,1);

struct GLCheckeredSphere
{
  GLCheckeredSphere();
  void Draw();

  Real radius;
  Vector3 center;
  GLColor c1,c2;
  int numSlices,numStacks;
};

GLCheckeredSphere::GLCheckeredSphere()
  :radius(1),center(Zero),numSlices(16),numStacks(8)
{
  c1.set(1,1,1);
  c2.set(0,0,0);
}

//theta is the vertical range, phi is the rotational range
void DrawSphereArc(Real r,Real theta0,Real theta1,Real phi0,Real phi1,int numSlices,int numStacks)
{
  Real thetaInc = (theta1-theta0)/Real(numStacks);
  Real phiInc = (phi1-phi0)/Real(numSlices);
  Real phi=phi0;
  Real theta;
  for(int i=0;i<numSlices;i++,phi+=phiInc) {
    Real x1=Cos(phi);
    Real x2=Cos(phi+phiInc);
    Real y1=Sin(phi);
    Real y2=Sin(phi+phiInc);
    theta=theta0;
    glBegin(GL_TRIANGLE_STRIP);
    for(int j=0;j<=numStacks;j++,theta+=thetaInc) {
      Real cz=Cos(theta);
      Real sz=Sin(theta);
      glNormal3f(x2*sz,y2*sz,cz);
      glVertex3f(r*x2*sz,r*y2*sz,r*cz);
      glNormal3f(x1*sz,y1*sz,cz);
      glVertex3f(r*x1*sz,r*y1*sz,r*cz);
    }
    glEnd();
  }
}

void GLCheckeredSphere::Draw()
{
  glEnable(GL_LIGHTING);
  glPushMatrix();
  {
    glTranslate(center);
    glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,c1.rgba);
    DrawSphereArc(radius, 0,Pi_2,  0,Pi_2,    numSlices/4,numStacks/2);
    DrawSphereArc(radius, 0,Pi_2,  Pi,3*Pi_2, numSlices/4,numStacks/2);
    DrawSphereArc(radius, Pi_2,Pi, Pi_2,Pi,   numSlices/4,numStacks/2);
    DrawSphereArc(radius, Pi_2,Pi, 3*Pi_2,TwoPi,numSlices/4,numStacks/2);
    glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,c2.rgba);
    DrawSphereArc(radius, 0,Pi_2,  Pi_2,Pi,   numSlices/4,numStacks/2);
    DrawSphereArc(radius, 0,Pi_2,  3*Pi_2,TwoPi,numSlices/4,numStacks/2);
    DrawSphereArc(radius, Pi_2,Pi, 0,Pi_2,    numSlices/4,numStacks/2);
    DrawSphereArc(radius, Pi_2,Pi, Pi,3*Pi_2, numSlices/4,numStacks/2);
  }
  glPopMatrix();
}

ViewRobot::ViewRobot(Robot* _robot)
  :robot(_robot)
{
}

ViewRobot::~ViewRobot()
{
}

void ViewRobot::Draw(Robot* _robot)
{
  robot = _robot;
  if(!robot) return;
  Draw();
}

void ViewRobot::SetColors(const GLColor& c)
{
  if(robot) {
    for(size_t i=0;i<robot->links.size();i++) {
      GLDraw::GeometryAppearance& a = Appearance(i);
      a.SetColor(c);
    }
  }
}

void ViewRobot::SetColor(int link,const GLColor& c)
{
  if(robot) {
    GLDraw::GeometryAppearance& a = Appearance(link);
    a.SetColor(c);
  }
}

void ViewRobot::SetGrey() { SetColors(grey); }

void ViewRobot::Draw()
{
  if(!robot) return;

  for(size_t i=0;i<robot->links.size();i++) {
    if(robot->IsGeometryEmpty(i)) continue;
    //TODO: why does this sanity check need to be here?  Example: TRINA_with_greflex.rob
    if(robot->geomManagers[i].Appearance()->geom != robot->geometry[i].get())
      robot->geomManagers[i].Appearance()->Set(*robot->geometry[i]);
    Matrix4 mat = robot->links[i].T_World;
    glPushMatrix();
    glMultMatrix(mat);
    GLDraw::GeometryAppearance& a = Appearance(i);
    if(a.geom != robot->geometry[i].get())
      a.Set(*robot->geometry[i]);
    a.DrawGL();
    glPopMatrix();
  }
}

void ViewRobot::DrawOpaque(bool opaque)
{
  if(!robot) return;

  GLDraw::GeometryAppearance::Element e = (opaque ? GLDraw::GeometryAppearance::ALL_OPAQUE : GLDraw::GeometryAppearance::ALL_TRANSPARENT);
  for(size_t i=0;i<robot->links.size();i++) {
    if(robot->IsGeometryEmpty(i)) continue;
    Matrix4 mat = robot->links[i].T_World;
    glPushMatrix();
    glMultMatrix(mat);
    GLDraw::GeometryAppearance& a = Appearance(i);
    if(a.geom != robot->geometry[i].get()) {
      a.Set(*robot->geometry[i]);
    }
    a.DrawGL(e);
    glPopMatrix();
  }
}

void ViewRobot::DrawLink_Local(int i,bool keepAppearance)
{
  if(!robot || robot->IsGeometryEmpty(i)) return;
  if(keepAppearance) {
    GLDraw::GeometryAppearance& a = Appearance(i);
    if(a.geom != robot->geometry[i].get())
      a.Set(*robot->geometry[i]);
    a.DrawGL();
  }
  else
    draw(*robot->geometry[i]);
}

void ViewRobot::DrawLink_World(int i,bool keepAppearance)
{
  if(!robot) return;
  Matrix4 mat = robot->links[i].T_World;
  glPushMatrix();
  glMultMatrix(mat);
  DrawLink_Local(i,keepAppearance);
  glPopMatrix();
}

void ViewRobot::DrawCenterOfMass(Real radius)
{
  if(!robot) return;
  Vector3 com = robot->GetCOM();

  GLCheckeredSphere sph;
  sph.center = com;
  sph.radius = radius;
  sph.c1.set(1,0,0);
  sph.c2.set(0,0,1);
  sph.Draw();

  glDisable(GL_LIGHTING);
  glColor3f(0,0,1);
  glBegin(GL_LINES);
  glVertex3f(com.x,com.y,com.z);
  glVertex3f(com.x,com.y,0);
  glEnd();
}

void ViewRobot::DrawLinkCenterOfMass(int i,Real radius)
{
  Vector3 com = robot->links[i].T_World*robot->links[i].com;
  GLCheckeredSphere sph;
  sph.center = com;
  sph.radius = radius;
  sph.c1.set(1,0,0);
  sph.c2.set(0,0,1);
  sph.Draw();
}

void ViewRobot::DrawLinkFrames(Real size)
{
  if(!robot) return;
  glDisable(GL_LIGHTING);
  for(size_t i=0;i<robot->links.size();i++) {
    glPushMatrix();
    glMultMatrix((Matrix4)robot->links[i].T_World);
    drawCoords(size);
    glPopMatrix();
  }
}

void ViewRobot::DrawLinkSkeleton()
{
  if(!robot) return;
  glDisable(GL_LIGHTING);
  glColor3f(1,0.5,0);
  glLineWidth(3.0);
  glBegin(GL_LINES);
  for(size_t i=0;i<robot->links.size();i++) {
    if(robot->parents[i] >= 0) {
      glVertex3v(robot->links[robot->parents[i]].T_World.t);
      glVertex3v(robot->links[i].T_World.t);
    }
  }
  glEnd();
  glLineWidth(1.0);
}

void ViewRobot::DrawTorques(const Vector& T)
{
  SetTorqueColors(T);
  Draw();
}

inline void GetTorqueColor(Real t,GLColor& color)
{
  if(t < 0.5) color.set(0.5+t,0.5+t,0.5-t);
  else if(t < 0.75) color.set(1,2-2*t,0);
  else if(t < 1) color.set(1,2-2*t,0);
  else color.set(0.5,0,0);
}

inline bool EqualColor(const GLColor& a,const GLColor& b)
{
  for(int i=0;i<4;i++)
    if(a.rgba[i] != b.rgba[i]) return false;
  return true;
}

void ViewRobot::SetTorqueColors(const Vector& T)
{
  if(T.empty()) {
    SetColors(GLColor(1,0,1));
    return;
  }
  //draw torques
  Assert(T.n == (int)robot->links.size() || T.n == (int)robot->drivers.size());
  if(T.n == (int)robot->links.size()) {
    for(int i=0;i<T.n;i++) {
      GetTorqueColor(T[i],Appearance(i).faceColor);
    }
  }
  else {
    for(int i=0;i<T.n;i++) {
      GLColor c;
      GetTorqueColor(T[i],c);
      for(size_t k=0;k<robot->drivers[i].linkIndices.size();k++)
	Appearance(robot->drivers[i].linkIndices[k]).faceColor = c;
    }
  }
}

GLDraw::GeometryAppearance& ViewRobot::Appearance(int link)
{
  Assert(robot!=NULL);
  if(appearanceStack.empty()) {
    if(robot->geomManagers[link].IsAppearanceShared()) {
      robot->geomManagers[link].SetUniqueAppearance();
    }
    return *robot->geomManagers[link].Appearance();
  }
  return appearanceStack.back()[link];
}

void ViewRobot::PushAppearance()
{
  if(robot==NULL) return;
  vector<GLDraw::GeometryAppearance> app(robot->links.size());
  for(size_t i=0;i<robot->links.size();i++) {
    app[i] = Appearance(i);
    if(Appearance(i).faceDisplayList)
      Assert(app[i].faceDisplayList);
  }
  appearanceStack.push_back(app);
}

void ViewRobot::PopAppearance()
{
  if(!appearanceStack.empty()) {
    //may want to copy back face display lists up the stack
    if(appearanceStack.size()==1) {
      for(size_t i=0;i<robot->links.size();i++) {
        ManagedGeometry::AppearancePtr app = robot->geomManagers[i].Appearance();
        const GLDraw::GeometryAppearance& oldapp = appearanceStack.back()[i];
        app->CopyCache(oldapp);
      }
    }
    else {
      size_t n=appearanceStack.size()-2;
      for(size_t i=0;i<robot->links.size();i++) {
        GLDraw::GeometryAppearance& app = appearanceStack[n][i];
        const GLDraw::GeometryAppearance& oldapp = appearanceStack.back()[i];
        app.CopyCache(oldapp);
      }
    }
    appearanceStack.resize(appearanceStack.size()-1);
  }
}

void ViewRobot::RestoreAppearance()
{
  appearanceStack.resize(0);
}

vector<GLDraw::GeometryAppearance> ViewRobot::GetAppearance()
{
  vector<GLDraw::GeometryAppearance> res;
  if(!robot) return res;
  res.resize(robot->links.size());
  for(size_t i=0;i<res.size();i++)
    res[i] = Appearance(i);
  return res;
}

void ViewRobot::SetAppearance(const vector<GLDraw::GeometryAppearance>& app)
{
  if(!robot) return;
  Assert(app.size()==robot->links.size());
  for(size_t i=0;i<app.size();i++) {
    Appearance(i).CopyMaterial(app[i]);
    Appearance(i).CopyCache(app[i],true);
  }
}
<|endoftext|>


<commit_before>// This code is based on Sabberstone project.
// Copyright (c) 2017-2018 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <hspp/Actions/Attack.hpp>

namespace Hearthstonepp::Generic
{
void Attack(Player& player, Character* source, Character* target)
{
    (void)player;
    (void)source;
    (void)target;
}
}  // namespace Hearthstonepp::Generic<commit_msg>[ci skip] feat(game-state): Copy code from CombatTask<commit_after>// This code is based on Sabberstone project.
// Copyright (c) 2017-2018 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <hspp/Actions/Attack.hpp>
#include <hspp/Tasks/SimpleTasks/DestroyTask.hpp>
#include <hspp/Tasks/SimpleTasks/FreezeTask.hpp>
#include <hspp/Tasks/SimpleTasks/PoisonousTask.hpp>

namespace Hearthstonepp::Generic
{
void Attack(Player& player, Character* source, Character* target)
{
    if (!source->CanAttack() ||
        !source->IsValidCombatTarget(player.GetOpponent(), target))
    {
        return;
    }

    const std::size_t targetAttack = target->GetAttack();
    const std::size_t sourceAttack = source->GetAttack();

    const std::size_t targetDamage = target->TakeDamage(*source, sourceAttack);
    const bool isTargetDamaged = targetDamage > 0;

    // Destroy target if attacker is poisonous
    if (isTargetDamaged && source->GetGameTag(GameTag::POISONOUS) == 1)
    {
        SimpleTasks::PoisonousTask(target).Run(player);
    }

    // Freeze target if attacker is freezer
    if (isTargetDamaged && source->GetGameTag(GameTag::FREEZE) == 1)
    {
        SimpleTasks::FreezeTask(EntityType::TARGET, target).Run(player);
    }

    // Ignore damage from defenders with 0 attack
    if (targetAttack > 0)
    {
        const std::size_t sourceDamage =
            source->TakeDamage(*target, targetAttack);
        const bool isSourceDamaged = sourceDamage > 0;

        // Destroy source if defender is poisonous
        if (isSourceDamaged && target->GetGameTag(GameTag::POISONOUS) == 1)
        {
            SimpleTasks::PoisonousTask(source).Run(player);
        }

        // Freeze source if defender is freezer
        if (isSourceDamaged && target->GetGameTag(GameTag::FREEZE) == 1)
        {
            SimpleTasks::FreezeTask(EntityType::SOURCE, source).Run(player);
        }
    }

    // Remove stealth ability if attacker has it
    if (source->GetGameTag(GameTag::STEALTH) == 1)
    {
        source->SetGameTag(GameTag::STEALTH, 0);
    }

    // Remove durability from weapon if hero attack
    const Hero* hero = dynamic_cast<Hero*>(source);
    if (hero != nullptr && hero->weapon != nullptr &&
        hero->weapon->GetGameTag(GameTag::IMMUNE) == 0)
    {
        hero->weapon->durability -= 1;

        // Destroy weapon if durability is 0
        if (hero->weapon->durability == 0)
        {
            SimpleTasks::DestroyTask(EntityType::WEAPON).Run(player);
        }
    }

    source->numAttacked++;

    if ((source->numAttacked >= 1 &&
         source->GetGameTag(GameTag::WINDFURY) == 0) ||
        (source->numAttacked >= 2 &&
         source->GetGameTag(GameTag::WINDFURY) == 1))
    {
        source->SetGameTag(GameTag::EXHAUSTED, 1);
    }

    if (source->isDestroyed)
    {
        source->Destroy();
    }

    if (target->isDestroyed)
    {
        target->Destroy();
    }
}
}  // namespace Hearthstonepp::Generic<|endoftext|>


<commit_before>
// QT includes
#include <QCoreApplication>
#include <QImage>

// getoptPlusPLus includes
#include <getoptPlusPlus/getoptpp.h>

#include "ProtoWrapper.h"
#include "X11Wrapper.h"

using namespace vlofgren;

// save the image as screenshot
void saveScreenshot(const char * filename, const Image<ColorRgb> & image)
{
	// store as PNG
	QImage pngImage((const uint8_t *) image.memptr(), image.width(), image.height(), 3*image.width(), QImage::Format_RGB888);
	pngImage.save(filename);
}

int main(int argc, char ** argv)
{
	QCoreApplication app(argc, argv);

	try
	{
		// create the option parser and initialize all parameters
		OptionsParser optionParser("X11 capture application for Hyperion");
		ParameterSet & parameters = optionParser.getParameters();

		IntParameter           & argCropWidth       = parameters.add<IntParameter>          (0x0, "crop-width",       "Number of pixels to crop from the left and right sides in the picture before decimation [default=0]");
		IntParameter           & argCropHeight      = parameters.add<IntParameter>          (0x0, "crop-height",      "Number of pixels to crop from the top and the bottom in the picture before decimation [default=0]");
		IntParameter           & argSizeDecimation  = parameters.add<IntParameter>          ('s', "size-decimator",   "Decimation factor for the output size [default=1]");
		SwitchParameter<>      & argScreenshot      = parameters.add<SwitchParameter<>>     (0x0, "screenshot",       "Take a single screenshot, save it to file and quit");
		StringParameter        & argAddress         = parameters.add<StringParameter>       ('a', "address",          "Set the address of the hyperion server [default: 127.0.0.1:19445]");
		IntParameter           & argPriority        = parameters.add<IntParameter>          ('p', "priority",         "Use the provided priority channel (the lower the number, the higher the priority) [default: 800]");
		SwitchParameter<>      & argSkipReply       = parameters.add<SwitchParameter<>>     (0x0, "skip-reply",       "Do not receive and check reply messages from Hyperion");
		SwitchParameter<>      & argHelp            = parameters.add<SwitchParameter<>>     ('h', "help",             "Show this help message and exit");

		// set defaults
		argCropWidth.setDefault(0);
		argCropHeight.setDefault(0);
		argSizeDecimation.setDefault(1);
		argAddress.setDefault("127.0.0.1:19445");
		argPriority.setDefault(800);

		// parse all options
		optionParser.parse(argc, const_cast<const char **>(argv));

		// check if we need to display the usage. exit if we do.
		if (argHelp.isSet())
		{
			optionParser.usage();
			return 0;
		}

		// Create the X11 grabbing stuff
		X11Wrapper x11Wrapper(argCropWidth.getValue(), argCropHeight.getValue(), argSizeDecimation.getValue());

		if (argScreenshot.isSet())
		{
			// Capture a single screenshot and finish
			const Image<ColorRgb> & screenshot = x11Wrapper.getScreenshot();
			saveScreenshot("screenshot.png", screenshot);
		}
		else
		{
			// Create the Proto-connection with hyperiond
			ProtoWrapper protoWrapper("127.0.0.1:19445", argSkipReply.isSet());

			// Connect the screen capturing to the proto processing
			QObject::connect(&x11Wrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &protoWrapper, SLOT(process(Image<ColorRgb>)));

			// Start the capturing
			x11Wrapper.start();

			// Start the application
			app.exec();
		}
	}
	catch (const std::runtime_error & e)
	{
		// An error occured. Display error and quit
		std::cerr << e.what() << std::endl;
		return -1;
	}

	return 0;
}
<commit_msg>Fixed correct addres configuration<commit_after>
// QT includes
#include <QCoreApplication>
#include <QImage>

// getoptPlusPLus includes
#include <getoptPlusPlus/getoptpp.h>

#include "ProtoWrapper.h"
#include "X11Wrapper.h"

using namespace vlofgren;

// save the image as screenshot
void saveScreenshot(const char * filename, const Image<ColorRgb> & image)
{
	// store as PNG
	QImage pngImage((const uint8_t *) image.memptr(), image.width(), image.height(), 3*image.width(), QImage::Format_RGB888);
	pngImage.save(filename);
}

int main(int argc, char ** argv)
{
	QCoreApplication app(argc, argv);

	try
	{
		// create the option parser and initialize all parameters
		OptionsParser optionParser("X11 capture application for Hyperion");
		ParameterSet & parameters = optionParser.getParameters();

		IntParameter           & argCropWidth       = parameters.add<IntParameter>          (0x0, "crop-width",       "Number of pixels to crop from the left and right sides in the picture before decimation [default=0]");
		IntParameter           & argCropHeight      = parameters.add<IntParameter>          (0x0, "crop-height",      "Number of pixels to crop from the top and the bottom in the picture before decimation [default=0]");
		IntParameter           & argSizeDecimation  = parameters.add<IntParameter>          ('s', "size-decimator",   "Decimation factor for the output size [default=1]");
		SwitchParameter<>      & argScreenshot      = parameters.add<SwitchParameter<>>     (0x0, "screenshot",       "Take a single screenshot, save it to file and quit");
		StringParameter        & argAddress         = parameters.add<StringParameter>       ('a', "address",          "Set the address of the hyperion server [default: 127.0.0.1:19445]");
		IntParameter           & argPriority        = parameters.add<IntParameter>          ('p', "priority",         "Use the provided priority channel (the lower the number, the higher the priority) [default: 800]");
		SwitchParameter<>      & argSkipReply       = parameters.add<SwitchParameter<>>     (0x0, "skip-reply",       "Do not receive and check reply messages from Hyperion");
		SwitchParameter<>      & argHelp            = parameters.add<SwitchParameter<>>     ('h', "help",             "Show this help message and exit");

		// set defaults
		argCropWidth.setDefault(0);
		argCropHeight.setDefault(0);
		argSizeDecimation.setDefault(1);
		argAddress.setDefault("127.0.0.1:19445");
		argPriority.setDefault(800);

		// parse all options
		optionParser.parse(argc, const_cast<const char **>(argv));

		// check if we need to display the usage. exit if we do.
		if (argHelp.isSet())
		{
			optionParser.usage();
			return 0;
		}

		// Create the X11 grabbing stuff
		X11Wrapper x11Wrapper(argCropWidth.getValue(), argCropHeight.getValue(), argSizeDecimation.getValue());

		if (argScreenshot.isSet())
		{
			// Capture a single screenshot and finish
			const Image<ColorRgb> & screenshot = x11Wrapper.getScreenshot();
			saveScreenshot("screenshot.png", screenshot);
		}
		else
		{
			// Create the Proto-connection with hyperiond
			ProtoWrapper protoWrapper(argAddress.getValue(), argSkipReply.isSet());

			// Connect the screen capturing to the proto processing
			QObject::connect(&x11Wrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &protoWrapper, SLOT(process(Image<ColorRgb>)));

			// Start the capturing
			x11Wrapper.start();

			// Start the application
			app.exec();
		}
	}
	catch (const std::runtime_error & e)
	{
		// An error occured. Display error and quit
		std::cerr << e.what() << std::endl;
		return -1;
	}

	return 0;
}
<|endoftext|>