<commit_before>/*
 * ProbingPT.cpp
 *
 *  Created on: 3 Nov 2015
 *      Author: hieu
 */
#include <boost/foreach.hpp>
#include "ProbingPT.h"
#include "../System.h"
#include "../Scores.h"
#include "../FF/FeatureFunctions.h"
#include "../Search/Manager.h"
#include "../legacy/FactorCollection.h"
#include "../legacy/ProbingPT/quering.hh"
#include "../legacy/Util2.h"

using namespace std;

namespace Moses2
{

ProbingPT::ProbingPT(size_t startInd, const std::string &line)
:PhraseTable(startInd, line)
{
	  ReadParameters();
}

ProbingPT::~ProbingPT()
{
  delete m_engine;
}

void ProbingPT::Load(System &system)
{
  m_engine = new QueryEngine(m_path.c_str());

  m_unkId = 456456546456;

  FactorCollection &vocab = system.GetVocab();

  // source vocab
  const std::map<uint64_t, std::string> &sourceVocab = m_engine->getSourceVocab();
  std::map<uint64_t, std::string>::const_iterator iterSource;
  for (iterSource = sourceVocab.begin(); iterSource != sourceVocab.end(); ++iterSource) {
	const string &wordStr = iterSource->second;
	const Factor *factor = vocab.AddFactor(wordStr, system);

	uint64_t probingId = iterSource->first;
	size_t factorId = factor->GetId();

	if (factorId >= m_sourceVocab.size()) {
		m_sourceVocab.resize(factorId + 1, m_unkId);
	}
	m_sourceVocab[factorId] = probingId;
  }

  // target vocab
  const std::map<unsigned int, std::string> &probingVocab = m_engine->getVocab();
  std::map<unsigned int, std::string>::const_iterator iter;
  for (iter = probingVocab.begin(); iter != probingVocab.end(); ++iter) {
	const string &wordStr = iter->second;
	const Factor *factor = vocab.AddFactor(wordStr, system);

	unsigned int probingId = iter->first;

	if (probingId >= m_targetVocab.size()) {
		m_targetVocab.resize(probingId + 1, NULL);
	}
	m_targetVocab[probingId] = factor;
  }
}

void ProbingPT::Lookup(const Manager &mgr, InputPaths &inputPaths) const
{
  RecycleData &recycler = GetThreadSpecificObj(m_recycleData);

  BOOST_FOREACH(InputPath &path, inputPaths) {
	TargetPhrases *tpsPtr;
	tpsPtr = Lookup(mgr, mgr.GetPool(), path, recycler);
	path.AddTargetPhrases(*this, tpsPtr);
  }
}

TargetPhrases* ProbingPT::Lookup(const Manager &mgr,
		MemPool &pool,
		InputPath &inputPath,
		RecycleData &recycler) const
{
	const Phrase &sourcePhrase = inputPath.subPhrase;
	TargetPhrases *ret = CreateTargetPhrase(pool, mgr.system, sourcePhrase, recycler);
	return ret;
}

TargetPhrases* ProbingPT::CreateTargetPhrase(MemPool &pool,
		const System &system,
		const Phrase &sourcePhrase,
		RecycleData &recycler) const
{

  // create a target phrase from the 1st word of the source, prefix with 'ProbingPT:'
  size_t sourceSize = sourcePhrase.GetSize();
	assert(sourceSize);

  TargetPhrases *tps = NULL;
  uint64_t probingSource[sourceSize];
  bool ok;
  ConvertToProbingSourcePhrase(sourcePhrase, ok, probingSource);
  if (!ok) {
    // source phrase contains a word unknown in the pt.
    // We know immediately there's no translation for it
    return tps;
  }

  std::pair<bool, std::vector<target_text*>* > query_result;

  //Actual lookup
  query_result = m_engine->query(probingSource, sourceSize, recycler);

  if (query_result.first) {
    //m_engine->printTargetInfo(query_result.second);
	const std::vector<target_text*> &probingTargetPhrases = *query_result.second;
	tps = new (pool.Allocate<TargetPhrases>()) TargetPhrases(pool, probingTargetPhrases.size());

    for (size_t i = 0; i < probingTargetPhrases.size(); ++i) {
      target_text *probingTargetPhrase = probingTargetPhrases[i];
      TargetPhrase *tp = CreateTargetPhrase(pool, system, sourcePhrase, *probingTargetPhrase);

      tps->AddTargetPhrase(*tp);

      recycler.tt.Add(probingTargetPhrase);
    }

    recycler.tts.Add(probingTargetPhrases);

    tps->SortAndPrune(m_tableLimit);
    system.featureFunctions.EvaluateAfterTablePruning(pool, *tps, sourcePhrase);
  }
  else {
	  assert(query_result.second.size() == 0);
  }

  return tps;

}

TargetPhrase *ProbingPT::CreateTargetPhrase(MemPool &pool, const System &system, const Phrase &sourcePhrase, const target_text &probingTargetPhrase) const
{

  const std::vector<unsigned int> &probingPhrase = probingTargetPhrase.target_phrase;
  size_t size = probingPhrase.size();

  TargetPhrase *tp = new (pool.Allocate<TargetPhrase>()) TargetPhrase(pool, system, size);

  // words
  for (size_t i = 0; i < size; ++i) {
    uint64_t probingId = probingPhrase[i];
    const Factor *factor = GetTargetFactor(probingId);
    assert(factor);

    Word &word = (*tp)[i];
    word[0] = factor;
  }

  // score for this phrase table
  SCORE scores[probingTargetPhrase.prob.size()];
  std::copy(probingTargetPhrase.prob.begin(), probingTargetPhrase.prob.end(), scores);
  std::transform(scores, scores + probingTargetPhrase.prob.size(), scores, TransformScore);
  std::transform(scores, scores + probingTargetPhrase.prob.size(), scores, FloorScore);
  tp->GetScores().PlusEquals(system, *this, scores);

  // extra scores
  //cerr << "probingTargetPhrase.prob.size()=" << probingTargetPhrase.prob.size() << endl;
  if (probingTargetPhrase.prob.size() > m_numScores) {
	  // we have extra scores, possibly for lex ro. Keep them in the target phrase.
	  size_t numExtraScores = probingTargetPhrase.prob.size() - m_numScores;
	  tp->scoreProperties = pool.Allocate<SCORE>(numExtraScores);
	  memcpy(tp->scoreProperties, scores + m_numScores, sizeof(SCORE) * numExtraScores);

	  /*
	  for (size_t i = 0; i < probingTargetPhrase.prob.size(); ++i) {
		  cerr << probingTargetPhrase.prob[i] << " ";
	  }
	  cerr << endl;

	  for (size_t i = 0; i < probingTargetPhrase.prob.size(); ++i) {
		  cerr << scores[i] << " ";
	  }
	  cerr << endl;

	  for (size_t i = 0; i < numExtraScores; ++i) {
		  cerr << tp->scoreProperties[i] << " ";
	  }
	  cerr << endl;
	  */
  }

//  // alignment
//  /*
//  const std::vector<unsigned char> &alignments = probingTargetPhrase.word_all1;
//
//  AlignmentInfo &aligns = tp->GetAlignTerm();
//  for (size_t i = 0; i < alignS.size(); i += 2 ) {
//    aligns.Add((size_t) alignments[i], (size_t) alignments[i+1]);
//  }
//  */

  // score of all other ff when this rule is being loaded
  const FeatureFunctions &ffs = system.featureFunctions;
  ffs.EvaluateInIsolation(pool, system, sourcePhrase, *tp);
  return tp;

}

void ProbingPT::ConvertToProbingSourcePhrase(const Phrase &sourcePhrase, bool &ok, uint64_t probingSource[]) const
{

  size_t size = sourcePhrase.GetSize();
  for (size_t i = 0; i < size; ++i) {
    const Factor *factor = sourcePhrase[i][0];
    uint64_t probingId = GetSourceProbingId(factor);
    if (probingId == m_unkId) {
      ok = false;
      return;
    } else {
      probingSource[i] = probingId;
    }
  }

  ok = true;
}

void ProbingPT::GetScoresProperty(const std::string &key, size_t ind, SCORE *scoreArr)
		{

		}

}

<commit_msg>Revert "recycle query_result"<commit_after>/*
 * ProbingPT.cpp
 *
 *  Created on: 3 Nov 2015
 *      Author: hieu
 */
#include <boost/foreach.hpp>
#include "ProbingPT.h"
#include "../System.h"
#include "../Scores.h"
#include "../FF/FeatureFunctions.h"
#include "../Search/Manager.h"
#include "../legacy/FactorCollection.h"
#include "../legacy/ProbingPT/quering.hh"
#include "../legacy/Util2.h"

using namespace std;

namespace Moses2
{

ProbingPT::ProbingPT(size_t startInd, const std::string &line)
:PhraseTable(startInd, line)
{
	  ReadParameters();
}

ProbingPT::~ProbingPT()
{
  delete m_engine;
}

void ProbingPT::Load(System &system)
{
  m_engine = new QueryEngine(m_path.c_str());

  m_unkId = 456456546456;

  FactorCollection &vocab = system.GetVocab();

  // source vocab
  const std::map<uint64_t, std::string> &sourceVocab = m_engine->getSourceVocab();
  std::map<uint64_t, std::string>::const_iterator iterSource;
  for (iterSource = sourceVocab.begin(); iterSource != sourceVocab.end(); ++iterSource) {
	const string &wordStr = iterSource->second;
	const Factor *factor = vocab.AddFactor(wordStr, system);

	uint64_t probingId = iterSource->first;
	size_t factorId = factor->GetId();

	if (factorId >= m_sourceVocab.size()) {
		m_sourceVocab.resize(factorId + 1, m_unkId);
	}
	m_sourceVocab[factorId] = probingId;
  }

  // target vocab
  const std::map<unsigned int, std::string> &probingVocab = m_engine->getVocab();
  std::map<unsigned int, std::string>::const_iterator iter;
  for (iter = probingVocab.begin(); iter != probingVocab.end(); ++iter) {
	const string &wordStr = iter->second;
	const Factor *factor = vocab.AddFactor(wordStr, system);

	unsigned int probingId = iter->first;

	if (probingId >= m_targetVocab.size()) {
		m_targetVocab.resize(probingId + 1, NULL);
	}
	m_targetVocab[probingId] = factor;
  }
}

void ProbingPT::Lookup(const Manager &mgr, InputPaths &inputPaths) const
{
  RecycleData &recycler = GetThreadSpecificObj(m_recycleData);

  BOOST_FOREACH(InputPath &path, inputPaths) {
	TargetPhrases *tpsPtr;
	tpsPtr = Lookup(mgr, mgr.GetPool(), path, recycler);
	path.AddTargetPhrases(*this, tpsPtr);
  }
}

TargetPhrases* ProbingPT::Lookup(const Manager &mgr,
		MemPool &pool,
		InputPath &inputPath,
		RecycleData &recycler) const
{
	const Phrase &sourcePhrase = inputPath.subPhrase;
	TargetPhrases *ret = CreateTargetPhrase(pool, mgr.system, sourcePhrase, recycler);
	return ret;
}

TargetPhrases* ProbingPT::CreateTargetPhrase(MemPool &pool,
		const System &system,
		const Phrase &sourcePhrase,
		RecycleData &recycler) const
{

  // create a target phrase from the 1st word of the source, prefix with 'ProbingPT:'
  size_t sourceSize = sourcePhrase.GetSize();
	assert(sourceSize);

  TargetPhrases *tps = NULL;
  uint64_t probingSource[sourceSize];
  bool ok;
  ConvertToProbingSourcePhrase(sourcePhrase, ok, probingSource);
  if (!ok) {
    // source phrase contains a word unknown in the pt.
    // We know immediately there's no translation for it
    return tps;
  }

  std::pair<bool, std::vector<target_text*>* > query_result;

  //Actual lookup
  query_result = m_engine->query(probingSource, sourceSize, recycler);

  if (query_result.first) {
    //m_engine->printTargetInfo(query_result.second);
	const std::vector<target_text*> &probingTargetPhrases = *query_result.second;
	tps = new (pool.Allocate<TargetPhrases>()) TargetPhrases(pool, probingTargetPhrases.size());

    for (size_t i = 0; i < probingTargetPhrases.size(); ++i) {
      target_text *probingTargetPhrase = probingTargetPhrases[i];
      TargetPhrase *tp = CreateTargetPhrase(pool, system, sourcePhrase, *probingTargetPhrase);

      tps->AddTargetPhrase(*tp);

      recycler.tt.Add(probingTargetPhrase);
    }

    tps->SortAndPrune(m_tableLimit);
    system.featureFunctions.EvaluateAfterTablePruning(pool, *tps, sourcePhrase);
  }
  else {
	  assert(query_result.second.size() == 0);
  }

  return tps;

}

TargetPhrase *ProbingPT::CreateTargetPhrase(MemPool &pool, const System &system, const Phrase &sourcePhrase, const target_text &probingTargetPhrase) const
{

  const std::vector<unsigned int> &probingPhrase = probingTargetPhrase.target_phrase;
  size_t size = probingPhrase.size();

  TargetPhrase *tp = new (pool.Allocate<TargetPhrase>()) TargetPhrase(pool, system, size);

  // words
  for (size_t i = 0; i < size; ++i) {
    uint64_t probingId = probingPhrase[i];
    const Factor *factor = GetTargetFactor(probingId);
    assert(factor);

    Word &word = (*tp)[i];
    word[0] = factor;
  }

  // score for this phrase table
  SCORE scores[probingTargetPhrase.prob.size()];
  std::copy(probingTargetPhrase.prob.begin(), probingTargetPhrase.prob.end(), scores);
  std::transform(scores, scores + probingTargetPhrase.prob.size(), scores, TransformScore);
  std::transform(scores, scores + probingTargetPhrase.prob.size(), scores, FloorScore);
  tp->GetScores().PlusEquals(system, *this, scores);

  // extra scores
  //cerr << "probingTargetPhrase.prob.size()=" << probingTargetPhrase.prob.size() << endl;
  if (probingTargetPhrase.prob.size() > m_numScores) {
	  // we have extra scores, possibly for lex ro. Keep them in the target phrase.
	  size_t numExtraScores = probingTargetPhrase.prob.size() - m_numScores;
	  tp->scoreProperties = pool.Allocate<SCORE>(numExtraScores);
	  memcpy(tp->scoreProperties, scores + m_numScores, sizeof(SCORE) * numExtraScores);

	  /*
	  for (size_t i = 0; i < probingTargetPhrase.prob.size(); ++i) {
		  cerr << probingTargetPhrase.prob[i] << " ";
	  }
	  cerr << endl;

	  for (size_t i = 0; i < probingTargetPhrase.prob.size(); ++i) {
		  cerr << scores[i] << " ";
	  }
	  cerr << endl;

	  for (size_t i = 0; i < numExtraScores; ++i) {
		  cerr << tp->scoreProperties[i] << " ";
	  }
	  cerr << endl;
	  */
  }

//  // alignment
//  /*
//  const std::vector<unsigned char> &alignments = probingTargetPhrase.word_all1;
//
//  AlignmentInfo &aligns = tp->GetAlignTerm();
//  for (size_t i = 0; i < alignS.size(); i += 2 ) {
//    aligns.Add((size_t) alignments[i], (size_t) alignments[i+1]);
//  }
//  */

  // score of all other ff when this rule is being loaded
  const FeatureFunctions &ffs = system.featureFunctions;
  ffs.EvaluateInIsolation(pool, system, sourcePhrase, *tp);
  return tp;

}

void ProbingPT::ConvertToProbingSourcePhrase(const Phrase &sourcePhrase, bool &ok, uint64_t probingSource[]) const
{

  size_t size = sourcePhrase.GetSize();
  for (size_t i = 0; i < size; ++i) {
    const Factor *factor = sourcePhrase[i][0];
    uint64_t probingId = GetSourceProbingId(factor);
    if (probingId == m_unkId) {
      ok = false;
      return;
    } else {
      probingSource[i] = probingId;
    }
  }

  ok = true;
}

void ProbingPT::GetScoresProperty(const std::string &key, size_t ind, SCORE *scoreArr)
		{

		}

}

<|endoftext|>


<commit_before>/// HEADER
#include "output_display_adapter.h"

/// PROJECT
#include <csapex/msg/io.h>
#include <csapex/view/utility/register_node_adapter.h>
#include <csapex/utility/assert.h>
#include <csapex/model/node.h>
#include <csapex/model/node_state.h>
#include <csapex/model/node_facade_remote.h>

/// SYSTEM
#include <QPainter>
#include <QGraphicsSceneEvent>
#include <QGraphicsPixmapItem>
#include <QPushButton>
#include <QBoxLayout>
#include <QResizeEvent>

using namespace csapex;

CSAPEX_REGISTER_LEGACY_NODE_ADAPTER(OutputDisplayAdapter, csapex::OutputDisplay)

OutputDisplayAdapter::OutputDisplayAdapter(NodeFacadeWeakPtr node, NodeBox* parent)
    : ResizableNodeAdapter(node, parent)
{
    if(auto local = std::dynamic_pointer_cast<NodeFacadeLocal>(node.lock())) {
        wrapped_ = std::dynamic_pointer_cast<OutputDisplay>(local->getNode());

        auto n = wrapped_.lock();
        // translate to UI thread via Qt signal
        trackConnection(n->display_request.connect(std::bind(&OutputDisplayAdapter::displayRequest, this, std::placeholders::_1)));

        n->setAdapted();

    } else if(auto remote = std::dynamic_pointer_cast<NodeFacadeRemote>(node.lock())) {
//        TODO: remote!
    }

}

OutputDisplayAdapter::~OutputDisplayAdapter()
{

}

bool OutputDisplayAdapter::eventFilter(QObject *o, QEvent *e)
{
    if (e->type() == QEvent::Resize){
        QSize s = label_view_->sizeHint();
        setSize(s.width(), s.height());
    }

    return false;
}

void OutputDisplayAdapter::resize(const QSize& size)
{
    label_view_->setSize(size);
}

void OutputDisplayAdapter::setupUi(QBoxLayout* layout)
{
    label_view_ = new ImageWidget;
    label_view_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    label_view_->installEventFilter(this);

    layout->addWidget(label_view_);

    QHBoxLayout* sub = new QHBoxLayout;

    QPushButton* fit = new QPushButton("resize to content");
    sub->addWidget(fit, 0,  Qt::AlignLeft);
    QObject::connect(fit, SIGNAL(clicked()), this, SLOT(fitInView()));

    sub->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum));

    layout->addLayout(sub);

    connect(this, &OutputDisplayAdapter::displayRequest, this, &OutputDisplayAdapter::display);

    ResizableNodeAdapter::setupUi(layout);
}

void OutputDisplayAdapter::setManualResize(bool manual)
{
    label_view_->setManualResize(manual);
}

void OutputDisplayAdapter::fitInView()
{
    setSize(last_image_size_.width(), last_image_size_.height());

    doResize();
}

void OutputDisplayAdapter::display(const QImage& img)
{
    last_image_size_ = img.size();
    label_view_->setPixmap(QPixmap::fromImage(img));
    label_view_->repaint();
}

ImageWidget::ImageWidget(QWidget *parent) :
    QWidget(parent), size(100,100), manual_resize_(false)
{
}

void ImageWidget::paintEvent(QPaintEvent *event)
{
    QWidget::paintEvent(event);

    if (pix.isNull())
        return;

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    QSize pixSize = pix.size();
    pixSize.scale(event->rect().size(), Qt::KeepAspectRatio);

    QPixmap scaledPix = pix.scaled(pixSize,
                                   Qt::KeepAspectRatio,
                                   Qt::SmoothTransformation
                                   );

    int x = (width() - scaledPix.width()) / 2;
    int y = (height() - scaledPix.height()) / 2;

    painter.drawPixmap(QPoint(x,y), scaledPix);

}

void ImageWidget::resizeEvent(QResizeEvent * re)
{
    if(manual_resize_) {
        setSize(re->size());
    }
}

const QPixmap* ImageWidget::pixmap() const
{
    return &pix;
}

void ImageWidget::setPixmap (const QPixmap &pixmap)
{
    pix = pixmap;
}

void ImageWidget::setManualResize(bool manual)
{
    manual_resize_ = manual;
    updateGeometry();
}

void ImageWidget::setSize(const QSize &s)
{
    size = s;
    updateGeometry();
}
void ImageWidget::setSize(int w, int h)
{
    setSize(QSize(w,h));
}

QSize ImageWidget::sizeHint() const
{
    return size;
}
QSize ImageWidget::minimumSizeHint() const
{
    if(manual_resize_) {
        return QSize(10, 10);
    } else {
        return size;
    }
}

/// MOC
#include "../moc_output_display_adapter.cpp"

<commit_msg>buildfixes<commit_after>/// HEADER
#include "output_display_adapter.h"

/// PROJECT
#include <csapex/msg/io.h>
#include <csapex/view/utility/register_node_adapter.h>
#include <csapex/utility/assert.h>
#include <csapex/model/node.h>
#include <csapex/model/node_state.h>
#include <csapex/model/node_facade_remote.h>

/// SYSTEM
#include <QPainter>
#include <QGraphicsSceneEvent>
#include <QGraphicsPixmapItem>
#include <QPushButton>
#include <QBoxLayout>
#include <QResizeEvent>

using namespace csapex;

CSAPEX_REGISTER_NODE_ADAPTER(OutputDisplayAdapter, csapex::OutputDisplay)

OutputDisplayAdapter::OutputDisplayAdapter(NodeFacadeWeakPtr node, NodeBox* parent)
    : ResizableNodeAdapter(node, parent)
{
    if(auto local = std::dynamic_pointer_cast<NodeFacadeLocal>(node.lock())) {
        wrapped_ = std::dynamic_pointer_cast<OutputDisplay>(local->getNode());

        auto n = wrapped_.lock();
        // translate to UI thread via Qt signal
        trackConnection(n->display_request.connect(std::bind(&OutputDisplayAdapter::displayRequest, this, std::placeholders::_1)));

        n->setAdapted();

    } else if(auto remote = std::dynamic_pointer_cast<NodeFacadeRemote>(node.lock())) {
//        TODO: remote!
    }

}

OutputDisplayAdapter::~OutputDisplayAdapter()
{

}

bool OutputDisplayAdapter::eventFilter(QObject *o, QEvent *e)
{
    if (e->type() == QEvent::Resize){
        QSize s = label_view_->sizeHint();
        setSize(s.width(), s.height());
    }

    return false;
}

void OutputDisplayAdapter::resize(const QSize& size)
{
    label_view_->setSize(size);
}

void OutputDisplayAdapter::setupUi(QBoxLayout* layout)
{
    label_view_ = new ImageWidget;
    label_view_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    label_view_->installEventFilter(this);

    layout->addWidget(label_view_);

    QHBoxLayout* sub = new QHBoxLayout;

    QPushButton* fit = new QPushButton("resize to content");
    sub->addWidget(fit, 0,  Qt::AlignLeft);
    QObject::connect(fit, SIGNAL(clicked()), this, SLOT(fitInView()));

    sub->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum));

    layout->addLayout(sub);

    connect(this, &OutputDisplayAdapter::displayRequest, this, &OutputDisplayAdapter::display);

    ResizableNodeAdapter::setupUi(layout);
}

void OutputDisplayAdapter::setManualResize(bool manual)
{
    label_view_->setManualResize(manual);
}

void OutputDisplayAdapter::fitInView()
{
    setSize(last_image_size_.width(), last_image_size_.height());

    doResize();
}

void OutputDisplayAdapter::display(const QImage& img)
{
    last_image_size_ = img.size();
    label_view_->setPixmap(QPixmap::fromImage(img));
    label_view_->repaint();
}

ImageWidget::ImageWidget(QWidget *parent) :
    QWidget(parent), size(100,100), manual_resize_(false)
{
}

void ImageWidget::paintEvent(QPaintEvent *event)
{
    QWidget::paintEvent(event);

    if (pix.isNull())
        return;

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    QSize pixSize = pix.size();
    pixSize.scale(event->rect().size(), Qt::KeepAspectRatio);

    QPixmap scaledPix = pix.scaled(pixSize,
                                   Qt::KeepAspectRatio,
                                   Qt::SmoothTransformation
                                   );

    int x = (width() - scaledPix.width()) / 2;
    int y = (height() - scaledPix.height()) / 2;

    painter.drawPixmap(QPoint(x,y), scaledPix);

}

void ImageWidget::resizeEvent(QResizeEvent * re)
{
    if(manual_resize_) {
        setSize(re->size());
    }
}

const QPixmap* ImageWidget::pixmap() const
{
    return &pix;
}

void ImageWidget::setPixmap (const QPixmap &pixmap)
{
    pix = pixmap;
}

void ImageWidget::setManualResize(bool manual)
{
    manual_resize_ = manual;
    updateGeometry();
}

void ImageWidget::setSize(const QSize &s)
{
    size = s;
    updateGeometry();
}
void ImageWidget::setSize(int w, int h)
{
    setSize(QSize(w,h));
}

QSize ImageWidget::sizeHint() const
{
    return size;
}
QSize ImageWidget::minimumSizeHint() const
{
    if(manual_resize_) {
        return QSize(10, 10);
    } else {
        return size;
    }
}

/// MOC
#include "../moc_output_display_adapter.cpp"

<|endoftext|>


<commit_before><commit_msg>asdfkjhasjdklfh<commit_after><|endoftext|>


<commit_before><commit_msg>almost working<commit_after><|endoftext|>


<commit_before>/* Tone.cpp

 A Tone Generator Library

 Written by Brett Hagman

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

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

 Version Modified By Date     Comments
 ------- ----------- -------- --------
 0001    B Hagman    09/08/02 Initial coding
 0002    B Hagman    09/08/18 Multiple pins
 0003    B Hagman    09/08/18 Moved initialization from constructor to begin()
 0004    B Hagman    09/09/26 Fixed problems with ATmega8
 0005    B Hagman    09/11/23 Scanned prescalars for best fit on 8 bit timers
 09/11/25 Changed pin toggle method to XOR
 09/11/25 Fixed timer0 from being excluded
 0006    D Mellis    09/12/29 Replaced objects with functions
 0007    M Sproul    10/08/29 Changed #ifdefs from cpu to register
 0008    S Kanemoto  12/06/22 Fixed for Leonardo by @maris_HY
 *************************************************/

#include "Arduino.h"
#include "pins_arduino.h"

/*
static int8_t toneBegin(uint8_t _pin) {
    //TODO implement tone
    return 0;
}
*/

void tone(uint8_t _pin, unsigned int frequency, unsigned long duration) {
    //TODO implement tone
}

void noTone(uint8_t _pin) {
    //TODO implement tone
}
<commit_msg>Implementation of Tone API using timer1<commit_after>/*
  Tone.cpp

  A Tone Generator Library for the ESP8266

  Copyright (c) 2016 Ben Pirt. All rights reserved.
  This file is part of the esp8266 core for Arduino environment.

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

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "Arduino.h"
#include "pins_arduino.h"

#define AVAILABLE_TONE_PINS 1
const uint8_t tone_timers[] = { 1 };
static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255, };
static long toggle_counts[AVAILABLE_TONE_PINS] = { 0, };
#define T1INDEX 0

void t1IntHandler();

static int8_t toneBegin(uint8_t _pin) {
  int8_t _index = -1;

  // if we're already using the pin, reuse it.
  for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
    if (tone_pins[i] == _pin) {
      return i;
    }
  }

  // search for an unused timer.
  for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
    if (tone_pins[i] == 255) {
      tone_pins[i] = _pin;
      _index = i;
      break;
    }
  }

  return _index;
}

// frequency (in hertz) and duration (in milliseconds).
void tone(uint8_t _pin, unsigned int frequency, unsigned long duration) {
  int8_t _index;

  _index = toneBegin(_pin);

  if (_index >= 0) {
    // Set the pinMode as OUTPUT
    pinMode(_pin, OUTPUT);

    // Calculate the toggle count
    if (duration > 0) {
      toggle_counts[_index] = 2 * frequency * duration / 1000;
    } else {
      toggle_counts[_index] = -1;
    }

    // set up the interrupt frequency
    switch (tone_timers[_index]) {
      case 0:
        // Not currently supported
        break;

      case 1:
        timer1_disable();
        timer1_isr_init();
        timer1_attachInterrupt(t1IntHandler);
        timer1_enable(TIM_DIV1, TIM_EDGE, TIM_LOOP);
        timer1_write((clockCyclesPerMicrosecond() * 500000) / frequency);
        break;
    }
  }
}

void disableTimer(uint8_t _index) {
  tone_pins[_index] = 255;

  switch (tone_timers[_index]) {
    case 0:
      // Not currently supported
      break;

    case 1:
      timer1_disable();
      break;
  }
}

void noTone(uint8_t _pin) {
  for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
    if (tone_pins[i] == _pin) {
      tone_pins[i] = 255;
      disableTimer(i);
      break;
    }
  }
  digitalWrite(_pin, LOW);
}

void t1IntHandler() {
  if (toggle_counts[T1INDEX] > 0){
    // toggle the pin
    digitalWrite(tone_pins[T1INDEX], toggle_counts[T1INDEX] % 2);
    toggle_counts[T1INDEX]--;
  }else{
    disableTimer(T1INDEX);
    digitalWrite(tone_pins[T1INDEX], LOW);
  }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <math.h>
#include <string>
#include <vector>
#include "mex.h"

#include <nix.hpp>

#include "handle.h"
#include "arguments.h"

// *** datatype converter

template<typename T>
struct to_mx_class_id {

    static mxClassID value() {
        nix::DataType dtype = nix::to_data_type<T>::value;
        switch (dtype) {
            case nix::DataType::Double:
                return mxDOUBLE_CLASS;

            default:
                mexErrMsgIdAndTxt("MATLAB:toclassid:notimplemented", "Implement me!");
                return mxVOID_CLASS;
        }
    }

};

template<typename T>
mxArray* vector_to_array(const std::vector<T> &v) {
    mxClassID klass_id = to_mx_class_id<T>::value();
    mxArray *data = mxCreateNumericMatrix(1, v.size(), klass_id, mxREAL);
    double *ptr = mxGetPr(data);
    memcpy(ptr, v.data(), sizeof(T) * v.size());
    return data;
}

template<>
mxArray* vector_to_array(const std::vector<std::string> &v) {
    mxArray *data = mxCreateCellMatrix(1, v.size());
    for (size_t i = 0; i < v.size(); i++) {
        mxSetCell(data, i, mxCreateString(v[i].c_str()));
    }

    return data;
}

// *** functions ***

static void entity_destory(const extractor &input, infusor &output)
{
    mexPrintf("[+] entity_destory\n");
    handle h = input.hdl(1);
    h.destroy();
}

static void open_file(const extractor &input, infusor &output)
{
    input.require_arguments({mxCHAR_CLASS, mxCHAR_CLASS}, true);
    mexPrintf("[+] open_file\n");

    std::string name = input.str(1);

    nix::File fn = nix::File::open(name, nix::FileMode::ReadWrite);
    handle h = handle(fn);

    output.set(0, h);
}

static void list_blocks(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_blocks\n");
    nix::File fd = input.entity<nix::File>(1);

    std::vector<nix::Block> blocks = fd.blocks();

    std::vector<const char *> fields = { "name", "id" };

    mxArray *sa =  mxCreateStructMatrix(blocks.size(), 1, fields.size(), fields.data());

    for (size_t n = 0; n < blocks.size(); n++) {
        mxSetFieldByNumber(sa, n, 0, mxCreateString(blocks[n].name().c_str()));
        mxSetFieldByNumber(sa, n, 1, mxCreateString(blocks[n].id().c_str()));
    }

    output.set(0, sa);
}

static void list_data_arrays(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_data_arrays\n");

    nix::File nf = input.entity<nix::File>(1);
    nix::Block block = nf.getBlock(input.str(2));

    std::vector<nix::DataArray> arr = block.dataArrays();

    std::vector<const char *> fields = { "name", "id" };

    mxArray *sa =  mxCreateStructMatrix(arr.size(), 1, fields.size(), fields.data());

    for (size_t n = 0; n < arr.size(); n++) {
        mxSetFieldByNumber(sa, n, 0, mxCreateString(arr[n].name().c_str()));
        mxSetFieldByNumber(sa, n, 1, mxCreateString(arr[n].id().c_str()));
    }

    output.set(0, sa);
}

static void open_block(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_data_arrays\n");
    nix::File nf = input.entity<nix::File>(1);
    nix::Block block = nf.getBlock(input.str(2));
    handle bb = handle(block);
    output.set(0, bb);
}

static void open_data_array(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_data_arrays\n");
    nix::Block block = input.entity<nix::Block>(1);
    nix::DataArray da = block.getDataArray(input.str(2));
    handle bd = handle(da);
    output.set(0, bd);
}

static void block_list_data_arrays(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_data_arrays\n");

    nix::Block block = input.entity<nix::Block>(1);
    std::vector<nix::DataArray> arr = block.dataArrays();

    std::vector<const char *> fields = { "name", "id" };

    mxArray *sa =  mxCreateStructMatrix(arr.size(), 1, fields.size(), fields.data());

    for (size_t n = 0; n < arr.size(); n++) {
        mxSetFieldByNumber(sa, n, 0, mxCreateString(arr[n].name().c_str()));
        mxSetFieldByNumber(sa, n, 1, mxCreateString(arr[n].id().c_str()));
    }

    output.set(0, sa);
}

static mxArray * ndsize_to_mxarray(const nix::NDSize &size)
{
    mxArray *res = mxCreateNumericMatrix(1, size.size(), mxUINT64_CLASS, mxREAL);
    void *ptr = mxGetData(res);
    uint64_t *data = static_cast<uint64_t *>(ptr);

    for (size_t i = 0; i < size.size(); i++) {
        data[i] = static_cast<uint64_t>(size[i]);
    }

    return res;
}

static nix::NDSize mx_array_to_ndsize(const mxArray *arr) {

    size_t m = mxGetM(arr);
    size_t n = mxGetN(arr);

    //if (m != 1 && n != 1)

    size_t k = std::max(n, m);
    nix::NDSize size(k);

    double *data = mxGetPr(arr);
    for (size_t i = 0; i < size.size(); i++) {
        size[i] = static_cast<nix::NDSize::value_type>(data[i]);
    }

    return size;
}

static mxArray *nmCreateScalar(uint32_t val) {
    mxArray *arr = mxCreateNumericMatrix(1, 1, mxUINT32_CLASS, mxREAL);
    void *data = mxGetData(arr);
    memcpy(data, &val, sizeof(uint32_t));
    return arr;
}

static mxArray *dim_to_struct(nix::SetDimension dim) {

    std::vector<const char *> fields = { "type", "type_id", "label" };
    mxArray *sa =  mxCreateStructMatrix(1, 1, fields.size(), fields.data());

    mxSetFieldByNumber(sa, 0, 0, mxCreateString("set"));
    mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(1));

    std::vector<std::string> labels = dim.labels();
    return sa;
}

static mxArray *dim_to_struct(nix::SampledDimension dim) {

    std::vector<const char *> fields = { "type", "type_id", "interval", "label", "unit"};
    mxArray *sa =  mxCreateStructMatrix(1, 1, fields.size(), fields.data());

    mxSetFieldByNumber(sa, 0, 0, mxCreateString("sampled"));
    mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(2));
    mxSetFieldByNumber(sa, 0, 2, mxCreateDoubleScalar(dim.samplingInterval()));

    boost::optional<std::string> label = dim.label();
    if (label) {
        mxSetFieldByNumber(sa, 0, 3, mxCreateString(label->c_str()));
    }

    boost::optional<std::string> unit = dim.unit();
    if (unit) {
        mxSetFieldByNumber(sa, 0, 4, mxCreateString(unit->c_str()));
    }

    return sa;
}

static mxArray *dim_to_struct(nix::RangeDimension dim) {

    std::vector<const char *> fields = { "type", "type_id" };
    mxArray *sa =  mxCreateStructMatrix(1, 1, fields.size(), fields.data());

    mxSetFieldByNumber(sa, 0, 0, mxCreateString("range"));
    mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(3));
    return sa;
}

static void data_array_describe(const extractor &input, infusor &output)
{
    mexPrintf("[+] block_describe_data_array\n");
    nix::DataArray da = input.entity<nix::DataArray>(1);

    std::vector<const char *> fields = { "name", "id", "shape",  "unit", "dimensions", "label",
                                         "polynom_coefficients"};
    mxArray *sa =  mxCreateStructMatrix(1, 1, fields.size(), fields.data());

    mxSetFieldByNumber(sa, 0, 0, mxCreateString(da.name().c_str()));
    mxSetFieldByNumber(sa, 0, 1, mxCreateString(da.id().c_str()));
    mxSetFieldByNumber(sa, 0, 2, ndsize_to_mxarray(da.dataExtent()));

    boost::optional<std::string> unit = da.unit();
    if (unit) {
        mxSetFieldByNumber(sa, 0, 3, mxCreateString(unit->c_str()));
    }

    size_t ndims = da.dimensionCount();

    mxArray *dims = mxCreateCellMatrix(1, ndims);
    std::vector<nix::Dimension> da_dims = da.dimensions();

    for(size_t i = 0; i < ndims; i++) {
        mxArray *ca;

        switch(da_dims[i].dimensionType()) {
            case nix::DimensionType::Set:
                ca = dim_to_struct(da_dims[i].asSetDimension());
                break;
            case nix::DimensionType::Range:
                ca = dim_to_struct(da_dims[i].asRangeDimension());
                break;
            case nix::DimensionType::Sample:
                ca = dim_to_struct(da_dims[i].asSampledDimension());
                break;
        }

        mxSetCell(dims, i, ca);
    }

    mxSetFieldByNumber(sa, 0, 4, dims);

    boost::optional<std::string> label = da.label();
    if (unit) {
        mxSetFieldByNumber(sa, 0, 5, mxCreateString(label->c_str()));
    }

    std::vector<double> pc = da.polynomCoefficients();

    if (!pc.empty()) {
        mxSetFieldByNumber(sa, 0, 6, vector_to_array(pc));
    }

    output.set(0, sa);
}

static void data_array_read_all(const extractor &input, infusor &output)
{
    mexPrintf("[+] block_describe_data_array\n");
    nix::DataArray da = input.entity<nix::DataArray>(1);

    nix::NDSize size = da.dataExtent();
    std::vector<mwSize> dims(size.size());

    for (size_t i = 0; i < size.size(); i++) {
        dims[i] = static_cast<mwSize>(size[i]);
    }

    mxArray *data = mxCreateNumericArray(size.size(), dims.data(), mxDOUBLE_CLASS, mxREAL);
    double *ptr = mxGetPr(data);

    nix::NDSize offset(size.size(), 0);
    da.getData(nix::DataType::Double , ptr, size, offset);

    output.set(0, data);
}

// *** ***

typedef void (*fn_t)(const extractor &input, infusor &output);

struct fendpoint {

fendpoint(std::string name, fn_t fn) : name(name), fn(fn) {}

    std::string name;
    fn_t fn;
};

const std::vector<fendpoint> funcs = {
        {"Entity::destroy", entity_destory},
        {"File::open", open_file},
        {"File::listBlocks", list_blocks},
        {"File::listDataArrays", list_data_arrays},
        {"File::openBlock", open_block},
        {"Block::openDataArray", open_data_array},
        {"Block::listDataArrays", block_list_data_arrays},
        {"DataArray::describe", data_array_describe},
        {"DataArray::readAll", data_array_read_all}
};

// main entry point
void mexFunction(int            nlhs,
                 mxArray       *lhs[],
                 int            nrhs,
                 const mxArray *rhs[])
{
    extractor input(rhs, nrhs);
    infusor   output(lhs, nlhs);

    std::string cmd = input.str(0);

    mexPrintf("[F] %s\n", cmd.c_str());

    bool processed = false;
    for (const auto &fn : funcs) {
        if (fn.name == cmd) {
            try {
                fn.fn(input, output);
            } catch (std::exception &e) {
                mexErrMsgIdAndTxt("MATLAB:arg:dispatch", e.what());
            } catch (...) {
                mexErrMsgIdAndTxt("MATLAB:arg:dispatch", "unkown exception");
            }
            processed = true;
            break;
        }
    }

    if (!processed) {
        mexErrMsgIdAndTxt("MATLAB:arg:dispatch", "Unkown command");
    }
}

<commit_msg>dim_to_struct (SetDim) return labels as "labels"<commit_after>#include <iostream>
#include <math.h>
#include <string>
#include <vector>
#include "mex.h"

#include <nix.hpp>

#include "handle.h"
#include "arguments.h"

// *** datatype converter

template<typename T>
struct to_mx_class_id {

    static mxClassID value() {
        nix::DataType dtype = nix::to_data_type<T>::value;
        switch (dtype) {
            case nix::DataType::Double:
                return mxDOUBLE_CLASS;

            default:
                mexErrMsgIdAndTxt("MATLAB:toclassid:notimplemented", "Implement me!");
                return mxVOID_CLASS;
        }
    }

};

template<typename T>
mxArray* vector_to_array(const std::vector<T> &v) {
    mxClassID klass_id = to_mx_class_id<T>::value();
    mxArray *data = mxCreateNumericMatrix(1, v.size(), klass_id, mxREAL);
    double *ptr = mxGetPr(data);
    memcpy(ptr, v.data(), sizeof(T) * v.size());
    return data;
}

template<>
mxArray* vector_to_array(const std::vector<std::string> &v) {
    mxArray *data = mxCreateCellMatrix(1, v.size());
    for (size_t i = 0; i < v.size(); i++) {
        mxSetCell(data, i, mxCreateString(v[i].c_str()));
    }

    return data;
}

// *** functions ***

static void entity_destory(const extractor &input, infusor &output)
{
    mexPrintf("[+] entity_destory\n");
    handle h = input.hdl(1);
    h.destroy();
}

static void open_file(const extractor &input, infusor &output)
{
    input.require_arguments({mxCHAR_CLASS, mxCHAR_CLASS}, true);
    mexPrintf("[+] open_file\n");

    std::string name = input.str(1);

    nix::File fn = nix::File::open(name, nix::FileMode::ReadWrite);
    handle h = handle(fn);

    output.set(0, h);
}

static void list_blocks(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_blocks\n");
    nix::File fd = input.entity<nix::File>(1);

    std::vector<nix::Block> blocks = fd.blocks();

    std::vector<const char *> fields = { "name", "id" };

    mxArray *sa =  mxCreateStructMatrix(blocks.size(), 1, fields.size(), fields.data());

    for (size_t n = 0; n < blocks.size(); n++) {
        mxSetFieldByNumber(sa, n, 0, mxCreateString(blocks[n].name().c_str()));
        mxSetFieldByNumber(sa, n, 1, mxCreateString(blocks[n].id().c_str()));
    }

    output.set(0, sa);
}

static void list_data_arrays(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_data_arrays\n");

    nix::File nf = input.entity<nix::File>(1);
    nix::Block block = nf.getBlock(input.str(2));

    std::vector<nix::DataArray> arr = block.dataArrays();

    std::vector<const char *> fields = { "name", "id" };

    mxArray *sa =  mxCreateStructMatrix(arr.size(), 1, fields.size(), fields.data());

    for (size_t n = 0; n < arr.size(); n++) {
        mxSetFieldByNumber(sa, n, 0, mxCreateString(arr[n].name().c_str()));
        mxSetFieldByNumber(sa, n, 1, mxCreateString(arr[n].id().c_str()));
    }

    output.set(0, sa);
}

static void open_block(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_data_arrays\n");
    nix::File nf = input.entity<nix::File>(1);
    nix::Block block = nf.getBlock(input.str(2));
    handle bb = handle(block);
    output.set(0, bb);
}

static void open_data_array(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_data_arrays\n");
    nix::Block block = input.entity<nix::Block>(1);
    nix::DataArray da = block.getDataArray(input.str(2));
    handle bd = handle(da);
    output.set(0, bd);
}

static void block_list_data_arrays(const extractor &input, infusor &output)
{
    mexPrintf("[+] list_data_arrays\n");

    nix::Block block = input.entity<nix::Block>(1);
    std::vector<nix::DataArray> arr = block.dataArrays();

    std::vector<const char *> fields = { "name", "id" };

    mxArray *sa =  mxCreateStructMatrix(arr.size(), 1, fields.size(), fields.data());

    for (size_t n = 0; n < arr.size(); n++) {
        mxSetFieldByNumber(sa, n, 0, mxCreateString(arr[n].name().c_str()));
        mxSetFieldByNumber(sa, n, 1, mxCreateString(arr[n].id().c_str()));
    }

    output.set(0, sa);
}

static mxArray * ndsize_to_mxarray(const nix::NDSize &size)
{
    mxArray *res = mxCreateNumericMatrix(1, size.size(), mxUINT64_CLASS, mxREAL);
    void *ptr = mxGetData(res);
    uint64_t *data = static_cast<uint64_t *>(ptr);

    for (size_t i = 0; i < size.size(); i++) {
        data[i] = static_cast<uint64_t>(size[i]);
    }

    return res;
}

static nix::NDSize mx_array_to_ndsize(const mxArray *arr) {

    size_t m = mxGetM(arr);
    size_t n = mxGetN(arr);

    //if (m != 1 && n != 1)

    size_t k = std::max(n, m);
    nix::NDSize size(k);

    double *data = mxGetPr(arr);
    for (size_t i = 0; i < size.size(); i++) {
        size[i] = static_cast<nix::NDSize::value_type>(data[i]);
    }

    return size;
}

static mxArray *nmCreateScalar(uint32_t val) {
    mxArray *arr = mxCreateNumericMatrix(1, 1, mxUINT32_CLASS, mxREAL);
    void *data = mxGetData(arr);
    memcpy(data, &val, sizeof(uint32_t));
    return arr;
}

static mxArray *dim_to_struct(nix::SetDimension dim) {

    std::vector<const char *> fields = { "type", "type_id", "labels" };
    mxArray *sa =  mxCreateStructMatrix(1, 1, fields.size(), fields.data());

    mxSetFieldByNumber(sa, 0, 0, mxCreateString("set"));
    mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(1));

    std::vector<std::string> labels = dim.labels();
    mxSetFieldByNumber(sa, 0, 2, vector_to_array(labels));

    return sa;
}

static mxArray *dim_to_struct(nix::SampledDimension dim) {

    std::vector<const char *> fields = { "type", "type_id", "interval", "label", "unit"};
    mxArray *sa =  mxCreateStructMatrix(1, 1, fields.size(), fields.data());

    mxSetFieldByNumber(sa, 0, 0, mxCreateString("sampled"));
    mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(2));
    mxSetFieldByNumber(sa, 0, 2, mxCreateDoubleScalar(dim.samplingInterval()));

    boost::optional<std::string> label = dim.label();
    if (label) {
        mxSetFieldByNumber(sa, 0, 3, mxCreateString(label->c_str()));
    }

    boost::optional<std::string> unit = dim.unit();
    if (unit) {
        mxSetFieldByNumber(sa, 0, 4, mxCreateString(unit->c_str()));
    }

    return sa;
}

static mxArray *dim_to_struct(nix::RangeDimension dim) {

    std::vector<const char *> fields = { "type", "type_id" };
    mxArray *sa =  mxCreateStructMatrix(1, 1, fields.size(), fields.data());

    mxSetFieldByNumber(sa, 0, 0, mxCreateString("range"));
    mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(3));
    return sa;
}

static void data_array_describe(const extractor &input, infusor &output)
{
    mexPrintf("[+] block_describe_data_array\n");
    nix::DataArray da = input.entity<nix::DataArray>(1);

    std::vector<const char *> fields = { "name", "id", "shape",  "unit", "dimensions", "label",
                                         "polynom_coefficients"};
    mxArray *sa =  mxCreateStructMatrix(1, 1, fields.size(), fields.data());

    mxSetFieldByNumber(sa, 0, 0, mxCreateString(da.name().c_str()));
    mxSetFieldByNumber(sa, 0, 1, mxCreateString(da.id().c_str()));
    mxSetFieldByNumber(sa, 0, 2, ndsize_to_mxarray(da.dataExtent()));

    boost::optional<std::string> unit = da.unit();
    if (unit) {
        mxSetFieldByNumber(sa, 0, 3, mxCreateString(unit->c_str()));
    }

    size_t ndims = da.dimensionCount();

    mxArray *dims = mxCreateCellMatrix(1, ndims);
    std::vector<nix::Dimension> da_dims = da.dimensions();

    for(size_t i = 0; i < ndims; i++) {
        mxArray *ca;

        switch(da_dims[i].dimensionType()) {
            case nix::DimensionType::Set:
                ca = dim_to_struct(da_dims[i].asSetDimension());
                break;
            case nix::DimensionType::Range:
                ca = dim_to_struct(da_dims[i].asRangeDimension());
                break;
            case nix::DimensionType::Sample:
                ca = dim_to_struct(da_dims[i].asSampledDimension());
                break;
        }

        mxSetCell(dims, i, ca);
    }

    mxSetFieldByNumber(sa, 0, 4, dims);

    boost::optional<std::string> label = da.label();
    if (unit) {
        mxSetFieldByNumber(sa, 0, 5, mxCreateString(label->c_str()));
    }

    std::vector<double> pc = da.polynomCoefficients();

    if (!pc.empty()) {
        mxSetFieldByNumber(sa, 0, 6, vector_to_array(pc));
    }

    output.set(0, sa);
}

static void data_array_read_all(const extractor &input, infusor &output)
{
    mexPrintf("[+] block_describe_data_array\n");
    nix::DataArray da = input.entity<nix::DataArray>(1);

    nix::NDSize size = da.dataExtent();
    std::vector<mwSize> dims(size.size());

    for (size_t i = 0; i < size.size(); i++) {
        dims[i] = static_cast<mwSize>(size[i]);
    }

    mxArray *data = mxCreateNumericArray(size.size(), dims.data(), mxDOUBLE_CLASS, mxREAL);
    double *ptr = mxGetPr(data);

    nix::NDSize offset(size.size(), 0);
    da.getData(nix::DataType::Double , ptr, size, offset);

    output.set(0, data);
}

// *** ***

typedef void (*fn_t)(const extractor &input, infusor &output);

struct fendpoint {

fendpoint(std::string name, fn_t fn) : name(name), fn(fn) {}

    std::string name;
    fn_t fn;
};

const std::vector<fendpoint> funcs = {
        {"Entity::destroy", entity_destory},
        {"File::open", open_file},
        {"File::listBlocks", list_blocks},
        {"File::listDataArrays", list_data_arrays},
        {"File::openBlock", open_block},
        {"Block::openDataArray", open_data_array},
        {"Block::listDataArrays", block_list_data_arrays},
        {"DataArray::describe", data_array_describe},
        {"DataArray::readAll", data_array_read_all}
};

// main entry point
void mexFunction(int            nlhs,
                 mxArray       *lhs[],
                 int            nrhs,
                 const mxArray *rhs[])
{
    extractor input(rhs, nrhs);
    infusor   output(lhs, nlhs);

    std::string cmd = input.str(0);

    mexPrintf("[F] %s\n", cmd.c_str());

    bool processed = false;
    for (const auto &fn : funcs) {
        if (fn.name == cmd) {
            try {
                fn.fn(input, output);
            } catch (std::exception &e) {
                mexErrMsgIdAndTxt("MATLAB:arg:dispatch", e.what());
            } catch (...) {
                mexErrMsgIdAndTxt("MATLAB:arg:dispatch", "unkown exception");
            }
            processed = true;
            break;
        }
    }

    if (!processed) {
        mexErrMsgIdAndTxt("MATLAB:arg:dispatch", "Unkown command");
    }
}

<|endoftext|>


<commit_before>a2007c70-4b02-11e5-b2de-28cfe9171a43<commit_msg>Tuesday, turns out it was tuesday<commit_after>a20d2380-4b02-11e5-b7cf-28cfe9171a43<|endoftext|>


<commit_before>#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <cmath>
#include <vector>
#include <SDL/SDL.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>

SDL_Surface *surface;
bool done = false;
bool is_active = true;

void
init_sdl ()
{
	const SDL_VideoInfo *video_info;

	if (SDL_Init( SDL_INIT_VIDEO ) < 0)
	{
		fprintf(stderr, "Video initialization failed: %s", SDL_GetError());
		exit(1);
	}

	video_info = SDL_GetVideoInfo();
	if (!video_info)
	{
		fprintf(stderr, "Video info query failed: %s",
		SDL_GetError());
		exit(1);
	}

	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 0);

	surface = SDL_SetVideoMode(600, 600, 32, SDL_OPENGL | SDL_GL_DOUBLEBUFFER);
	if (!surface)
	{
		fprintf(stderr, "Video mode set failed: %s", SDL_GetError());
		exit(1);
	}
}

void
resize_viewport ()
{
  glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, 600, 600, 0, -1, 1);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glDisable(GL_DEPTH_TEST);
}

void
init_opengl ()
{
	glShadeModel(GL_SMOOTH);
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glClearDepth(20.0f);
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
	glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);

	resize_viewport();
}

class Vector2
{
	public:
		Vector2 (float _x = 0.0f, float _y = 0.0f)
		{
			x = _x;
			y = _y;
		}

		float
		length ()
		{
			return sqrtf(x*x + y*y);
		}

		float x;
		float y;
};

class Mosquito
{
	public:
		Vector2 velocity;
		Vector2 position;

		static Mosquito
		random ()
		{
			Mosquito m;

			m.velocity.x = (float)(rand() % 1000) / 1000.0f;
			m.velocity.y = (float)(rand() % 1000) / 1000.0f;
			/* m.velocity.x = (float)(rand() % 1000) / 1000.0f - 0.5f; */
			/* m.velocity.y = (float)(rand() % 1000) / 1000.0f - 0.5f; */

			m.position.x = (float)(rand() % 600);
			m.position.y = (float)(rand() % 600);

			return m;
		}

		void
		draw ()
		{
			glLoadIdentity();

			glTranslatef(position.x, position.y, 0.0f);
			glRotatef(atan2(velocity.y, velocity.x) * 180.0f / M_PI + 90.0f, 0.0f, 0.0f, 1.0f);

			glBegin(GL_QUADS);
				glVertex2f(-2.0f, -6.0f);
				glVertex2f( 2.0f, -6.0f);
				glVertex2f( 2.0f,  6.0f);
				glVertex2f(-2.0f,  6.0f);
			glEnd();
		}

};

Vector2
operator+ (Vector2 const& _a, Vector2 const& _b)
{
	Vector2 result;
	result.x = _a.x + _b.x;
	result.y = _a.y + _b.y;

	return result;
}

Vector2
operator- (Vector2 const& _a, Vector2 const& _b)
{
	Vector2 result;
	result.x = _a.x - _b.x;
	result.y = _a.y - _b.y;

	return result;
}

Vector2&
operator/= (Vector2& _v, float _s)
{
  _v.x /= _s;
  _v.y /= _s;

  return _v;
}

Vector2&
operator+= (Vector2& _a, Vector2& _b)
{
  _a.x += _b.x;
  _a.y += _b.y;

  return _a;
}

Vector2&
operator-= (Vector2& _a, Vector2& _b)
{
  _a.x -= _b.x;
  _a.y -= _b.y;

  return _a;
}

Vector2
rule_1 (Mosquito& _m, std::vector<Mosquito> _swarm)
{
	Vector2 mass_centre;

	for (auto& m : _swarm)
	{
		if (&_m != &m)
			mass_centre += m.position;
	}
	mass_centre /= (_swarm.size() - 1);

	Vector2 direction = mass_centre - _m.position;
	direction /= 70.0f;

	return direction;
}

Vector2
rule_2 (Mosquito& _m, std::vector<Mosquito> _swarm)
{
	Vector2 centre;

	for(auto& m : _swarm)
	{
		if (&_m != &m)
		{
			Vector2 difference = m.position - _m.position;
			if (difference.length() < 10.0f)
				centre -= difference;
		}
	}

	return centre;
}

Vector2
rule_3 (Mosquito& _m, std::vector<Mosquito> _swarm)
{
	Vector2 velocity;

	for(auto& m : _swarm)
	{
		if (&_m != &m)
		{
			velocity += m.velocity;
		}
	}
	velocity /= (float)(_swarm.size() - 1);

	Vector2 result;
	result = velocity - _m.velocity;
	result /= 8.0f;

	return result;
}

Vector2
rule_4 (Mosquito& _m)
{
	Vector2 top_velocity;
	Vector2 bottom_velocity;
	Vector2 left_velocity;
	Vector2 right_velocity;

	top_velocity.y = fabs(20.0f / _m.position.y);
	bottom_velocity.y = -fabs(20.0f / (_m.position.y - 600.0f));
	left_velocity.x = fabs(20.0f / _m.position.x);
	right_velocity.x = -fabs(20.0f / (_m.position.x - 600.0f));

	Vector2 result = top_velocity + bottom_velocity + left_velocity +
	    right_velocity;

	result /= 0.1f;

	return result;
}

void
draw_scene (std::vector<Mosquito>& _swarm)
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

	glColor3ub(0, 99, 0);
	for (auto& m : _swarm)
		m.draw();
}

std::vector<Mosquito>
step (std::vector<Mosquito>& _swarm)
{
	std::vector<Mosquito> new_swarm;

	for (auto& m : _swarm)
	{
		Vector2 v1 = rule_1(m, _swarm);
		Vector2 v2 = rule_2(m, _swarm);
		Vector2 v3 = rule_3(m, _swarm);
		Vector2 v4 = rule_4(m);

		Vector2 velocity;
		velocity += v1;
		velocity += v2;
		velocity += v3;
		velocity += v4;

		velocity /= 10000.0f;

		Mosquito new_mosquito;
		new_mosquito.velocity = m.velocity + velocity;
		new_mosquito.position = m.position + new_mosquito.velocity;

		if (new_mosquito.velocity.length() > 0.4)
			new_mosquito.velocity /= 10.0f;

		new_swarm.push_back(new_mosquito);
	}

	return new_swarm;
}

void
main_loop (std::vector<Mosquito>& _swarm)
{
	is_active = true;
	SDL_Event event;

	while (!done)
	{
		while (SDL_PollEvent(&event))
		{
			switch (event.type)
			{
				case SDL_ACTIVEEVENT:
					if (event.active.state == SDL_APPACTIVE )
						is_active = (event.active.gain != 0);
				break;

				case SDL_QUIT:
					done = true;
				break;

				default:
				break;
			}
		}

		if (is_active)
		{
			_swarm = step(_swarm);
			draw_scene(_swarm);
			SDL_GL_SwapBuffers();
		}
	}
}

int
main (int argc, char *argv[])
{
	const unsigned int N = 200;
	std::vector<Mosquito> swarm;
	srand(time(NULL));

	for (unsigned int i = 0; i < N; i++)
		swarm.push_back(Mosquito::random());

  init_sdl();
	init_opengl();

	main_loop(swarm);

	return EXIT_SUCCESS;
}

<commit_msg>Monster commit<commit_after>#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <cmath>
#include <vector>
#include <SDL/SDL.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>

SDL_Surface *surface;
bool done = false;
bool is_active = true;

void
init_sdl ()
{
	const SDL_VideoInfo *video_info;

	if (SDL_Init( SDL_INIT_VIDEO ) < 0)
	{
		fprintf(stderr, "Video initialization failed: %s", SDL_GetError());
		exit(1);
	}

	video_info = SDL_GetVideoInfo();
	if (!video_info)
	{
		fprintf(stderr, "Video info query failed: %s",
		SDL_GetError());
		exit(1);
	}

	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 0);

	surface = SDL_SetVideoMode(600, 600, 32, SDL_OPENGL | SDL_GL_DOUBLEBUFFER);
	if (!surface)
	{
		fprintf(stderr, "Video mode set failed: %s", SDL_GetError());
		exit(1);
	}
}

void
resize_viewport ()
{
  glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, 600, 600, 0, -1, 1);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glDisable(GL_DEPTH_TEST);
}

void
init_opengl ()
{
	glShadeModel(GL_SMOOTH);
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glClearDepth(20.0f);
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
	glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);

	resize_viewport();
}

class Vector2
{
	public:
		Vector2 (float _x = 0.0f, float _y = 0.0f)
		{
			x = _x;
			y = _y;
		}

		float
		length ()
		{
			return sqrtf(x*x + y*y);
		}

		float x;
		float y;
};

class Mosquito
{
	public:
		Vector2 velocity;
		Vector2 position;

		static Mosquito
		random ()
		{
			Mosquito m;

			m.velocity.x = (float)(rand() % 1000) / 1000.0f - 0.5f;
			m.velocity.y = (float)(rand() % 1000) / 1000.0f - 0.5f;

			if (rand() % 2 == 0)
			{
				m.position.x = (float)(rand() % 300);
				m.position.y = (float)(rand() % 300);
			}
			else
			{
				m.position.x = (float)(rand() % 300) + 300;
				m.position.y = (float)(rand() % 300) + 300;
			}

			return m;
		}

		void
		draw ()
		{
			glLoadIdentity();

			glTranslatef(position.x, position.y, 0.0f);
			glRotatef(atan2(velocity.y, velocity.x) * 180.0f / M_PI + 90.0f, 0.0f, 0.0f, 1.0f);

			glBegin(GL_QUADS);
				glVertex2f(-2.0f, -6.0f);
				glVertex2f( 2.0f, -6.0f);
				glVertex2f( 2.0f,  6.0f);
				glVertex2f(-2.0f,  6.0f);
			glEnd();
		}

};

Vector2
operator+ (Vector2 const& _a, Vector2 const& _b)
{
	Vector2 result;
	result.x = _a.x + _b.x;
	result.y = _a.y + _b.y;

	return result;
}

Vector2
operator- (Vector2 const& _a, Vector2 const& _b)
{
	Vector2 result;
	result.x = _a.x - _b.x;
	result.y = _a.y - _b.y;

	return result;
}

Vector2&
operator/= (Vector2& _v, float _s)
{
  _v.x /= _s;
  _v.y /= _s;

  return _v;
}

Vector2&
operator+= (Vector2& _a, Vector2& _b)
{
  _a.x += _b.x;
  _a.y += _b.y;

  return _a;
}

Vector2&
operator-= (Vector2& _a, Vector2& _b)
{
  _a.x -= _b.x;
  _a.y -= _b.y;

  return _a;
}

Vector2
rule_1 (Mosquito& _m, std::vector<Mosquito> _swarm)
{
	Vector2 mass_centre;

	for (auto& m : _swarm)
	{
		if (&_m != &m)
			mass_centre += m.position;
	}
	mass_centre /= (_swarm.size() - 1);

	Vector2 direction = mass_centre - _m.position;
	direction /= 50.0f;

	return direction;
}

Vector2
rule_2 (Mosquito& _m, std::vector<Mosquito> _swarm)
{
	Vector2 centre;

	for(auto& m : _swarm)
	{
		if (&_m != &m)
		{
			Vector2 difference = m.position - _m.position;
			if (difference.length() < 20.0f)
				centre -= difference;
		}
	}

	return centre;
}

Vector2
rule_3 (Mosquito& _m, std::vector<Mosquito> _swarm)
{
	Vector2 velocity;

	for(auto& m : _swarm)
	{
		if (&_m != &m)
		{
			velocity += m.velocity;
		}
	}
	velocity /= (float)(_swarm.size() - 1);

	Vector2 result;
	result = velocity - _m.velocity;
	result /= 2.0f;

	return result;
}

Vector2
rule_4 (Mosquito& _m)
{
	Vector2 top_velocity;
	Vector2 bottom_velocity;
	Vector2 left_velocity;
	Vector2 right_velocity;

	if (_m.position.x == 0.0f || _m.position.y == 0.0f ||
	    _m.position.x == 600.0f || _m.position.y == 600.0f)
		return Vector2();

	top_velocity.y = fabs(20.0f / _m.position.y);
	bottom_velocity.y = -fabs(20.0f / (_m.position.y - 600.0f));
	left_velocity.x = fabs(20.0f / _m.position.x);
	right_velocity.x = -fabs(20.0f / (_m.position.x - 600.0f));

	Vector2 result = top_velocity + bottom_velocity + left_velocity +
	    right_velocity;

	result /= 0.1f;

	return result;
}

void
draw_scene (std::vector<Mosquito>& _swarm)
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

	glColor3ub(0, 99, 0);
	for (auto& m : _swarm)
		m.draw();
}

std::vector<Mosquito>
step (std::vector<Mosquito>& _swarm)
{
	std::vector<Mosquito> new_swarm;

	for (auto& m : _swarm)
	{
		Vector2 v1 = rule_1(m, _swarm);
		Vector2 v2 = rule_2(m, _swarm);
		Vector2 v3 = rule_3(m, _swarm);
		Vector2 v4 = rule_4(m);

		Vector2 velocity;
		velocity += v1;
		velocity += v2;
		velocity += v3;
		velocity += v4;

		velocity /= 10000.0f;

		Mosquito new_mosquito;
		new_mosquito.velocity = m.velocity + velocity;
		new_mosquito.position = m.position + new_mosquito.velocity;

		if (new_mosquito.velocity.length() > 0.6)
			new_mosquito.velocity /= 10.0f;

		new_swarm.push_back(new_mosquito);
	}

	return new_swarm;
}

void
main_loop (std::vector<Mosquito>& _swarm)
{
	is_active = true;
	SDL_Event event;

	while (!done)
	{
		while (SDL_PollEvent(&event))
		{
			switch (event.type)
			{
				case SDL_ACTIVEEVENT:
					if (event.active.state == SDL_APPACTIVE )
						is_active = (event.active.gain != 0);
				break;

				case SDL_QUIT:
					done = true;
				break;

				default:
				break;
			}
		}

		if (is_active)
		{
			_swarm = step(_swarm);
			draw_scene(_swarm);
			SDL_GL_SwapBuffers();
		}
	}
}

int
main (int argc, char *argv[])
{
	const unsigned int N = 50;
	std::vector<Mosquito> swarm;
	srand(time(NULL));

	for (unsigned int i = 0; i < N; i++)
		swarm.push_back(Mosquito::random());

  init_sdl();
	init_opengl();

	main_loop(swarm);

	return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#include <GLXW/glxw.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/transform.hpp>
#include <GLFW/glfw3.h>
#include <iostream>
#include <vector>
#include <defer.h>
#include <chrono>

#include "utils/utils.h"
#include "utils/camera.h"
#include "utils/models.h"

void windowSizeCallback(GLFWwindow *, int width, int height) {
  glViewport(0, 0, width, height);
}

int main() {
  if(glfwInit() == GL_FALSE) {
    std::cerr << "Failed to initialize GLFW" << std::endl;
    return -1;
  }
  defer(glfwTerminate());

  glfwDefaultWindowHints();

  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  glfwWindowHint(GLFW_SAMPLES, 4);

  GLFWwindow* window = glfwCreateWindow(800, 600, "Models", nullptr, nullptr);
  if(window == nullptr) {
    std::cerr << "Failed to open GLFW window" << std::endl;
    return -1;
  }
  defer(glfwDestroyWindow(window));

  glfwMakeContextCurrent(window);

  if(glxwInit()) {
    std::cerr << "Failed to init GLXW" << std::endl;
    return -1;
  }

  glfwSwapInterval(1);
  glfwSetWindowSizeCallback(window, windowSizeCallback);
  glfwShowWindow(window);

  bool errorFlag = false;
  std::vector<GLuint> shaders;

  GLuint vertexShaderId = loadShader("shaders/vertexShader.glsl", GL_VERTEX_SHADER, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to load vertex shader (invalid working directory?)" << std::endl;
    return -1;
  }

  shaders.push_back(vertexShaderId);

  GLuint fragmentShaderId = loadShader("shaders/fragmentShader.glsl", GL_FRAGMENT_SHADER, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to load fragment shader (invalid working directory?)" << std::endl;
    return -1;
  }
  shaders.push_back(fragmentShaderId);

  GLuint programId = prepareProgram(shaders, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to prepare program" << std::endl;
    return -1;
  }
  defer(glDeleteProgram(programId));

  glDeleteShader(vertexShaderId);
  glDeleteShader(fragmentShaderId);

  // === prepare textures ===
  GLuint textureArray[3];
  int texturesNum = sizeof(textureArray)/sizeof(textureArray[0]);
  glGenTextures(texturesNum, textureArray);
  defer(glDeleteTextures(texturesNum, textureArray));

  GLuint grassTexture = textureArray[0];
  GLuint skyboxTexture = textureArray[1];
  GLuint towerTexture = textureArray[2];

  if(!loadDDSTexture("textures/grass.dds", grassTexture)) return -1;

  if(!loadDDSTexture("textures/skybox.dds", skyboxTexture)) return -1;
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

  if(!loadDDSTexture("textures/tower.dds", towerTexture)) return -1;

  // === prepare VAOs ===
  GLuint vaoArray[3];
  int vaosNum = sizeof(vaoArray)/sizeof(vaoArray[0]);
  glGenVertexArrays(vaosNum, vaoArray);
  defer(glDeleteVertexArrays(vaosNum, vaoArray));

  GLuint grassVAO = vaoArray[0];
  GLuint skyboxVAO = vaoArray[1];
  GLuint towerVAO = vaoArray[2];

  // === prepare VBOs ===
  GLuint vboArray[6];
  int vbosNum = sizeof(vboArray)/sizeof(vboArray[0]);
  glGenBuffers(vbosNum, vboArray);
  defer(glDeleteBuffers(vbosNum, vboArray));

  GLuint grassVBO = vboArray[0];
  GLuint skyboxVBO = vboArray[1];
  GLuint towerVBO = vboArray[2];
  GLuint grassIndicesVBO = vboArray[3];
  GLuint skyboxIndicesVBO = vboArray[4];
  GLuint towerIndicesVBO = vboArray[5];

  // === load models ===

  GLsizei grassIndicesNumber, skyboxIndicesNumber, towerIndicesNumber;
  GLenum grassIndexType, skyboxIndexType, towerIndexType;
  if(!modelLoad("models/grass.emd", grassVAO, grassVBO, grassIndicesVBO, &grassIndicesNumber, &grassIndexType)) return -1;
  if(!modelLoad("models/skybox.emd", skyboxVAO, skyboxVBO, skyboxIndicesVBO, &skyboxIndicesNumber, &skyboxIndexType)) return -1;
  if(!modelLoad("models/tower.emd", towerVAO, towerVBO, towerIndicesVBO, &towerIndicesNumber, &towerIndexType)) return -1;

  glm::mat4 projection = glm::perspective(70.0f, 4.0f / 3.0f, 0.3f, 250.0f);

  GLint uniformMVP = getUniformLocation(programId, "MVP");
  GLint uniformM = getUniformLocation(programId, "M");
  GLint uniformTextureSample = getUniformLocation(programId, "textureSampler");
  GLint uniformCameraPos = getUniformLocation(programId, "cameraPos");
  GLint uniformMaterialSpecularFactor = getUniformLocation(programId, "materialSpecularFactor");
  GLint uniformMaterialSpecularIntensity = getUniformLocation(programId, "materialSpecularIntensity");
  GLint uniformDirectionalLightDirection = getUniformLocation(programId, "directionalLight.direction");
  GLint uniformDirectionalLightColor = getUniformLocation(programId, "directionalLight.color");
  GLint uniformDirectionalLightAmbientIntensity = getUniformLocation(programId, "directionalLight.ambientIntensity");
  GLint uniformDirectionalLightDiffuseIntensity = getUniformLocation(programId, "directionalLight.diffuseIntensity");

  auto startTime = std::chrono::high_resolution_clock::now();
  auto prevTime = startTime;

  glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // hide cursor

  Camera camera(window, glm::vec3(0, 0, 5), 3.14f /* toward -Z */, 0.0f /* look at the horizon */);

  glEnable(GL_DOUBLEBUFFER);
  glEnable(GL_CULL_FACE);
  glEnable(GL_MULTISAMPLE);
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LESS);

  glClearColor(0, 0, 0, 1);

  glUniform1i(uniformTextureSample, 0);

  // TODO: вынести glUniform для света за тело цикла + ставить view uniform только один раз в цикле
  while(glfwWindowShouldClose(window) == GL_FALSE) {
    if(glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) break;

    if(glfwGetKey(window, GLFW_KEY_Z) == GLFW_PRESS) {
      glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    }

    if(glfwGetKey(window, GLFW_KEY_X) == GLFW_PRESS) {
      glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    }

    auto currentTime = std::chrono::high_resolution_clock::now();
    float startDeltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - startTime).count();
    float prevDeltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - prevTime).count();
    prevTime = currentTime;

    float rotationTimeMs = 100000.0f;
    float currentRotation = startDeltaTimeMs / rotationTimeMs;
    float islandAngle = 360.0f*(currentRotation - (long)currentRotation);

    glm::vec3 cameraPos;
    camera.getPosition(&cameraPos);

    glUniform3f(uniformCameraPos, cameraPos.x, cameraPos.y, cameraPos.z);

    glm::vec3 directionalLightColor(1.0f, 1.0f, 1.0f);
    glUniform3f(uniformDirectionalLightColor, directionalLightColor.r, directionalLightColor.g, directionalLightColor.b);

    glm::vec3 directionalLightDirection = glm::normalize(glm::vec3(0.0f, -1.0f, 1.0f));
    glUniform3f(uniformDirectionalLightDirection, directionalLightDirection.x, directionalLightDirection.y, directionalLightDirection.z);

    float directionalLightAmbientIntensity = 0.2f;
    glUniform1f(uniformDirectionalLightAmbientIntensity, directionalLightAmbientIntensity);

    float directionalLightDiffuseIntensity = 1.0f;
    glUniform1f(uniformDirectionalLightDiffuseIntensity, directionalLightDiffuseIntensity);

    glm::mat4 view;
    camera.getViewMatrix(prevDeltaTimeMs, &view);
    glm::mat4 vp = projection * view;

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(programId);

    glm::mat4 towerM = glm::rotate(islandAngle, 0.0f, 1.0f, 0.0f) * glm::translate(-1.5f, -1.0f, -1.5f);
    glm::mat4 towerMVP = vp * towerM;

    glBindTexture(GL_TEXTURE_2D, towerTexture);
    glBindVertexArray(towerVAO);
    glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &towerMVP[0][0]);
    glUniformMatrix4fv(uniformM, 1, GL_FALSE, &towerM[0][0]);
    glUniform1f(uniformMaterialSpecularFactor, 1.0f);
    glUniform1f(uniformMaterialSpecularIntensity, 0.0f);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, towerIndicesVBO);
    glDrawElements(GL_TRIANGLES, towerIndicesNumber, towerIndexType, nullptr);

    glm::mat4 grassM = glm::rotate(islandAngle, 0.0f, 1.0f, 0.0f) * glm::translate(0.0f, -1.0f, 0.0f);
    glm::mat4 grassMVP = vp * grassM;

    glBindTexture(GL_TEXTURE_2D, grassTexture);
    glBindVertexArray(grassVAO);
    glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &grassMVP[0][0]);
    glUniformMatrix4fv(uniformM, 1, GL_FALSE, &grassM[0][0]);
    glUniform1f(uniformMaterialSpecularFactor, 32.0f);
    glUniform1f(uniformMaterialSpecularIntensity, 2.0f);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, grassIndicesVBO);
    glDrawElements(GL_TRIANGLES, grassIndicesNumber, grassIndexType, nullptr);

    glm::mat4 skyboxM = glm::translate(cameraPos) * glm::scale(100.0f,100.0f,100.0f);
    glm::mat4 skyboxMVP = vp * skyboxM;

    // TODO: implement modelDraw procedure (or maybe Model object?)
    glBindTexture(GL_TEXTURE_2D, skyboxTexture);
    glBindVertexArray(skyboxVAO);
    glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &skyboxMVP[0][0]);
    glUniformMatrix4fv(uniformM, 1, GL_FALSE, &skyboxM[0][0]);
    glUniform1f(uniformMaterialSpecularFactor, 1.0f);
    glUniform1f(uniformMaterialSpecularIntensity, 0.0f);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skyboxIndicesVBO);
    glDrawElements(GL_TRIANGLES, skyboxIndicesNumber, skyboxIndexType, nullptr);

    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  return 0;
}
<commit_msg>Minor changes<commit_after>#include <GLXW/glxw.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/transform.hpp>
#include <GLFW/glfw3.h>
#include <iostream>
#include <vector>
#include <defer.h>
#include <chrono>

#include "utils/utils.h"
#include "utils/camera.h"
#include "utils/models.h"

void windowSizeCallback(GLFWwindow *, int width, int height) {
  glViewport(0, 0, width, height);
}

int main() {
  if(glfwInit() == GL_FALSE) {
    std::cerr << "Failed to initialize GLFW" << std::endl;
    return -1;
  }
  defer(glfwTerminate());

  glfwDefaultWindowHints();

  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  glfwWindowHint(GLFW_SAMPLES, 4);

  GLFWwindow* window = glfwCreateWindow(800, 600, "Models", nullptr, nullptr);
  if(window == nullptr) {
    std::cerr << "Failed to open GLFW window" << std::endl;
    return -1;
  }
  defer(glfwDestroyWindow(window));

  glfwMakeContextCurrent(window);

  if(glxwInit()) {
    std::cerr << "Failed to init GLXW" << std::endl;
    return -1;
  }

  glfwSwapInterval(1);
  glfwSetWindowSizeCallback(window, windowSizeCallback);
  glfwShowWindow(window);

  bool errorFlag = false;
  std::vector<GLuint> shaders;

  GLuint vertexShaderId = loadShader("shaders/vertexShader.glsl", GL_VERTEX_SHADER, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to load vertex shader (invalid working directory?)" << std::endl;
    return -1;
  }

  shaders.push_back(vertexShaderId);

  GLuint fragmentShaderId = loadShader("shaders/fragmentShader.glsl", GL_FRAGMENT_SHADER, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to load fragment shader (invalid working directory?)" << std::endl;
    return -1;
  }
  shaders.push_back(fragmentShaderId);

  GLuint programId = prepareProgram(shaders, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to prepare program" << std::endl;
    return -1;
  }
  defer(glDeleteProgram(programId));

  glDeleteShader(vertexShaderId);
  glDeleteShader(fragmentShaderId);

  // === prepare textures ===
  GLuint textureArray[3];
  int texturesNum = sizeof(textureArray)/sizeof(textureArray[0]);
  glGenTextures(texturesNum, textureArray);
  defer(glDeleteTextures(texturesNum, textureArray));

  GLuint grassTexture = textureArray[0];
  GLuint skyboxTexture = textureArray[1];
  GLuint towerTexture = textureArray[2];

  if(!loadDDSTexture("textures/grass.dds", grassTexture)) return -1;

  if(!loadDDSTexture("textures/skybox.dds", skyboxTexture)) return -1;
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

  if(!loadDDSTexture("textures/tower.dds", towerTexture)) return -1;

  // === prepare VAOs ===
  GLuint vaoArray[3];
  int vaosNum = sizeof(vaoArray)/sizeof(vaoArray[0]);
  glGenVertexArrays(vaosNum, vaoArray);
  defer(glDeleteVertexArrays(vaosNum, vaoArray));

  GLuint grassVAO = vaoArray[0];
  GLuint skyboxVAO = vaoArray[1];
  GLuint towerVAO = vaoArray[2];

  // === prepare VBOs ===
  GLuint vboArray[6];
  int vbosNum = sizeof(vboArray)/sizeof(vboArray[0]);
  glGenBuffers(vbosNum, vboArray);
  defer(glDeleteBuffers(vbosNum, vboArray));

  GLuint grassVBO = vboArray[0];
  GLuint skyboxVBO = vboArray[1];
  GLuint towerVBO = vboArray[2];
  GLuint grassIndicesVBO = vboArray[3];
  GLuint skyboxIndicesVBO = vboArray[4];
  GLuint towerIndicesVBO = vboArray[5];

  // === load models ===

  GLsizei grassIndicesNumber, skyboxIndicesNumber, towerIndicesNumber;
  GLenum grassIndexType, skyboxIndexType, towerIndexType;
  if(!modelLoad("models/grass.emd", grassVAO, grassVBO, grassIndicesVBO, &grassIndicesNumber, &grassIndexType)) return -1;
  if(!modelLoad("models/skybox.emd", skyboxVAO, skyboxVBO, skyboxIndicesVBO, &skyboxIndicesNumber, &skyboxIndexType)) return -1;
  if(!modelLoad("models/tower.emd", towerVAO, towerVBO, towerIndicesVBO, &towerIndicesNumber, &towerIndexType)) return -1;

  glm::mat4 projection = glm::perspective(70.0f, 4.0f / 3.0f, 0.3f, 250.0f);

  GLint uniformMVP = getUniformLocation(programId, "MVP");
  GLint uniformM = getUniformLocation(programId, "M");
  GLint uniformTextureSample = getUniformLocation(programId, "textureSampler");
  GLint uniformCameraPos = getUniformLocation(programId, "cameraPos");

  GLint uniformMaterialSpecularFactor = getUniformLocation(programId, "materialSpecularFactor");
  GLint uniformMaterialSpecularIntensity = getUniformLocation(programId, "materialSpecularIntensity");

  GLint uniformDirectionalLightDirection = getUniformLocation(programId, "directionalLight.direction");
  GLint uniformDirectionalLightColor = getUniformLocation(programId, "directionalLight.color");
  GLint uniformDirectionalLightAmbientIntensity = getUniformLocation(programId, "directionalLight.ambientIntensity");
  GLint uniformDirectionalLightDiffuseIntensity = getUniformLocation(programId, "directionalLight.diffuseIntensity");

//  GLint uniformPointLightPosition = getUniformLocation(programId, "pointLight.position");
//  GLint uniformPointLightColor = getUniformLocation(programId, "pointLight.color");
//  GLint uniformPointLightAmbientIntensity = getUniformLocation(programId, "pointLight.ambientIntensity");
//  GLint uniformPointLightDiffuseIntensity = getUniformLocation(programId, "pointLight.diffuseIntensity");

  auto startTime = std::chrono::high_resolution_clock::now();
  auto prevTime = startTime;

  glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // hide cursor

  Camera camera(window, glm::vec3(0, 0, 5), 3.14f /* toward -Z */, 0.0f /* look at the horizon */);

  glEnable(GL_DOUBLEBUFFER);
  glEnable(GL_CULL_FACE);
  glEnable(GL_MULTISAMPLE);
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LESS);
  glClearColor(0, 0, 0, 1);

  glUseProgram(programId);

  glUniform1i(uniformTextureSample, 0);

  glm::vec3 directionalLightColor(1.0f, 1.0f, 1.0f);
  glUniform3f(uniformDirectionalLightColor, directionalLightColor.r, directionalLightColor.g, directionalLightColor.b);

  glm::vec3 directionalLightDirection = glm::normalize(glm::vec3(0.0f, -1.0f, 1.0f));
  glUniform3f(uniformDirectionalLightDirection, directionalLightDirection.x, directionalLightDirection.y, directionalLightDirection.z);

  float directionalLightAmbientIntensity = 0.2f;
  glUniform1f(uniformDirectionalLightAmbientIntensity, directionalLightAmbientIntensity);

  float directionalLightDiffuseIntensity = 1.0f;
  glUniform1f(uniformDirectionalLightDiffuseIntensity, directionalLightDiffuseIntensity);

  while(glfwWindowShouldClose(window) == GL_FALSE) {
    if(glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) break;

    if(glfwGetKey(window, GLFW_KEY_Z) == GLFW_PRESS) {
      glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    }

    if(glfwGetKey(window, GLFW_KEY_X) == GLFW_PRESS) {
      glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    }

    auto currentTime = std::chrono::high_resolution_clock::now();
    float startDeltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - startTime).count();
    float prevDeltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - prevTime).count();
    prevTime = currentTime;

    float rotationTimeMs = 100000.0f;
    float currentRotation = startDeltaTimeMs / rotationTimeMs;
    float islandAngle = 360.0f*(currentRotation - (long)currentRotation);

    glm::vec3 cameraPos;
    camera.getPosition(&cameraPos);

    glUniform3f(uniformCameraPos, cameraPos.x, cameraPos.y, cameraPos.z);

    glm::mat4 view;
    camera.getViewMatrix(prevDeltaTimeMs, &view);
    glm::mat4 vp = projection * view;

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glm::mat4 towerM = glm::rotate(islandAngle, 0.0f, 1.0f, 0.0f) * glm::translate(-1.5f, -1.0f, -1.5f);
    glm::mat4 towerMVP = vp * towerM;

    glBindTexture(GL_TEXTURE_2D, towerTexture);
    glBindVertexArray(towerVAO);
    glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &towerMVP[0][0]);
    glUniformMatrix4fv(uniformM, 1, GL_FALSE, &towerM[0][0]);
    glUniform1f(uniformMaterialSpecularFactor, 1.0f);
    glUniform1f(uniformMaterialSpecularIntensity, 0.0f);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, towerIndicesVBO);
    glDrawElements(GL_TRIANGLES, towerIndicesNumber, towerIndexType, nullptr);

    glm::mat4 grassM = glm::rotate(islandAngle, 0.0f, 1.0f, 0.0f) * glm::translate(0.0f, -1.0f, 0.0f);
    glm::mat4 grassMVP = vp * grassM;

    glBindTexture(GL_TEXTURE_2D, grassTexture);
    glBindVertexArray(grassVAO);
    glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &grassMVP[0][0]);
    glUniformMatrix4fv(uniformM, 1, GL_FALSE, &grassM[0][0]);
    glUniform1f(uniformMaterialSpecularFactor, 32.0f);
    glUniform1f(uniformMaterialSpecularIntensity, 2.0f);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, grassIndicesVBO);
    glDrawElements(GL_TRIANGLES, grassIndicesNumber, grassIndexType, nullptr);

    glm::mat4 skyboxM = glm::translate(cameraPos) * glm::scale(100.0f,100.0f,100.0f);
    glm::mat4 skyboxMVP = vp * skyboxM;

    // TODO: implement modelDraw procedure (or maybe Model object?)
    glBindTexture(GL_TEXTURE_2D, skyboxTexture);
    glBindVertexArray(skyboxVAO);
    glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &skyboxMVP[0][0]);
    glUniformMatrix4fv(uniformM, 1, GL_FALSE, &skyboxM[0][0]);
    glUniform1f(uniformMaterialSpecularFactor, 1.0f);
    glUniform1f(uniformMaterialSpecularIntensity, 0.0f);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skyboxIndicesVBO);
    glDrawElements(GL_TRIANGLES, skyboxIndicesNumber, skyboxIndexType, nullptr);

    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  return 0;
}
<|endoftext|>


<commit_before>
/*
Author: Tristan Bepler (tbepler@gmail.com)
*/

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>

using namespace std;

vector<string> split( const string& line ){
    stringstream ss( line );
    vector<string> tokens;
    string token;
    while( !ss.eof() ){
        ss >> token;
        tokens.push_back( token );
    }
    return tokens;
}

void transpose( istream& in, ostream& out ){
    string line;
    vector< vector<string> > entries;
    vector<string> row;
    size_t maxLen = 0;
    while( getline( in, line ) ){
        row = split( line );
        entries.push_back( row );
        if( row.size() > maxLen ) maxLen = row.size();
    }

    //transpose
    for( size_t j = 0 ; j < maxLen ; ++j ){
        for( size_t i = 0 ; i < entries.size() ; ++i ){
            row = entries[i];
            if( j < row.size() ) out << row[j];
            out << " ";
        }
        out << endl;
    }

}

int main( int argc, const char* argv[] ){

    for( int i = 1 ; i < argc ; ++i ){
        string arg(argv[i]);
        if( arg == "--help" || arg == "-h" ){
            cerr << "Usage: transpose [FILES] [ < FILE ]" << endl;
            return 0;
        }
    }

    if( argc > 1 ){
        for( int i = 1 ; i < argc ; ++i ){
            ifstream in( argv[i] );
            if( in.is_open() ){
                transpose( in, cout );
                in.close();
            }else{
                cerr << "Unable to open file: " << argv[i] << endl;
            }
        }
    }else{
        transpose( cin, cout );
    }

}
<commit_msg>added ability to transpose files in place<commit_after>
/*
Author: Tristan Bepler (tbepler@gmail.com)
*/

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>

using namespace std;

vector<string> split( const string& line ){
    stringstream ss( line );
    vector<string> tokens;
    string token;
    while( !ss.eof() ){
        token.clear();
        ss >> token;
        if( !token.empty() ){
            tokens.push_back( token );
        }
    }
    return tokens;
}

struct Transpose{

    vector< vector< string > > entries;
    size_t maxRow;

};

istream& operator>> ( istream& in, Transpose& t ){
    t.entries.clear();
    t.maxRow = 0;
    string line;
    vector<string> row;
    while( getline( in, line ) ){
        row = split( line );
        t.entries.push_back( row );
        if( row.size() > t.maxRow ) t.maxRow = row.size();
    }
    return in;
}

ostream& operator<< ( ostream& out, Transpose& t ){
    //transpose
    vector<string> row;
    for( size_t j = 0 ; j < t.maxRow ; ++j ){
        for( size_t i = 0 ; i < t.entries.size() ; ++i ){
            row = t.entries[i];
            if( j < row.size() ){
                out << row[j];
            }
            out << " ";
        }
        out << endl;
    }
    return out;
}

void usage( ostream& out ){
    out << "Usage: transpose [--help/-h] [--in-place/-i] [FILES] [ < FILE ]" << endl;
    out << "-i\t--in-place\tTransposes the files in place" << endl;
    out << "-h\t--help\tDisplays this help statement" << endl;
}

int main( int argc, const char* argv[] ){

    vector<const char*> files;
    bool inplace = false;

    for( int i = 1 ; i < argc ; ++i ){
        string arg(argv[i]);
        if( arg == "--help" || arg == "-h" ){
            usage( cerr );
            return 0;
        }else if( arg == "--in-place" || arg == "-i" ){
            inplace = true;
        }else{
            files.push_back( argv[i] );
        }
    }

    Transpose t;
    if( !files.empty() ){
        fstream fin;
        fstream fout;
        for( size_t i = 0 ; i < files.size() ; ++i ){
            fin.open( files[i], ios::in );
            if( fin.is_open() ){
                fin >> t;
                fin.close();
                if( inplace ){
                    fout.open( files[i], ios::out | ios::trunc );
                    if( fout.is_open() ){
                        fout << t;
                        fout.close();
                    }else{
                        cerr << "Unable to open file for writing: " << files[i] << endl;
                    }
                }else{
                    cout << t;
                }
            }else{
                cerr << "Unable to open file for reading: " << files[i] << endl;
            }
        }
    }else{
        cin >> t;
        cout << t;
    }

}
<|endoftext|>


<commit_before>4d817cfd-ad5d-11e7-8335-ac87a332f658<commit_msg>Bug fixes and performance improvements<commit_after>4dff00bd-ad5d-11e7-b2da-ac87a332f658<|endoftext|>


<commit_before>//
//  main.cpp
//  Chip8
//
//  Created by Tyson Decker on 2/12/14.
//  Copyright (c) 2014 Solving Rubik. All rights reserved.
//

#include <iostream>
#include "Chip8.h"
#include "Screen.h"
#include "unistd.h"

Chip8 chip8;
Screen screen;

int main(int argc, const char * argv[])
{
    std::cout << "Chip8 Emulator\n";
    std::cout << "Made By: Tyson Decker\n";

    // Init the Chip8
    chip8.loadRom(argv[1]);
    chip8.printMemory();

    // Emulation Loop

    while(chip8.running)
    {
        // Emulate One Cycle
        chip8.emulateCycle();

        // Check Draw Flag
        if(chip8.drawFlag)
            chip8.drawScreen();

        // Store Keypress state
//for(int i = 0; i < 800000; i++){}
    }

    return 0;
}

<commit_msg>Removed unused reference<commit_after>//
//  main.cpp
//  Chip8
//
//  Created by Tyson Decker on 2/12/14.
//  Copyright (c) 2014 Solving Rubik. All rights reserved.
//

#include <iostream>
#include "Chip8.h"
#include "Screen.h"
#include "unistd.h"

Chip8 chip8;

int main(int argc, const char * argv[])
{
    std::cout << "Chip8 Emulator\n";
    std::cout << "Made By: Tyson Decker\n";

    // Init the Chip8
    chip8.loadRom(argv[1]);
    chip8.printMemory();

    // Emulation Loop

    while(chip8.running)
    {
        // Emulate One Cycle
        chip8.emulateCycle();

        // Check Draw Flag
        if(chip8.drawFlag)
            chip8.drawScreen();

        // Store Keypress state
//for(int i = 0; i < 800000; i++){}
    }

    return 0;
}

<|endoftext|>