<commit_before>#include "CDT.h"
#include "VerifyTopology.h"

#include <fstream>
#include <iostream>
#include <limits>

#include <QApplication>
#include <QCheckBox>
#include <QColor>
#include <QDir>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QListWidget>
#include <QMessageBox>
#include <QOpenGLWidget>
#include <QPaintEvent>
#include <QPainter>
#include <QPushButton>
#include <QSpinBox>
#include <QTextStream>

typedef double CoordType;
typedef CDT::Triangulation<CoordType> Triangulation;
typedef CDT::V2d<CoordType> V2d;
typedef CDT::Vertex<CoordType> Vertex;
typedef CDT::Triangle Triangle;
typedef CDT::Box2d<CoordType> Box2d;
typedef CDT::Index Index;
typedef CDT::Edge Edge;

class CDTWidget : public QOpenGLWidget
{
    Q_OBJECT

public:
    explicit CDTWidget(QWidget* parent = NULL)
        : QOpenGLWidget(parent)
    {
        setAutoFillBackground(false);
    }

    QSize sizeHint() const
    {
        return QSize(9001, 9001); // over 9000!
    }

public slots:
    void buildCDT(QListWidgetItem* item)
    {
        QDir dir = QDir(QDir::currentPath(), tr("*.txt"));
        dir.setPath(QStringLiteral("../test files"));
        const QString fileName = dir.filePath(item->text());
        readData(fileName);
        updateCDT();
    }

    void setPointsLimit(int limit)
    {
        m_ptLimit = static_cast<std::size_t>(limit);
        updateCDT();
    }

    void setEdgeLimit(int limit)
    {
        m_edgeLimit = static_cast<std::size_t>(limit);
        updateCDT();
    }

    void hidePoints(int isHidePoints)
    {
        m_isHidePoints = (isHidePoints != 0);
        update();
    }

    void hideSuperTriangle(int isHideSuperTri)
    {
        m_isHideSuperTri = (isHideSuperTri != 0);
        updateCDT();
    }

    void removeOuterTriangles(int isRemoveOuter)
    {
        m_isRemoveOuter = (isRemoveOuter != 0);
        updateCDT();
    }

    void prtScn()
    {}

    void saveToOff()
    {
        std::ofstream fout("out.off");
        fout.precision(std::numeric_limits<CoordType>::digits10 + 1);
        if(!fout.is_open())
            throw std::runtime_error("Save can't open file for writing OFF");
        fout << "OFF\n";

        fout << m_cdt.vertices.size() << ' ' << m_cdt.triangles.size()
             << " 0\n";
        // Write vertices
        const Box2d box = calculateBox(m_points);
        const CoordType stZ =
            -std::fmax(box.max.x - box.min.x, box.max.y - box.min.y);
        std::size_t counter = 0;
        BOOST_FOREACH(const Vertex& v, m_cdt.vertices)
        {
            const CoordType z =
                !m_isRemoveOuter && !m_isHideSuperTri && counter < 3 ? stZ
                                                                     : 0.0;
            fout << v.pos.x << ' ' << v.pos.y << ' ' << z << "\n";
            counter++;
        }
        // Write faces
        BOOST_FOREACH(const Triangle& t, m_cdt.triangles)
        {
            fout << "3 " << t.vertices[0] << ' ' << t.vertices[1] << ' '
                 << t.vertices[2] << "\n";
        }
        fout.close();
    }

private:
    void readData(const QString& file)
    {
        QFile data(file);
        if(!data.open(QFile::ReadOnly))
        {
            QMessageBox::warning(
                this, tr("CDT"), tr("Could not open file ") + file);
        }
        QTextStream inStream(&data);
        std::size_t nPts, nEdges;
        inStream >> nPts >> nEdges;
        m_points.clear();
        for(std::size_t i = 0; i < nPts; ++i)
        {
            CoordType x1, y1;
            inStream >> x1 >> y1;
            m_points.push_back(V2d::make(x1, y1));
        }
        m_edges.clear();
        for(std::size_t i = 0; i < nEdges; ++i)
        {
            CDT::VertInd v1, v2;
            inStream >> v1 >> v2;
            m_edges.push_back(Edge(v1, v2));
        }
        inStream.skipWhiteSpace();
    }

    void updateCDT()
    {
        m_cdt = Triangulation();
        if(!m_points.empty())
        {
            const std::vector<V2d> pts =
                m_ptLimit < m_points.size()
                    ? std::vector<V2d>(&m_points[0], &m_points[m_ptLimit])
                    : m_points;
            m_cdt.insertVertices(pts);
            if(m_ptLimit >= m_points.size() && !m_edges.empty())
            {
                const std::vector<Edge> edges =
                    m_edgeLimit < m_edges.size()
                        ? std::vector<Edge>(&m_edges[0], &m_edges[m_edgeLimit])
                        : m_edges;
                m_cdt.insertEdges(edges);
            }
            if(m_isRemoveOuter)
                m_cdt.eraseOuterTriangles();
            else if(m_isHideSuperTri)
                m_cdt.eraseSuperTriangle();
        }
        if(!CDT::verifyTopology(m_cdt))
        {
            QMessageBox errBox;
            errBox.setText(QStringLiteral("Triangulation has wrong topology"));
            errBox.exec();
        }
        update();
    }

protected:
    void paintEvent(QPaintEvent*)
    {
        QPainter p(this);
        glClearColor(1.f, 1.f, 1.f, 1.f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        if(m_cdt.vertices.empty())
            return;

        const CoordType fixedSize(std::min(size().width(), size().height()));
        p.setRenderHints(QPainter::Antialiasing);
        p.translate(fixedSize / 2.0, fixedSize / 2.0);
        p.scale(1, -1);

        const Box2d box = calculateBox(m_points);
        const V2d c = {(box.min.x + box.max.x) / 2.0,
                            (box.min.y + box.max.y) / 2.0};
        const double scale =
            0.8 * fixedSize /
            (std::fmax(box.max.x - box.min.x, box.max.y - box.min.y));

        QPen pen;
        pen.setCapStyle(Qt::RoundCap);

        // Draw triangles
        pen.setWidthF(2.0);
        // outer triangles
        if(!m_isHideSuperTri && !m_isRemoveOuter)
        {
            pen.setColor(QColor(220, 220, 220));
            p.setPen(pen);
            BOOST_FOREACH(const Triangle& t, m_cdt.triangles)
            {
                if(t.vertices[0] > 2 && t.vertices[1] > 2 && t.vertices[2] > 2)
                    continue;
                const V2d& v1 = m_cdt.vertices[t.vertices[0]].pos;
                const V2d& v2 = m_cdt.vertices[t.vertices[1]].pos;
                const V2d& v3 = m_cdt.vertices[t.vertices[2]].pos;
                const QPointF pt1(scale * (v1.x - c.x), scale * (v1.y - c.y));
                const QPointF pt2(scale * (v2.x - c.x), scale * (v2.y - c.y));
                const QPointF pt3(scale * (v3.x - c.x), scale * (v3.y - c.y));
                p.drawLine(pt1, pt2);
                p.drawLine(pt2, pt3);
                p.drawLine(pt3, pt1);
            }
        }

        // actual triangles
        pen.setColor(QColor(150, 150, 150));
        p.setPen(pen);
        BOOST_FOREACH(const Triangle& t, m_cdt.triangles)
        {
            if(!m_isHideSuperTri && !m_isRemoveOuter)
                if(t.vertices[0] < 3 || t.vertices[1] < 3 || t.vertices[2] < 3)
                    continue;
            const V2d& v1 = m_cdt.vertices[t.vertices[0]].pos;
            const V2d& v2 = m_cdt.vertices[t.vertices[1]].pos;
            const V2d& v3 = m_cdt.vertices[t.vertices[2]].pos;
            const QPointF pt1(scale * (v1.x - c.x), scale * (v1.y - c.y));
            const QPointF pt2(scale * (v2.x - c.x), scale * (v2.y - c.y));
            const QPointF pt3(scale * (v3.x - c.x), scale * (v3.y - c.y));
            p.drawLine(pt1, pt2);
            p.drawLine(pt2, pt3);
            p.drawLine(pt3, pt1);
        }
        // constraint edges
        pen.setColor(QColor(50, 50, 50));
        p.setPen(pen);
        BOOST_FOREACH(const Edge& e, m_cdt.fixedEdges)
        {
            const V2d& v1 = m_cdt.vertices[e.v1()].pos;
            const V2d& v2 = m_cdt.vertices[e.v2()].pos;
            const QPointF pt1(scale * (v1.x - c.x), scale * (v1.y - c.y));
            const QPointF pt2(scale * (v2.x - c.x), scale * (v2.y - c.y));
            p.drawLine(pt1, pt2);
        }

        if(m_isHidePoints)
            return;
        // draw points
        pen.setColor(QColor(50, 50, 200));
        pen.setWidthF(7.0);
        p.setPen(pen);
        for(std::size_t i = 0; i < m_cdt.vertices.size(); ++i)
        {
            const Vertex& v = m_cdt.vertices[i];
            const QPointF pt(scale * (v.pos.x - c.x), scale * (v.pos.y - c.y));
            p.drawPoint(pt);
        }
        // last added point
        if(m_ptLimit <= m_points.size())
        {
            pen.setColor(QColor(200, 50, 50));
            pen.setWidthF(9.0);
            p.setPen(pen);
            const Vertex& v = m_cdt.vertices.back();
            const QPointF pt(scale * (v.pos.x - c.x), scale * (v.pos.y - c.y));
            p.drawPoint(pt);
        }
    }

private:
    Triangulation m_cdt;
    std::vector<V2d> m_points;
    std::vector<Edge> m_edges;
    std::size_t m_ptLimit;
    std::size_t m_edgeLimit;
    bool m_isHidePoints;
    bool m_isHideSuperTri;
    bool m_isRemoveOuter;
};

class MainWindow : public QWidget
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget* parent = Q_NULLPTR)
        : QWidget(parent)
    {
        m_cdtWidget = new CDTWidget();
        // Right pane
        QListWidget* filesList = new QListWidget();
        filesList->connect(
            filesList,
            SIGNAL(itemDoubleClicked(QListWidgetItem*)),
            m_cdtWidget,
            SLOT(buildCDT(QListWidgetItem*)));

        QSpinBox* ptsSpinbox = new QSpinBox;
        ptsSpinbox->setRange(0, 999999);
        connect(
            ptsSpinbox,
            SIGNAL(valueChanged(int)),
            m_cdtWidget,
            SLOT(setPointsLimit(int)));
        ptsSpinbox->setValue(999999);

        QSpinBox* edgesSpinbox = new QSpinBox;
        edgesSpinbox->setRange(0, 999999);
        connect(
            edgesSpinbox,
            SIGNAL(valueChanged(int)),
            m_cdtWidget,
            SLOT(setEdgeLimit(int)));
        edgesSpinbox->setValue(999999);

        QCheckBox* hidePoints = new QCheckBox(QStringLiteral("Hide points"));
        connect(
            hidePoints,
            SIGNAL(stateChanged(int)),
            m_cdtWidget,
            SLOT(hidePoints(int)));
        m_cdtWidget->hidePoints(0);
        hidePoints->setChecked(false);

        QCheckBox* hideSuperTri =
            new QCheckBox(QStringLiteral("Hide super-triangle"));
        connect(
            hideSuperTri,
            SIGNAL(stateChanged(int)),
            m_cdtWidget,
            SLOT(hideSuperTriangle(int)));
        m_cdtWidget->hideSuperTriangle(0);
        hideSuperTri->setChecked(false);

        QCheckBox* removeOuter =
            new QCheckBox(QStringLiteral("Remove outer triangles"));
        connect(
            removeOuter,
            SIGNAL(stateChanged(int)),
            m_cdtWidget,
            SLOT(removeOuterTriangles(int)));
        m_cdtWidget->removeOuterTriangles(0);
        removeOuter->setChecked(false);

        QPushButton* screenshotBtn = new QPushButton(tr("Make Screenshot"));
        connect(screenshotBtn, SIGNAL(clicked()), m_cdtWidget, SLOT(prtScn()));
        screenshotBtn->setMinimumHeight(50);

        QPushButton* saveBtn = new QPushButton(tr("Save to .OFF"));
        connect(saveBtn, SIGNAL(clicked()), m_cdtWidget, SLOT(saveToOff()));
        saveBtn->setMinimumHeight(50);

        QGridLayout* rightLayout = new QGridLayout;
        int cntr = 0;
        rightLayout->addWidget(filesList, cntr++, 0);
        rightLayout->addWidget(ptsSpinbox, cntr++, 0);
        rightLayout->addWidget(edgesSpinbox, cntr++, 0);
        rightLayout->addWidget(hidePoints, cntr++, 0);
        rightLayout->addWidget(removeOuter, cntr++, 0);
        rightLayout->addWidget(hideSuperTri, cntr++, 0);
        rightLayout->addWidget(screenshotBtn, cntr++, 0);
        rightLayout->addWidget(saveBtn, cntr++, 0);

        // Center
        QHBoxLayout* centralLayout = new QHBoxLayout;
        centralLayout->addWidget(m_cdtWidget);
        centralLayout->addLayout(rightLayout);
        setLayout(centralLayout);

        setWindowTitle(tr("CDT Visualizer"));

        // Read files list
        QDir dir = QDir(QDir::currentPath(), tr("*.txt"));
        dir.setPath(QStringLiteral("../test files"));
        QFileInfoList list = dir.entryInfoList();
        filesList->clear();
        QFileInfoList::iterator it;
        for(it = list.begin(); it != list.end(); ++it)
            filesList->addItem(it->fileName());
        filesList->setCurrentRow(0);
    }

private:
    CDTWidget* m_cdtWidget;
};

int main(int argc, char* argv[])
{
    QSurfaceFormat fmt;
    fmt.setSamples(8);
    QSurfaceFormat::setDefaultFormat(fmt);

    QApplication app(argc, argv);
    MainWindow window;
    window.show();
    return app.exec();
}

#include "main.moc"
<commit_msg>Fix static-analysis warnings<commit_after>#include "CDT.h"
#include "VerifyTopology.h"

#include <fstream>
#include <iostream>
#include <limits>

#include <QApplication>
#include <QCheckBox>
#include <QColor>
#include <QDir>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QListWidget>
#include <QMessageBox>
#include <QOpenGLWidget>
#include <QPaintEvent>
#include <QPainter>
#include <QPushButton>
#include <QSpinBox>
#include <QTextStream>

typedef double CoordType;
typedef CDT::Triangulation<CoordType> Triangulation;
typedef CDT::V2d<CoordType> V2d;
typedef CDT::Vertex<CoordType> Vertex;
typedef CDT::Triangle Triangle;
typedef CDT::Box2d<CoordType> Box2d;
typedef CDT::Index Index;
typedef CDT::Edge Edge;

class CDTWidget : public QOpenGLWidget
{
    Q_OBJECT

public:
    explicit CDTWidget(QWidget* parent = NULL)
        : QOpenGLWidget(parent)
        , m_ptLimit(9999999)
        , m_edgeLimit(9999999)
        , m_isHidePoints(false)
        , m_isHideSuperTri(false)
        , m_isRemoveOuter(false)
    {
        setAutoFillBackground(false);
    }

    QSize sizeHint() const
    {
        return QSize(9001, 9001); // over 9000!
    }

public slots:
    void buildCDT(QListWidgetItem* item)
    {
        QDir dir = QDir(QDir::currentPath(), tr("*.txt"));
        dir.setPath(QStringLiteral("../test files"));
        const QString fileName = dir.filePath(item->text());
        readData(fileName);
        updateCDT();
    }

    void setPointsLimit(int limit)
    {
        m_ptLimit = static_cast<std::size_t>(limit);
        updateCDT();
    }

    void setEdgeLimit(int limit)
    {
        m_edgeLimit = static_cast<std::size_t>(limit);
        updateCDT();
    }

    void hidePoints(int isHidePoints)
    {
        m_isHidePoints = (isHidePoints != 0);
        update();
    }

    void hideSuperTriangle(int isHideSuperTri)
    {
        m_isHideSuperTri = (isHideSuperTri != 0);
        updateCDT();
    }

    void removeOuterTriangles(int isRemoveOuter)
    {
        m_isRemoveOuter = (isRemoveOuter != 0);
        updateCDT();
    }

    void prtScn()
    {}

    void saveToOff()
    {
        std::ofstream fout("out.off");
        fout.precision(std::numeric_limits<CoordType>::digits10 + 1);
        if(!fout.is_open())
            throw std::runtime_error("Save can't open file for writing OFF");
        fout << "OFF\n";

        fout << m_cdt.vertices.size() << ' ' << m_cdt.triangles.size()
             << " 0\n";
        // Write vertices
        const Box2d box = calculateBox(m_points);
        const CoordType stZ =
            -std::fmax(box.max.x - box.min.x, box.max.y - box.min.y);
        std::size_t counter = 0;
        BOOST_FOREACH(const Vertex& v, m_cdt.vertices)
        {
            const CoordType z =
                !m_isRemoveOuter && !m_isHideSuperTri && counter < 3 ? stZ
                                                                     : 0.0;
            fout << v.pos.x << ' ' << v.pos.y << ' ' << z << "\n";
            counter++;
        }
        // Write faces
        BOOST_FOREACH(const Triangle& t, m_cdt.triangles)
        {
            fout << "3 " << t.vertices[0] << ' ' << t.vertices[1] << ' '
                 << t.vertices[2] << "\n";
        }
        fout.close();
    }

private:
    void readData(const QString& file)
    {
        QFile data(file);
        if(!data.open(QFile::ReadOnly))
        {
            QMessageBox::warning(
                this, tr("CDT"), tr("Could not open file ") + file);
        }
        QTextStream inStream(&data);
        std::size_t nPts, nEdges;
        inStream >> nPts >> nEdges;
        m_points.clear();
        for(std::size_t i = 0; i < nPts; ++i)
        {
            CoordType x1, y1;
            inStream >> x1 >> y1;
            m_points.push_back(V2d::make(x1, y1));
        }
        m_edges.clear();
        for(std::size_t i = 0; i < nEdges; ++i)
        {
            CDT::VertInd v1, v2;
            inStream >> v1 >> v2;
            m_edges.push_back(Edge(v1, v2));
        }
        inStream.skipWhiteSpace();
    }

    void updateCDT()
    {
        m_cdt = Triangulation();
        if(!m_points.empty())
        {
            const std::vector<V2d> pts =
                m_ptLimit < m_points.size()
                    ? std::vector<V2d>(&m_points[0], &m_points[m_ptLimit])
                    : m_points;
            m_cdt.insertVertices(pts);
            if(m_ptLimit >= m_points.size() && !m_edges.empty())
            {
                const std::vector<Edge> edges =
                    m_edgeLimit < m_edges.size()
                        ? std::vector<Edge>(&m_edges[0], &m_edges[m_edgeLimit])
                        : m_edges;
                m_cdt.insertEdges(edges);
            }
            if(m_isRemoveOuter)
                m_cdt.eraseOuterTriangles();
            else if(m_isHideSuperTri)
                m_cdt.eraseSuperTriangle();
        }
        if(!CDT::verifyTopology(m_cdt))
        {
            QMessageBox errBox;
            errBox.setText(QStringLiteral("Triangulation has wrong topology"));
            errBox.exec();
        }
        update();
    }

protected:
    void paintEvent(QPaintEvent*)
    {
        QPainter p(this);
        glClearColor(1.f, 1.f, 1.f, 1.f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        if(m_cdt.vertices.empty())
            return;

        const CoordType fixedSize(std::min(size().width(), size().height()));
        p.setRenderHints(QPainter::Antialiasing);
        p.translate(fixedSize / 2.0, fixedSize / 2.0);
        p.scale(1, -1);

        const Box2d box = calculateBox(m_points);
        const V2d c = {(box.min.x + box.max.x) / 2.0,
                            (box.min.y + box.max.y) / 2.0};
        const double scale =
            0.8 * fixedSize /
            (std::fmax(box.max.x - box.min.x, box.max.y - box.min.y));

        QPen pen;
        pen.setCapStyle(Qt::RoundCap);

        // Draw triangles
        pen.setWidthF(2.0);
        // outer triangles
        if(!m_isHideSuperTri && !m_isRemoveOuter)
        {
            pen.setColor(QColor(220, 220, 220));
            p.setPen(pen);
            BOOST_FOREACH(const Triangle& t, m_cdt.triangles)
            {
                if(t.vertices[0] > 2 && t.vertices[1] > 2 && t.vertices[2] > 2)
                    continue;
                const V2d& v1 = m_cdt.vertices[t.vertices[0]].pos;
                const V2d& v2 = m_cdt.vertices[t.vertices[1]].pos;
                const V2d& v3 = m_cdt.vertices[t.vertices[2]].pos;
                const QPointF pt1(scale * (v1.x - c.x), scale * (v1.y - c.y));
                const QPointF pt2(scale * (v2.x - c.x), scale * (v2.y - c.y));
                const QPointF pt3(scale * (v3.x - c.x), scale * (v3.y - c.y));
                p.drawLine(pt1, pt2);
                p.drawLine(pt2, pt3);
                p.drawLine(pt3, pt1);
            }
        }

        // actual triangles
        pen.setColor(QColor(150, 150, 150));
        p.setPen(pen);
        BOOST_FOREACH(const Triangle& t, m_cdt.triangles)
        {
            if(!m_isHideSuperTri && !m_isRemoveOuter)
                if(t.vertices[0] < 3 || t.vertices[1] < 3 || t.vertices[2] < 3)
                    continue;
            const V2d& v1 = m_cdt.vertices[t.vertices[0]].pos;
            const V2d& v2 = m_cdt.vertices[t.vertices[1]].pos;
            const V2d& v3 = m_cdt.vertices[t.vertices[2]].pos;
            const QPointF pt1(scale * (v1.x - c.x), scale * (v1.y - c.y));
            const QPointF pt2(scale * (v2.x - c.x), scale * (v2.y - c.y));
            const QPointF pt3(scale * (v3.x - c.x), scale * (v3.y - c.y));
            p.drawLine(pt1, pt2);
            p.drawLine(pt2, pt3);
            p.drawLine(pt3, pt1);
        }
        // constraint edges
        pen.setColor(QColor(50, 50, 50));
        p.setPen(pen);
        BOOST_FOREACH(const Edge& e, m_cdt.fixedEdges)
        {
            const V2d& v1 = m_cdt.vertices[e.v1()].pos;
            const V2d& v2 = m_cdt.vertices[e.v2()].pos;
            const QPointF pt1(scale * (v1.x - c.x), scale * (v1.y - c.y));
            const QPointF pt2(scale * (v2.x - c.x), scale * (v2.y - c.y));
            p.drawLine(pt1, pt2);
        }

        if(m_isHidePoints)
            return;
        // draw points
        pen.setColor(QColor(50, 50, 200));
        pen.setWidthF(7.0);
        p.setPen(pen);
        for(std::size_t i = 0; i < m_cdt.vertices.size(); ++i)
        {
            const Vertex& v = m_cdt.vertices[i];
            const QPointF pt(scale * (v.pos.x - c.x), scale * (v.pos.y - c.y));
            p.drawPoint(pt);
        }
        // last added point
        if(m_ptLimit <= m_points.size())
        {
            pen.setColor(QColor(200, 50, 50));
            pen.setWidthF(9.0);
            p.setPen(pen);
            const Vertex& v = m_cdt.vertices.back();
            const QPointF pt(scale * (v.pos.x - c.x), scale * (v.pos.y - c.y));
            p.drawPoint(pt);
        }
    }

private:
    Triangulation m_cdt;
    std::vector<V2d> m_points;
    std::vector<Edge> m_edges;
    std::size_t m_ptLimit;
    std::size_t m_edgeLimit;
    bool m_isHidePoints;
    bool m_isHideSuperTri;
    bool m_isRemoveOuter;
};

class MainWindow : public QWidget
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget* parent = Q_NULLPTR)
        : QWidget(parent)
    {
        m_cdtWidget = new CDTWidget();
        // Right pane
        QListWidget* filesList = new QListWidget();
        connect(
            filesList,
            SIGNAL(itemDoubleClicked(QListWidgetItem*)),
            m_cdtWidget,
            SLOT(buildCDT(QListWidgetItem*)));

        QSpinBox* ptsSpinbox = new QSpinBox;
        ptsSpinbox->setRange(0, 999999);
        connect(
            ptsSpinbox,
            SIGNAL(valueChanged(int)),
            m_cdtWidget,
            SLOT(setPointsLimit(int)));
        ptsSpinbox->setValue(999999);

        QSpinBox* edgesSpinbox = new QSpinBox;
        edgesSpinbox->setRange(0, 999999);
        connect(
            edgesSpinbox,
            SIGNAL(valueChanged(int)),
            m_cdtWidget,
            SLOT(setEdgeLimit(int)));
        edgesSpinbox->setValue(999999);

        QCheckBox* hidePoints = new QCheckBox(QStringLiteral("Hide points"));
        connect(
            hidePoints,
            SIGNAL(stateChanged(int)),
            m_cdtWidget,
            SLOT(hidePoints(int)));
        m_cdtWidget->hidePoints(0);
        hidePoints->setChecked(false);

        QCheckBox* hideSuperTri =
            new QCheckBox(QStringLiteral("Hide super-triangle"));
        connect(
            hideSuperTri,
            SIGNAL(stateChanged(int)),
            m_cdtWidget,
            SLOT(hideSuperTriangle(int)));
        m_cdtWidget->hideSuperTriangle(0);
        hideSuperTri->setChecked(false);

        QCheckBox* removeOuter =
            new QCheckBox(QStringLiteral("Remove outer triangles"));
        connect(
            removeOuter,
            SIGNAL(stateChanged(int)),
            m_cdtWidget,
            SLOT(removeOuterTriangles(int)));
        m_cdtWidget->removeOuterTriangles(0);
        removeOuter->setChecked(false);

        QPushButton* screenshotBtn = new QPushButton(tr("Make Screenshot"));
        connect(screenshotBtn, SIGNAL(clicked()), m_cdtWidget, SLOT(prtScn()));
        screenshotBtn->setMinimumHeight(50);

        QPushButton* saveBtn = new QPushButton(tr("Save to .OFF"));
        connect(saveBtn, SIGNAL(clicked()), m_cdtWidget, SLOT(saveToOff()));
        saveBtn->setMinimumHeight(50);

        QGridLayout* rightLayout = new QGridLayout;
        int cntr = 0;
        rightLayout->addWidget(filesList, cntr++, 0);
        rightLayout->addWidget(ptsSpinbox, cntr++, 0);
        rightLayout->addWidget(edgesSpinbox, cntr++, 0);
        rightLayout->addWidget(hidePoints, cntr++, 0);
        rightLayout->addWidget(removeOuter, cntr++, 0);
        rightLayout->addWidget(hideSuperTri, cntr++, 0);
        rightLayout->addWidget(screenshotBtn, cntr++, 0);
        rightLayout->addWidget(saveBtn, cntr++, 0);

        // Center
        QHBoxLayout* centralLayout = new QHBoxLayout;
        centralLayout->addWidget(m_cdtWidget);
        centralLayout->addLayout(rightLayout);
        setLayout(centralLayout);

        setWindowTitle(tr("CDT Visualizer"));

        // Read files list
        QDir dir = QDir(QDir::currentPath(), tr("*.txt"));
        dir.setPath(QStringLiteral("../test files"));
        QFileInfoList list = dir.entryInfoList();
        filesList->clear();
        QFileInfoList::iterator it;
        for(it = list.begin(); it != list.end(); ++it)
            filesList->addItem(it->fileName());
        filesList->setCurrentRow(0);
    }

private:
    CDTWidget* m_cdtWidget;
};

int main(int argc, char* argv[])
{
    QSurfaceFormat fmt;
    fmt.setSamples(8);
    QSurfaceFormat::setDefaultFormat(fmt);

    QApplication app(argc, argv);
    MainWindow window;
    window.show();
    return QApplication::exec();
}

#include "main.moc"
<|endoftext|>


<commit_before>
// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"

#include "App/Factories/AdditionNFDelegate.h"
#include "App/Factories/ConstantNFDelegate.h"
#include "App/Factories/PrinterNFDelegate.h"
#include "App/Factories/TextFileNFDelegate.h"

#include "System/QtBasedFileSystem.h"

// Qt.
#include <QApplication>

QString titleString()
{
    QString name = QString::fromStdString(App::appName());
    QString version = QString::fromStdString(App::appVersion());
    return QString("%1 - v%2").arg(name).arg(version);
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QtBasedFileSystem file_system;

    App app(&file_system);
    app.addNodeFactory(new AdditionNFDelegate);
    app.addNodeFactory(new ConstantNFDelegate);
    app.addNodeFactory(new PrinterNFDelegate);
    app.addNodeFactory(new TextFileNFDelegate);

    MainWindow w(&app);
    w.setWindowTitle(titleString());
    w.setMinimumSize(800, 600);
    w.show();

    app.setUI(&w);
    app.setDelegate(&w);

    return a.exec();
}
<commit_msg>Use function to load all script files in script directory.<commit_after>
// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"

#include "App/Factories/AdditionNFDelegate.h"
#include "App/Factories/ConstantNFDelegate.h"
#include "App/Factories/PrinterNFDelegate.h"
#include "App/Factories/TextFileNFDelegate.h"

#include "System/QtBasedFileSystem.h"

// Qt.
#include <QApplication>

QString titleString()
{
    QString name = QString::fromStdString(App::appName());
    QString version = QString::fromStdString(App::appVersion());
    return QString("%1 - v%2").arg(name).arg(version);
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QtBasedFileSystem file_system;

    App app(&file_system);
    app.addNodeFactory(new AdditionNFDelegate);
    app.addNodeFactory(new ConstantNFDelegate);
    app.addNodeFactory(new PrinterNFDelegate);
    app.addNodeFactory(new TextFileNFDelegate);
    app.loadScriptNodes("Nodin/NodeScripts/Lua");

    MainWindow w(&app);
    w.setWindowTitle(titleString());
    w.setMinimumSize(800, 600);
    w.show();

    app.setUI(&w);
    app.setDelegate(&w);

    return a.exec();
}
<|endoftext|>


<commit_before>#include "server.hpp"
#include "logger.hpp"
#include "json.hpp"

void myrpc(connection_hdl hdl, std::string callId, std::vector<WAMPP::JSON::NodePtr> args) {
    LOGGER_WRITE(Logger::DEBUG,"RPC CALLED with params:");

    for(std::vector<int>::size_type i = 0; i != args.size(); i++) {
        std::ostringstream oss;
        boost::apply_visitor(WAMPP::JSON::Serializer(oss),args[i]->data);
        LOGGER_WRITE(Logger::DEBUG,oss.str());
    }
}

int main() {
    // Log everything to stdout
    LOGGER_START(Logger::DEBUG, "")
    {
        WAMPP::JSON::Node root;
        root.data = WAMPP::JSON::Object();
        WAMPP::JSON::NodePtr pobj(new WAMPP::JSON::Node());
        pobj->data = WAMPP::JSON::Object();
        WAMPP::JSON::NodePtr ps(new WAMPP::JSON::Node());
        ps->data = "bar";
        boost::get<WAMPP::JSON::Object>(pobj->data).insert(
            std::make_pair("foo",ps));
        boost::get<WAMPP::JSON::Object>(root.data).insert(
            std::make_pair("inner",pobj));
    }
    {
        const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } ";
        printf("Original JSON:\n %s\n", json);

        rapidjson::Document document;
        document.Parse<0>(json);

        WAMPP::JSON::Node clone(document);

        std::ostringstream oss;
        boost::apply_visitor(WAMPP::JSON::Serializer(oss),clone.data);
        LOGGER_WRITE(Logger::DEBUG,oss.str());

    }
    try {

        WAMPP::Server server("WAMPP Server 1.0");

        // Register RPC cp
        server.addRPC("test",&myrpc);

        // Start the server
        server.run(9002);

    } catch (std::exception & e) {
        LOGGER_WRITE(Logger::ERROR, e.what())
    }
    LOGGER_STOP()
}
<commit_msg>improved main example<commit_after>#include "server.hpp"
#include "logger.hpp"
#include "json.hpp"

WAMPP::JSON::NodePtr myrpc(connection_hdl hdl,
                           std::string callId,
                           std::vector<WAMPP::JSON::NodePtr> args) {

    LOGGER_WRITE(Logger::DEBUG,"RPC Called with params:");
    for(std::vector<int>::size_type i = 0; i != args.size(); i++) {
        std::ostringstream oss;
        oss << "#" << i << ":";
        boost::apply_visitor(WAMPP::JSON::Serializer(oss),args[i]->data);
        LOGGER_WRITE(Logger::DEBUG,oss.str());
    }

    WAMPP::JSON::NodePtr result(new WAMPP::JSON::Node(string("OK")));
    std::ostringstream oss;
    boost::apply_visitor(WAMPP::JSON::Serializer(oss),result->data);
    LOGGER_WRITE(Logger::DEBUG,"Answering:");
    LOGGER_WRITE(Logger::DEBUG,oss.str());

    return result;
}

int main() {
    // Log everything to stdout
    LOGGER_START(Logger::DEBUG, "")
    try {

        WAMPP::Server server("WAMPP Server 1.0");

        // Register RPC cp
        server.addRPC("test",&myrpc);

        // Start the server
        server.run(9002);

    } catch (std::exception & e) {
        LOGGER_WRITE(Logger::ERROR, e.what())
    }
    LOGGER_STOP()
}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include <QWebView>
#include <QtWidgets>
#include <QWebFrame>
#include <QDir>
#include <QApplication>
#include <QDebug>
#include <QWebPage>
#include <QObject>

/*
 *  Utility:
 *  ./exectuable pageAddress width height decoration
 *
 *   - pageAddress: the html file path or url
 *   - width:       integer that represent the width of the window
 *   - height:      integer that represent the height of the window
 *   - decoration:  if it is "UNDECORATED" the window will be undecorated (it will not have
 *                  borders and the window buttons
 *
 * */

QWebView *webView;

/*
 *  Javascript functions (Public API)
 * */
class MyJavaScriptOperations : public QObject {
    Q_OBJECT
public:
    /*
     *  Close window
     *  $API.closeWindow();
     *
     **/
    Q_INVOKABLE void closeWindow () {
        webView->close();
    }

    /*
     *  Resize
     *  $API.resize(width, height);
     *
     **/
    Q_INVOKABLE void resize (int width, int height) {
        webView->resize(width, height);
    }

    /*
     *  Set window flags
     *  $API.setWindowFlags (type)
     *      - UNDECORATED
     *
     * */
    Q_INVOKABLE void setWindowFlags (QString type) {

        QStringList options;
        options << "UNDECORATED";

        switch (options.indexOf(type)) {
            case 0:
                webView->setWindowFlags(Qt::FramelessWindowHint);
                webView->show();
                break;
            // TODO Other cases
        }
    }

    /*
     *  Set window state
     *  $API.setWindowState (value)
     *      - MAXIMIZED
     *      - MINIMIZED
     *      - FULLSCREEN
     *      - ACTIVE
     * */
    Q_INVOKABLE void setWindowState (QString type) {

        QStringList options;
        options << "MAXIMIZED" << "MINIMIZED" << "FULLSCREEN" << "ACTIVATE";

        switch (options.indexOf(type)) {
            case 0:
                webView->setWindowState(Qt::WindowMaximized);
                break;
            case 1:
                webView->setWindowState(Qt::WindowMinimized);
                break;
            case 2:
                webView->setWindowState(Qt::WindowFullScreen);
                break;
            case 3:
                webView->setWindowState(Qt::WindowActive);
                break;
        }
    }

    /*
     *  Get window size
     *  $API.getWindowSize ()
     * */
    Q_INVOKABLE QObject *getWindowSize () {

        QObject *size = new QObject();
        QSize winSize = webView->size();

        size->setProperty("width", winSize.width());
        size->setProperty("height", winSize.height());

        return size;
    }

    /*
     *  Set window position
     *  $API.setWindowPosition (left, top)
     * */
    Q_INVOKABLE void setWindowPosition (int left, int top) {
        webView->move(left, top);
    }

    /*
     *  Get window position
     *  $API.getWindowPosition (left, top)
     * */
    Q_INVOKABLE QObject *getWindowPosition () {
        QObject *position = new QObject();
        QPoint point = webView->pos();

        position->setProperty("left", point.x());
        position->setProperty("top", point.y());

        return position;
    }

    /*
     *  Get mouse position
     *  $API.getMousePosition()
     *
     * */
    Q_INVOKABLE QObject *getMousePosition () {
        QObject *position = new QObject();
        QPoint point = QCursor::pos();

        position->setProperty("left", point.x());
        position->setProperty("top", point.y());

        return position;
    }

    /*
     *  Debug
     *  $API.debug(message)
     *
     * */
    Q_INVOKABLE void debug (QString message) {
        qDebug() << message;
    }

};

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

    QApplication app(argc, argv);

    // build the web view
    QWebView *view = new QWebView();

    webView = view;

    // get the html path
    QString HTML_PATH       = QString(argv[1]);

    // the path is NOT a web site url
    if (!HTML_PATH.startsWith("htt"))
    {
        // get it from the local machine
        HTML_PATH = "file://" + QDir::current().absolutePath() + QDir::separator() + HTML_PATH;
    }

    // set window width and height
    int     WINDOW_WIDTH    = QString(argv[2]).toInt();
    int     WINDOW_HEIGHT   = QString(argv[3]).toInt();

    // handle "UNDECORATED" flag
    if (QString(argv[4]) == "UNDECORATED") {

        // set background transparent for webview
        QPalette pal = view->palette();
        pal.setBrush(QPalette::Base, Qt::transparent);
        view->page()->setPalette(pal);
        view->setAttribute(Qt::WA_TranslucentBackground);

        view->setWindowFlags(Qt::FramelessWindowHint);
    }

    // add the public api functions
    view->page()->mainFrame()->addToJavaScriptWindowObject("$API", new MyJavaScriptOperations);

    // resize the window
    view->resize(WINDOW_WIDTH, WINDOW_HEIGHT);

    // load that HTML file or website
    view->load(QUrl(HTML_PATH));

    // show the web view
    view->show();

    return app.exec();
}

#include "main.moc"
<commit_msg>Added restored window state option.<commit_after>#include "mainwindow.h"
#include <QWebView>
#include <QtWidgets>
#include <QWebFrame>
#include <QDir>
#include <QApplication>
#include <QDebug>
#include <QWebPage>
#include <QObject>

/*
 *  Utility:
 *  ./exectuable pageAddress width height decoration
 *
 *   - pageAddress: the html file path or url
 *   - width:       integer that represent the width of the window
 *   - height:      integer that represent the height of the window
 *   - decoration:  if it is "UNDECORATED" the window will be undecorated (it will not have
 *                  borders and the window buttons
 *
 * */

QWebView *webView;

/*
 *  Javascript functions (Public API)
 * */
class MyJavaScriptOperations : public QObject {
    Q_OBJECT
public:
    /*
     *  Close window
     *  $API.closeWindow();
     *
     **/
    Q_INVOKABLE void closeWindow () {
        webView->close();
    }

    /*
     *  Resize
     *  $API.resize(width, height);
     *
     **/
    Q_INVOKABLE void resize (int width, int height) {
        webView->resize(width, height);
    }

    /*
     *  Set window flags
     *  $API.setWindowFlags (type)
     *      - UNDECORATED
     *
     * */
    Q_INVOKABLE void setWindowFlags (QString type) {

        QStringList options;
        options << "UNDECORATED";

        switch (options.indexOf(type)) {
            case 0:
                webView->setWindowFlags(Qt::FramelessWindowHint);
                webView->show();
                break;
            // TODO Other cases
        }
    }

    /*
     *  Set window state
     *  $API.setWindowState (value)
     *      - MAXIMIZED
     *      - MINIMIZED
     *      - FULLSCREEN
     *      - ACTIVE
     * */
    Q_INVOKABLE void setWindowState (QString type) {

        QStringList options;
        options << "MAXIMIZED" << "MINIMIZED" << "FULLSCREEN" << "ACTIVATE" << "RESTORED";

        switch (options.indexOf(type)) {
            case 0:
                webView->setWindowState(Qt::WindowMaximized);
                break;
            case 1:
                webView->setWindowState(Qt::WindowMinimized);
                break;
            case 2:
                webView->setWindowState(Qt::WindowFullScreen);
                break;
            case 3:
                webView->setWindowState(Qt::WindowActive);
                break;
            case 4:
                webView->setWindowState(Qt::WindowNoState);
                break;
        }
    }

    /*
     *  Get window size
     *  $API.getWindowSize ()
     * */
    Q_INVOKABLE QObject *getWindowSize () {

        QObject *size = new QObject();
        QSize winSize = webView->size();

        size->setProperty("width", winSize.width());
        size->setProperty("height", winSize.height());

        return size;
    }

    /*
     *  Set window position
     *  $API.setWindowPosition (left, top)
     * */
    Q_INVOKABLE void setWindowPosition (int left, int top) {
        webView->move(left, top);
    }

    /*
     *  Get window position
     *  $API.getWindowPosition (left, top)
     * */
    Q_INVOKABLE QObject *getWindowPosition () {
        QObject *position = new QObject();
        QPoint point = webView->pos();

        position->setProperty("left", point.x());
        position->setProperty("top", point.y());

        return position;
    }

    /*
     *  Get mouse position
     *  $API.getMousePosition()
     *
     * */
    Q_INVOKABLE QObject *getMousePosition () {
        QObject *position = new QObject();
        QPoint point = QCursor::pos();

        position->setProperty("left", point.x());
        position->setProperty("top", point.y());

        return position;
    }

    /*
     *  Debug
     *  $API.debug(message)
     *
     * */
    Q_INVOKABLE void debug (QString message) {
        qDebug() << message;
    }

};

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

    QApplication app(argc, argv);

    // build the web view
    QWebView *view = new QWebView();

    webView = view;

    // get the html path
    QString HTML_PATH       = QString(argv[1]);

    // the path is NOT a web site url
    if (!HTML_PATH.startsWith("htt"))
    {
        // get it from the local machine
        HTML_PATH = "file://" + QDir::current().absolutePath() + QDir::separator() + HTML_PATH;
    }

    // set window width and height
    int     WINDOW_WIDTH    = QString(argv[2]).toInt();
    int     WINDOW_HEIGHT   = QString(argv[3]).toInt();

    // handle "UNDECORATED" flag
    if (QString(argv[4]) == "UNDECORATED") {

        // set background transparent for webview
        QPalette pal = view->palette();
        pal.setBrush(QPalette::Base, Qt::transparent);
        view->page()->setPalette(pal);
        view->setAttribute(Qt::WA_TranslucentBackground);

        view->setWindowFlags(Qt::FramelessWindowHint);
    }

    // add the public api functions
    view->page()->mainFrame()->addToJavaScriptWindowObject("$API", new MyJavaScriptOperations);

    // resize the window
    view->resize(WINDOW_WIDTH, WINDOW_HEIGHT);

    // load that HTML file or website
    view->load(QUrl(HTML_PATH));

    // show the web view
    view->show();

    return app.exec();
}

#include "main.moc"
<|endoftext|>


<commit_before>43d6f8c2-2748-11e6-9f6f-e0f84713e7b8<commit_msg>No longer crashes if X<commit_after>43e3d4dc-2748-11e6-ad72-e0f84713e7b8<|endoftext|>


<commit_before>f6a9f791-ad5c-11e7-8376-ac87a332f658<commit_msg>having coffee<commit_after>f719e317-ad5c-11e7-b9a1-ac87a332f658<|endoftext|>


<commit_before>/*
 * main.cpp
 *
 *  Created on: Apr 9, 2014
 *      Author: Pimenta
 */

#include <cmath>
#include <cstdint>
#include <cstdio>
#include <fstream>
#include <string>

using namespace std;

typedef int64_t  word_t;
typedef uint64_t uword_t;
typedef uint32_t address_t;

#ifndef MEM_WORDS
#define MEM_WORDS 0x2000
#endif

const uword_t ADDRESS_WIDTH = uword_t(log2(double(MEM_WORDS)));
const uword_t ADDRESS_MASK  = uword_t(MEM_WORDS - 1);

int main(int argc, char* argv[]) {
  if (argc != 2) {
    fprintf(stderr, "Usage mode: subleq-sim <meminit_file>\n");
    return 0;
  }

  uword_t* mem = new uword_t[MEM_WORDS];

  // read data
  ifstream f(argv[1]);
  for (address_t words = 0; ; ++words) {
    string tmp;

    // skip address
    f >> tmp;
    if (tmp == "END;") {
      break;
    }
    while (f.get() != ':');
    f.get();

    // read word
    tmp = "";
    for (char c = f.get(); c != ';'; c = f.get())
      tmp += c;
    sscanf(tmp.c_str(), "%llx", &mem[words]);
  }
  f.close();

  // run
  uword_t instruction;
  address_t Aaddr, Baddr, Jaddr;
  word_t sub;
  uword_t instructions = 0;
  for (address_t ip = 0; ; ip = sub <= 0 ? Jaddr : ip + 1) {
    instruction = mem[ip];
    if (0 > (word_t)instruction) {
      break;
    }
    Aaddr = (instruction >> 2*ADDRESS_WIDTH) & ADDRESS_MASK;
    Baddr = (instruction >> 1*ADDRESS_WIDTH) & ADDRESS_MASK;
    Jaddr = (instruction >> 0*ADDRESS_WIDTH) & ADDRESS_MASK;
    sub = mem[Baddr] - mem[Aaddr];
    printf("0x%08X: A=0x%08X(0x%016llX) B=0x%08X(0x%016llX) J=0x%08X sub=0x%016llX\n", ip, Aaddr, mem[Aaddr], Baddr, mem[Baddr], Jaddr, sub);
    fflush(stdout);
    mem[Baddr] = sub;
    instructions++;
  }
  printf("Instructions executed: %lld\n", instructions);

  delete[] mem;

  return 0;
}
<commit_msg>Removing fflush<commit_after>/*
 * main.cpp
 *
 *  Created on: Apr 9, 2014
 *      Author: Pimenta
 */

#include <cmath>
#include <cstdint>
#include <cstdio>
#include <fstream>
#include <string>

using namespace std;

typedef int64_t  word_t;
typedef uint64_t uword_t;
typedef uint32_t address_t;

#ifndef MEM_WORDS
#define MEM_WORDS 0x2000
#endif

const uword_t ADDRESS_WIDTH = uword_t(log2(double(MEM_WORDS)));
const uword_t ADDRESS_MASK  = uword_t(MEM_WORDS - 1);

int main(int argc, char* argv[]) {
  if (argc != 2) {
    fprintf(stderr, "Usage mode: subleq-sim <meminit_file>\n");
    return 0;
  }

  uword_t* mem = new uword_t[MEM_WORDS];

  // read data
  ifstream f(argv[1]);
  for (address_t words = 0; ; ++words) {
    string tmp;

    // skip address
    f >> tmp;
    if (tmp == "END;") {
      break;
    }
    while (f.get() != ':');
    f.get();

    // read word
    tmp = "";
    for (char c = f.get(); c != ';'; c = f.get())
      tmp += c;
    sscanf(tmp.c_str(), "%llx", &mem[words]);
  }
  f.close();

  // run
  uword_t instruction;
  address_t Aaddr, Baddr, Jaddr;
  word_t sub;
  uword_t instructions = 0;
  for (address_t ip = 0; ; ip = sub <= 0 ? Jaddr : ip + 1) {
    instruction = mem[ip];
    if (0 > (word_t)instruction) {
      break;
    }
    Aaddr = (instruction >> 2*ADDRESS_WIDTH) & ADDRESS_MASK;
    Baddr = (instruction >> 1*ADDRESS_WIDTH) & ADDRESS_MASK;
    Jaddr = (instruction >> 0*ADDRESS_WIDTH) & ADDRESS_MASK;
    sub = mem[Baddr] - mem[Aaddr];
    printf("0x%08X: A=0x%08X(0x%016llX) B=0x%08X(0x%016llX) J=0x%08X sub=0x%016llX\n", ip, Aaddr, mem[Aaddr], Baddr, mem[Baddr], Jaddr, sub);
    mem[Baddr] = sub;
    instructions++;
  }
  printf("Instructions executed: %lld\n", instructions);

  delete[] mem;

  return 0;
}
<|endoftext|>


<commit_before>/*
*
COPYRIGHT AND LICENSE

Copyright (c) 2011 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.

3. All advertising materials mentioning features or use of this
software must display the following acknowledgement: This product
includes software developed by the San Diego Supercomputer Center.

4. Neither the names of the Centers nor the names of the contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*
*
* LIDAR DEM Generation
* This program takes a set of randomly distributed points (ASCII or LAS)
* as input, and generates gridded points (DEM)
* Based on the notes by Prof. Ramon Arrowsmith(ramon.arrowsmith@asu.edu)
* Authors: Han S Kim (hskim@cs.ucsd.edu), Sriram Krishnan (sriram@sdsc.edu)
*
*/

/*

 *
 * FileName: main.cpp
 * Author: Han S Kim (hskim@cs.ucsd.edu), Sriram Krishnan (sriram@sdsc.edu)
 * Description: this program starts from this file
 *
 */
#include "config.h"
#include "Interpolation.h"
#include "Global.h"
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdexcept>
#include <boost/program_options.hpp>

#ifdef CURL_FOUND
#include <curl/curl.h>
#endif

namespace po = boost::program_options;

const std::string appName("points2grid");

int main(int argc, char **argv)
{
  clock_t t0, t1;

  // parameters
  char inputName[1024] = {0};
  char inputURL[2048] = {0};
  char outputName[1024] = {0};
  int input_format = INPUT_ASCII;
  int output_format = 0;
  unsigned int type = 0x00000000;
  double GRID_DIST_X = 6.0;
  double GRID_DIST_Y = 6.0;
  double searchRadius = (double) sqrt(2.0) * GRID_DIST_X;
  int window_size = 0;

  // argument processing..
  po::options_description general("General options"),
    df("Data file"),
    ot("Output Type"),
    res("Resolution"),
    nf("Null Filling"),
    desc;

  general.add_options()
    ("help", "produce a help message")
    ("output_file_name,o", po::value<std::string>()->required(), "without extension, i.e. if you want the output file to be test.asc, this parameter shoud be \"test\"")
    ("search_radius,r", po::value<float>(), "specifies the search radius. The default value is square root 2 of horizontal distance in a grid cell")
    ("output_format", po::value<std::string>(), "'all' generates every possible format,\n"
      "'arc' for ArcGIS format,\n"
      "'grid' for Ascii GRID format,\n"
      "the default value is --all")
    ("input_format", po::value<std::string>(), "'ascii' expects input point cloud in ASCII format (default)"
      "'las' expects input point cloud in LAS format");

  df.add_options()
#ifdef CURL_FOUND
    ("data_file_name,i", po::value<std::string>(), "path to unzipped plain text data file")
    ("data_file_url,l", po::value<std::string>(), "URL of unzipped plain text data file"
      "You must specify either a data_file_name or data_file_url.");
#else
    ("data_file_name,i", po::value<std::string>()->required(), "path to unzipped plain text data file");
#endif

  ot.add_options()
    ("min", "the Zmin values are stored")
    ("max", "the Zmax values are stored")
    ("mean", "the Zmean values are stored")
    ("idw", "the Zidw values are stored")
    ("den", "the density values are stored")
    ("all", "all the values are stored (default)");

  res.add_options()
    ("resolution", po::value<float>(), "The resolution is set to the specified value. Use square grids.\n"
      "If no resolution options are specified, a 6ft square grid is used")
    ("resolution-x", po::value<float>(), "The X side of grid cells is set to the specified value")
    ("resolution-y", po::value<float>(), "The Y side of grid cells is set to the specified value");

  nf.add_options()
    ("fill", "fills nulls in the DEM. Default window size is 3.")
    ("fill_window_size", po::value<int>(), "The fill window is set to value. Permissible values are 3, 5 and 7.");

  desc.add(general).add(df).add(ot).add(res).add(nf);

  po::variables_map vm;

  try {
    po::store(po::parse_command_line(argc, argv, desc), vm);

    if (vm.count("help")) {
      cout << "------------------------------------------------------------------------" << endl;
      cout << "   " << appName << " (development version )" << endl;
      cout << "------------------------------------------------------------------------" << endl;
      cout << "Usage: " << appName << " [options]" << endl;
      cout << desc << endl;
      exit(0);
    }

    po::notify(vm);

    if (vm.count("output_format")) {
      std::string of = vm["output_format"].as<std::string>();
      if(of.compare("all") == 0) {
		    output_format = OUTPUT_FORMAT_ALL;
      }
      else if(of.compare("arc") == 0)
		    output_format = OUTPUT_FORMAT_ARC_ASCII;
	    else if(of.compare("grid") == 0)
		    output_format = OUTPUT_FORMAT_GRID_ASCII;
	    else{
        throw std::logic_error("'" + of + "' is not a recognized output_format");
      }
    }
        // resolution
    if(vm.count("resolution")){
      float res = vm["resolution"].as<float>();
      GRID_DIST_X = res;
      GRID_DIST_Y = res;
      if(searchRadius == sqrt(2.0) * 6.0)
        searchRadius = (double) sqrt(2.0) * GRID_DIST_X;

      if(GRID_DIST_X == 0){
        throw std::logic_error("resolution must not be 0");
      }
    }

    if(vm.count("resolution-x")) {
      GRID_DIST_X = vm["resolution-x"].as<float>();
      if(searchRadius == sqrt(2.0) * 6.0)
        searchRadius = (double) sqrt(2.0) * GRID_DIST_X;

      if(GRID_DIST_X == 0){
        throw std::logic_error("resolution-x must not be 0");
      }
    }

    if(vm.count("resolution-y")) {
      GRID_DIST_Y = vm["resolution-y"].as<float>();
      if(GRID_DIST_Y == 0){
        throw std::logic_error("resolution-y must not be 0");
      }
    }

    if(vm.count("min")) {
      type |= OUTPUT_TYPE_MIN;
    }

    if(vm.count("max")) {
      type |= OUTPUT_TYPE_MAX;
    }

    if(vm.count("mean")) {
      type |= OUTPUT_TYPE_MEAN;
    }

    if(vm.count("idw")) {
      type |= OUTPUT_TYPE_IDW;
    }

    if(vm.count("den")) {
      type |= OUTPUT_TYPE_DEN;
    }

    if(vm.count("all")) {
      type = OUTPUT_TYPE_ALL;
    }

    if(vm.count("fill")) {
	    window_size = 3;
    }

    if(vm.count("fill_window_size")) {
		  window_size = vm["fill_window_size"].as<int>();
		  if(!((window_size == 3) || (window_size == 5) || (window_size == 7))) {
		    throw std::logic_error("window-size must be either 3, 5, or 7");
		  }
    }

    if(vm.count("input_format")) {
      std::string inf = vm["input_format"].as<std::string>();

      if(inf.compare("ascii") == 0)
        input_format = INPUT_ASCII;
      else if(inf.compare("las") == 0)
        input_format = INPUT_LAS;
      else{
        throw std::logic_error("'" + inf + "' is not a recognized input_format");
      }
    }

#ifdef CURL_FOUND
    if(vm.count("data_file_name")) {
      strncpy(inputName, vm["data_file_name"].as<std::string>().c_str(), sizeof(inputName));
    }
    if(vm.count("data_file_url")) {
      strncpy(inputURL, vm["data_file_url"].as<std::string>().c_str(), sizeof(inputURL));
    }

    if((inputName == NULL || !strcmp(inputName, "")) &&
        (inputURL == NULL || !strcmp(inputURL, "")))
      {
        throw std::logic_error("you must specify a valid data file");
      }
#else
    strncpy(inputName, vm["data_file_name"].as<std::string>().c_str(), sizeof(inputName));
    if (!strcmp(inputName, "")) {
      throw std::logic_error("data_file_name must not be an empty string");
    }
#endif

    // option required, so assumed to exist
	  strncpy(outputName, vm["output_file_name"].as<std::string>().c_str(), sizeof(outputName));

    if(vm.count("search_radius")) {
	    searchRadius = vm["search_radius"].as<float>();
    }

    if(type == 0)
      type = OUTPUT_TYPE_ALL;

  #ifdef CURL_FOUND
    // download file from URL, and set input name
    if (!((inputURL == NULL || !strcmp(inputURL, "")))) {

        CURL *curl;
        CURLcode res;

        /* get the file name from the URL */
        int i = 0;
        for(i = sizeof(inputURL); i>= 0; i--) {
	    if(inputURL[i] == '/')
	        break;
        }
        strncpy(inputName, inputURL+i+1, sizeof(inputName));

        curl = curl_easy_init();
        if (!curl) {
	    cout << "Can't initialize curl object to download input from: "
	         << inputURL << endl;
	    exit(1);
        }

        /* set URL */
        curl_easy_setopt(curl, CURLOPT_URL, inputURL);
        curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);

        /* and write to file */
        FILE *fp;
        fp = fopen(inputName, "w");
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

        /* perform the curl request and clean up */
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);

        if (res != 0) {
	    cout << "Error while downloading input from: " << inputURL << endl;
	    exit(1);
        }
    }
  #endif

    cout << "Parameters ************************" << endl;
    cout << "inputName: '" << inputName << "'" << endl;
    cout << "input_format: " << input_format << endl;
    cout << "outputName: '" << outputName << "'" << endl;
    cout << "GRID_DIST_X: " << GRID_DIST_X << endl;
    cout << "GRID_DIST_Y: " << GRID_DIST_Y << endl;
    cout << "searchRadius: " << searchRadius << endl;
    cout << "output_format: " << output_format << endl;
    cout << "type: " << type << endl;
    cout << "fill window size: " << window_size << endl;
    cout << "************************************" << endl;
  }
  catch (std::exception& e) {
    cerr << "error: " << e.what() << endl;
    cerr << "execute `" << appName << " --help` to see usage information" << endl;
    exit(1);
  }

  t0 = clock();

  Interpolation *ip = new Interpolation(GRID_DIST_X, GRID_DIST_Y, searchRadius, window_size);

  if(ip->init(inputName, input_format) < 0)
    {
      fprintf(stderr, "Interpolation::init() error\n");
      return -1;
    }

  t1 = clock();
  printf("Init + Min/Max time: %10.2f\n", (double)(t1 - t0)/CLOCKS_PER_SEC);

  t0 = clock();
  if(ip->interpolation(inputName, outputName, input_format, output_format, type) < 0)
    {
      fprintf(stderr, "Interpolation::interpolation() error\n");
      return -1;
    }

  t1 = clock();
  printf("DEM generation + Output time: %10.2f\n", (double)(t1 - t0)/CLOCKS_PER_SEC);

  printf("# of data: %d\n", ip->getDataCount());
  printf("dimension: %d x %d\n", ip->getGridSizeX(), ip->getGridSizeY());

  delete ip;

  return 0;
}
<commit_msg>Removing use of the required() value_semantic modifier. It's not supported by older versions of program_options.<commit_after>/*
*
COPYRIGHT AND LICENSE

Copyright (c) 2011 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.

3. All advertising materials mentioning features or use of this
software must display the following acknowledgement: This product
includes software developed by the San Diego Supercomputer Center.

4. Neither the names of the Centers nor the names of the contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*
*
* LIDAR DEM Generation
* This program takes a set of randomly distributed points (ASCII or LAS)
* as input, and generates gridded points (DEM)
* Based on the notes by Prof. Ramon Arrowsmith(ramon.arrowsmith@asu.edu)
* Authors: Han S Kim (hskim@cs.ucsd.edu), Sriram Krishnan (sriram@sdsc.edu)
*
*/

/*

 *
 * FileName: main.cpp
 * Author: Han S Kim (hskim@cs.ucsd.edu), Sriram Krishnan (sriram@sdsc.edu)
 * Description: this program starts from this file
 *
 */
#include "config.h"
#include "Interpolation.h"
#include "Global.h"
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdexcept>
#include <boost/program_options.hpp>

#ifdef CURL_FOUND
#include <curl/curl.h>
#endif

namespace po = boost::program_options;

const std::string appName("points2grid");

int main(int argc, char **argv)
{
  clock_t t0, t1;

  // parameters
  char inputName[1024] = {0};
  char inputURL[2048] = {0};
  char outputName[1024] = {0};
  int input_format = INPUT_ASCII;
  int output_format = 0;
  unsigned int type = 0x00000000;
  double GRID_DIST_X = 6.0;
  double GRID_DIST_Y = 6.0;
  double searchRadius = (double) sqrt(2.0) * GRID_DIST_X;
  int window_size = 0;

  // argument processing..
  po::options_description general("General options"),
    df("Data file"),
    ot("Output Type"),
    res("Resolution"),
    nf("Null Filling"),
    desc;

  general.add_options()
    ("help", "produce a help message")
    ("output_file_name,o", po::value<std::string>(), "required. name of output file without extension, i.e. if you want the output file to be test.asc, this parameter shoud be \"test\"")
    ("search_radius,r", po::value<float>(), "specifies the search radius. The default value is square root 2 of horizontal distance in a grid cell")
    ("output_format", po::value<std::string>(), "'all' generates every possible format,\n"
      "'arc' for ArcGIS format,\n"
      "'grid' for Ascii GRID format,\n"
      "the default value is --all")
    ("input_format", po::value<std::string>(), "'ascii' expects input point cloud in ASCII format (default)"
      "'las' expects input point cloud in LAS format");

  df.add_options()
#ifdef CURL_FOUND
    ("data_file_name,i", po::value<std::string>(), "path to unzipped plain text data file")
    ("data_file_url,l", po::value<std::string>(), "URL of unzipped plain text data file"
      "You must specify either a data_file_name or data_file_url.");
#else
    ("data_file_name,i", po::value<std::string>(), "required. path to unzipped plain text data file");
#endif

  ot.add_options()
    ("min", "the Zmin values are stored")
    ("max", "the Zmax values are stored")
    ("mean", "the Zmean values are stored")
    ("idw", "the Zidw values are stored")
    ("den", "the density values are stored")
    ("all", "all the values are stored (default)");

  res.add_options()
    ("resolution", po::value<float>(), "The resolution is set to the specified value. Use square grids.\n"
      "If no resolution options are specified, a 6ft square grid is used")
    ("resolution-x", po::value<float>(), "The X side of grid cells is set to the specified value")
    ("resolution-y", po::value<float>(), "The Y side of grid cells is set to the specified value");

  nf.add_options()
    ("fill", "fills nulls in the DEM. Default window size is 3.")
    ("fill_window_size", po::value<int>(), "The fill window is set to value. Permissible values are 3, 5 and 7.");

  desc.add(general).add(df).add(ot).add(res).add(nf);

  po::variables_map vm;

  try {
    po::store(po::parse_command_line(argc, argv, desc), vm);

    if (vm.count("help")) {
      cout << "------------------------------------------------------------------------" << endl;
      cout << "   " << appName << " (development version )" << endl;
      cout << "------------------------------------------------------------------------" << endl;
      cout << "Usage: " << appName << " [options]" << endl;
      cout << desc << endl;
      exit(0);
    }

    po::notify(vm);

    if (!vm.count("output_file_name")) {
      throw std::logic_error("output_file_name must be specified");
    }

    if (vm.count("output_format")) {
      std::string of = vm["output_format"].as<std::string>();
      if(of.compare("all") == 0) {
		    output_format = OUTPUT_FORMAT_ALL;
      }
      else if(of.compare("arc") == 0)
		    output_format = OUTPUT_FORMAT_ARC_ASCII;
	    else if(of.compare("grid") == 0)
		    output_format = OUTPUT_FORMAT_GRID_ASCII;
	    else{
        throw std::logic_error("'" + of + "' is not a recognized output_format");
      }
    }
        // resolution
    if(vm.count("resolution")){
      float res = vm["resolution"].as<float>();
      GRID_DIST_X = res;
      GRID_DIST_Y = res;
      if(searchRadius == sqrt(2.0) * 6.0)
        searchRadius = (double) sqrt(2.0) * GRID_DIST_X;

      if(GRID_DIST_X == 0){
        throw std::logic_error("resolution must not be 0");
      }
    }

    if(vm.count("resolution-x")) {
      GRID_DIST_X = vm["resolution-x"].as<float>();
      if(searchRadius == sqrt(2.0) * 6.0)
        searchRadius = (double) sqrt(2.0) * GRID_DIST_X;

      if(GRID_DIST_X == 0){
        throw std::logic_error("resolution-x must not be 0");
      }
    }

    if(vm.count("resolution-y")) {
      GRID_DIST_Y = vm["resolution-y"].as<float>();
      if(GRID_DIST_Y == 0){
        throw std::logic_error("resolution-y must not be 0");
      }
    }

    if(vm.count("min")) {
      type |= OUTPUT_TYPE_MIN;
    }

    if(vm.count("max")) {
      type |= OUTPUT_TYPE_MAX;
    }

    if(vm.count("mean")) {
      type |= OUTPUT_TYPE_MEAN;
    }

    if(vm.count("idw")) {
      type |= OUTPUT_TYPE_IDW;
    }

    if(vm.count("den")) {
      type |= OUTPUT_TYPE_DEN;
    }

    if(vm.count("all")) {
      type = OUTPUT_TYPE_ALL;
    }

    if(vm.count("fill")) {
	    window_size = 3;
    }

    if(vm.count("fill_window_size")) {
		  window_size = vm["fill_window_size"].as<int>();
		  if(!((window_size == 3) || (window_size == 5) || (window_size == 7))) {
		    throw std::logic_error("window-size must be either 3, 5, or 7");
		  }
    }

    if(vm.count("input_format")) {
      std::string inf = vm["input_format"].as<std::string>();

      if(inf.compare("ascii") == 0)
        input_format = INPUT_ASCII;
      else if(inf.compare("las") == 0)
        input_format = INPUT_LAS;
      else{
        throw std::logic_error("'" + inf + "' is not a recognized input_format");
      }
    }

#ifdef CURL_FOUND
    if(vm.count("data_file_name")) {
      strncpy(inputName, vm["data_file_name"].as<std::string>().c_str(), sizeof(inputName));
    }
    if(vm.count("data_file_url")) {
      strncpy(inputURL, vm["data_file_url"].as<std::string>().c_str(), sizeof(inputURL));
    }

    if((inputName == NULL || !strcmp(inputName, "")) &&
        (inputURL == NULL || !strcmp(inputURL, "")))
      {
        throw std::logic_error("you must specify a valid data file");
      }
#else
    if(!vm.count("data_file_name")) {
      throw std::logic_error("data_file_name  must be specified");
    }
    else {
      strncpy(inputName, vm["data_file_name"].as<std::string>().c_str(), sizeof(inputName));
      if (!strcmp(inputName, "")) {
	throw std::logic_error("data_file_name must not be an empty string");
      }
    }
#endif

    // option required, so assumed to exist
	  strncpy(outputName, vm["output_file_name"].as<std::string>().c_str(), sizeof(outputName));

    if(vm.count("search_radius")) {
	    searchRadius = vm["search_radius"].as<float>();
    }

    if(type == 0)
      type = OUTPUT_TYPE_ALL;

  #ifdef CURL_FOUND
    // download file from URL, and set input name
    if (!((inputURL == NULL || !strcmp(inputURL, "")))) {

        CURL *curl;
        CURLcode res;

        /* get the file name from the URL */
        int i = 0;
        for(i = sizeof(inputURL); i>= 0; i--) {
	    if(inputURL[i] == '/')
	        break;
        }
        strncpy(inputName, inputURL+i+1, sizeof(inputName));

        curl = curl_easy_init();
        if (!curl) {
	    cout << "Can't initialize curl object to download input from: "
	         << inputURL << endl;
	    exit(1);
        }

        /* set URL */
        curl_easy_setopt(curl, CURLOPT_URL, inputURL);
        curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);

        /* and write to file */
        FILE *fp;
        fp = fopen(inputName, "w");
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

        /* perform the curl request and clean up */
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);

        if (res != 0) {
	    cout << "Error while downloading input from: " << inputURL << endl;
	    exit(1);
        }
    }
  #endif

    cout << "Parameters ************************" << endl;
    cout << "inputName: '" << inputName << "'" << endl;
    cout << "input_format: " << input_format << endl;
    cout << "outputName: '" << outputName << "'" << endl;
    cout << "GRID_DIST_X: " << GRID_DIST_X << endl;
    cout << "GRID_DIST_Y: " << GRID_DIST_Y << endl;
    cout << "searchRadius: " << searchRadius << endl;
    cout << "output_format: " << output_format << endl;
    cout << "type: " << type << endl;
    cout << "fill window size: " << window_size << endl;
    cout << "************************************" << endl;
  }
  catch (std::exception& e) {
    cerr << "error: " << e.what() << endl;
    cerr << "execute `" << appName << " --help` to see usage information" << endl;
    exit(1);
  }

  t0 = clock();

  Interpolation *ip = new Interpolation(GRID_DIST_X, GRID_DIST_Y, searchRadius, window_size);

  if(ip->init(inputName, input_format) < 0)
    {
      fprintf(stderr, "Interpolation::init() error\n");
      return -1;
    }

  t1 = clock();
  printf("Init + Min/Max time: %10.2f\n", (double)(t1 - t0)/CLOCKS_PER_SEC);

  t0 = clock();
  if(ip->interpolation(inputName, outputName, input_format, output_format, type) < 0)
    {
      fprintf(stderr, "Interpolation::interpolation() error\n");
      return -1;
    }

  t1 = clock();
  printf("DEM generation + Output time: %10.2f\n", (double)(t1 - t0)/CLOCKS_PER_SEC);

  printf("# of data: %d\n", ip->getDataCount());
  printf("dimension: %d x %d\n", ip->getGridSizeX(), ip->getGridSizeY());

  delete ip;

  return 0;
}
<|endoftext|>


<commit_before>8532b7b0-2749-11e6-ae65-e0f84713e7b8<commit_msg>Really doesn't crash if X, now<commit_after>8540b6e3-2749-11e6-a020-e0f84713e7b8<|endoftext|>


<commit_before>af9f3eb0-ad58-11e7-9242-ac87a332f658<commit_msg>Put the thingie in the thingie<commit_after>b01b0868-ad58-11e7-8c74-ac87a332f658<|endoftext|>


<commit_before>cd196461-4b02-11e5-9969-28cfe9171a43<commit_msg>bug fix<commit_after>cd28984c-4b02-11e5-82d2-28cfe9171a43<|endoftext|>


<commit_before>9b40c317-4b02-11e5-bdb7-28cfe9171a43<commit_msg>OKAY this time it should work<commit_after>9b4cfbb0-4b02-11e5-8ecd-28cfe9171a43<|endoftext|>


<commit_before>42db6f0c-2748-11e6-b524-e0f84713e7b8<commit_msg>Nope, didn't work, now it does<commit_after>42e5c88a-2748-11e6-87c9-e0f84713e7b8<|endoftext|>


<commit_before>7c00dc80-2749-11e6-86bf-e0f84713e7b8<commit_msg>Deal with it<commit_after>7c1b6dfa-2749-11e6-9caa-e0f84713e7b8<|endoftext|>


<commit_before>3befeb0c-ad58-11e7-a402-ac87a332f658<commit_msg>Now it no longer crashes if X<commit_after>3ca12e78-ad58-11e7-a6ed-ac87a332f658<|endoftext|>


<commit_before>bbcf6647-4b02-11e5-8049-28cfe9171a43<commit_msg>My Backup<commit_after>bbddd8cc-4b02-11e5-867d-28cfe9171a43<|endoftext|>


<commit_before>
#include <SFML/Graphics.hpp>
#include <iostream>
#include "bullet_object.h"
#include "map_object.h"
#include "Tank_object.h"
#include "Barrel_object.h"
#include "Global_constant.h"
#include <string>
#include <math.h>
#include <vector>

bool collision_detect(std::vector<Bullet>b, Barrel barrel, Tank tank, Planet p);

int main()
{

	bool edge;
	map map1(1800, 800, "Space Tank");

	//Planet planet1(1,500,500,2000000,150,"sprites/planets/red.png");
	Planet planet2(2, 900, 400, 2000000, 150, "sprites/planets/earth.png");
	//Planet planet3(3,1300,300,2000000,300,"sprites/planets/pink.png");

	Tank tank1(&planet2, "sprites/tanks/tank3.png");
	Barrel barrel1(&tank1, "sprites/tanks/barrel3.png");

	sf::Vector2f speed(5, 57);
	Bullet bullet1(600, 400, 10, speed, "sprites/missile/missile_2_no_margin.png");
	std::vector<Bullet> b;
	b.push_back(bullet1);

	planet_node *head = new planet_node;
	head->value = &planet2;
	head->next = NULL;
	//head->next = new planet_node;
	//head->next->value = &planet1;
	//head->next->next = NULL;
	//head->next->next = new planet_node;
	//head->next->next->value = &planet3;
	//head->next->next->next = NULL;
	map1.head = head;

	enum Direction { Down, Left, Right, Up };
	float frameCounter = 0, switchFrame = 10, frameSpeed = 500;
	sf::Vector2i source(1, Down); //Tell where the animation start

	int bulletSpriteCounter = 0;
	bool bulletFired = false;

	sf::Clock clock;
	sf::Time time;
	int index = 0;

	barrel1.setTank(&tank1);

	while (map1.window.isOpen())
	{
		sf::Event Event;

		while (map1.window.pollEvent(Event))
		{
			map1.window.setKeyRepeatEnabled(true);

			switch (Event.type) {
			case sf::Event::Closed: {
				map1.window.close();
				break;
			}

			case sf::Event::KeyPressed: {

				if (Event.key.code == sf::Keyboard::Down)
				{
					barrel1.shape.rotate((float)-1.0);
				}

				if (Event.key.code == sf::Keyboard::Up)
				{
					barrel1.shape.rotate(1.0);
				}

				if (Event.key.code == sf::Keyboard::Right)
				{
					tank1.Move_Clock(0.05);
					barrel1.Move_Clock(0.05);
				}

				if (Event.key.code == sf::Keyboard::Left)
				{
					tank1.Move_ConterClock(0.05);
					barrel1.Move_ConterClock(0.05);
				}
				if (Event.key.code == sf::Keyboard::Space)
				{
					bulletFired = true;
				}
			}

			case sf::Event::MouseButtonPressed:
			{
				if (Event.mouseButton.button == sf::Mouse::Left)
				{
					std::cout << "Left Button Pressed at X:" << Event.mouseButton.x << "  Y:" << Event.mouseButton.y << std::endl;
				}
			}
			}

		}

		frameCounter += frameSpeed * clock.restart().asSeconds();
		if (frameCounter >= switchFrame) {
			frameCounter = 0;

			// Any Anomation update goes here
			planet2.shape.rotate(1);
			// Bullet Animation
			//bullet1.shape.rotate(1);
			if (!b.empty()) {

				if (!collision_detect(b, barrel1, tank1, planet2))
				{

					b[0].inc_bullet(map1.head);
					b[0].createSprite("sprites/missile/missile_2_no_margin.png");
					bulletSpriteCounter++;
					bulletSpriteCounter %= 4;
					b[0].shape.setTextureRect(sf::IntRect(bulletSpriteCounter * 60, 0, 60, 15));
					edge = false;

				}
				else
				{

					if (!edge)
					{
						std::cout << "Collision Detected!!" << std::endl;
						b[0].createSprite("sprites/explosions/explosion_1fix.png");
						bulletSpriteCounter++;
						bulletSpriteCounter %= 17;

						b[0].shape.setTextureRect(sf::IntRect(bulletSpriteCounter * 65, 0, 65, 65));
						if (bulletSpriteCounter == 16)
						{
							edge = true;
						}

					}

				}
			}

		}
		map1.window.draw(map1.background);
		//map1.window.draw(planet1.shape);
		map1.window.draw(planet2.shape);
		map1.window.draw(b[0].shape);
		map1.window.draw(barrel1.shape);
		map1.window.draw(tank1.shape);
		map1.window.display();
		map1.window.clear();
	}

}

bool collision_detect(std::vector<Bullet>b, Barrel barrel, Tank tank, Planet p)
{

		if ((b[0].shape.getGlobalBounds().intersects(p.shape.getGlobalBounds()))
			|| (b[0].shape.getGlobalBounds().intersects(tank.shape.getGlobalBounds()))
			|| (b[0].shape.getGlobalBounds().intersects(barrel.shape.getGlobalBounds())))
		{

			return true;
		}

	return false;
}
<commit_msg>comment<commit_after>
#include <SFML/Graphics.hpp>
#include <iostream>
#include "bullet_object.h"
#include "map_object.h"
#include "Tank_object.h"
#include "Barrel_object.h"
#include "Global_constant.h"
#include <string>
#include <math.h>
#include <vector>

bool collision_detect(std::vector<Bullet>b, Barrel barrel, Tank tank, Planet p);

int main()
{

	bool edge;
	map map1(1800, 800, "Space Tank");

	//Planet planet1(1,500,500,2000000,150,"sprites/planets/red.png");
	Planet planet2(2, 900, 400, 2000000, 150, "sprites/planets/earth.png");
	//Planet planet3(3,1300,300,2000000,300,"sprites/planets/pink.png");

	Tank tank1(&planet2, "sprites/tanks/tank3.png");
	Barrel barrel1(&tank1, "sprites/tanks/barrel3.png");

	sf::Vector2f speed(5, 57);
	Bullet bullet1(600, 400, 10, speed, "sprites/missile/missile_2_no_margin.png");
	std::vector<Bullet> b;
	b.push_back(bullet1);

	planet_node *head = new planet_node;
	head->value = &planet2;
	head->next = NULL;
	//head->next = new planet_node;
	//head->next->value = &planet1;
	//head->next->next = NULL;
	//head->next->next = new planet_node;
	//head->next->next->value = &planet3;
	//head->next->next->next = NULL;
	map1.head = head;

	enum Direction { Down, Left, Right, Up };
	float frameCounter = 0, switchFrame = 10, frameSpeed = 500;
	sf::Vector2i source(1, Down); //Tell where the animation start

	int bulletSpriteCounter = 0;
	bool bulletFired = false;

	sf::Clock clock;
	sf::Time time;
	int index = 0;

	barrel1.setTank(&tank1);

	while (map1.window.isOpen())
	{
		sf::Event Event;

		while (map1.window.pollEvent(Event))
		{
			map1.window.setKeyRepeatEnabled(true);

			switch (Event.type) {
			case sf::Event::Closed: {
				map1.window.close();
				break;
			}

			case sf::Event::KeyPressed: {

				if (Event.key.code == sf::Keyboard::Down)
				{
					barrel1.shape.rotate((float)-1.0);
				}

				if (Event.key.code == sf::Keyboard::Up)
				{
					barrel1.shape.rotate(1.0);
				}

				if (Event.key.code == sf::Keyboard::Right)
				{
					tank1.Move_Clock(0.05);
					barrel1.Move_Clock(0.05);
				}

				if (Event.key.code == sf::Keyboard::Left)
				{
					tank1.Move_ConterClock(0.05);
					barrel1.Move_ConterClock(0.05);
				}
				if (Event.key.code == sf::Keyboard::Space)
				{
					bulletFired = true;
				}
			}

			case sf::Event::MouseButtonPressed:
			{
				if (Event.mouseButton.button == sf::Mouse::Left)
				{
					std::cout << "Left Button Pressed at X:" << Event.mouseButton.x << "  Y:" << Event.mouseButton.y << std::endl;
				}
			}
			}

		}

		frameCounter += frameSpeed * clock.restart().asSeconds();
		if (frameCounter >= switchFrame) {
			frameCounter = 0;

			// Any Anomation update goes here
			planet2.shape.rotate(1);
			// Bullet Animation
			//bullet1.shape.rotate(1);
			if (!b.empty()) {

				if (!collision_detect(b, barrel1, tank1, planet2))
				{

					b[0].inc_bullet(map1.head);
					b[0].createSprite("sprites/missile/missile_2_no_margin.png");
					bulletSpriteCounter++;
					bulletSpriteCounter %= 4;
					b[0].shape.setTextureRect(sf::IntRect(bulletSpriteCounter * 60, 0, 60, 15));
					edge = false;

				}
				else
				{

					if (!edge)
					{
						std::cout << "Collision Detected!!" << std::endl;
						b[0].createSprite("sprites/explosions/explosion_1fix.png");
						bulletSpriteCounter++;
						bulletSpriteCounter %= 17;

						b[0].shape.setTextureRect(sf::IntRect(bulletSpriteCounter * 65, 0, 65, 65));
						if (bulletSpriteCounter == 16)
						{
							edge = true;
						}

						//b.clear();			// this causes vector iterator + error

					}

				}
			}

		}
		map1.window.draw(map1.background);
		//map1.window.draw(planet1.shape);
		map1.window.draw(planet2.shape);
		map1.window.draw(b[0].shape);
		map1.window.draw(barrel1.shape);
		map1.window.draw(tank1.shape);
		map1.window.display();
		map1.window.clear();
	}

}

bool collision_detect(std::vector<Bullet>b, Barrel barrel, Tank tank, Planet p)
{

		if ((b[0].shape.getGlobalBounds().intersects(p.shape.getGlobalBounds()))
			|| (b[0].shape.getGlobalBounds().intersects(tank.shape.getGlobalBounds()))
			|| (b[0].shape.getGlobalBounds().intersects(barrel.shape.getGlobalBounds())))
		{

			return true;
		}

	return false;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
// these two are to get maximums
#include <limits.h>
#include <float.h>
#include <thread>
#include <future>
#include <ctime>
#include <chrono>
#include <cmath>
#include <iostream>
#include <iomanip> // for std::setprecision()
#include <vector>
#include <cinttypes> // for std::uint_fast64_t

// for time stuff
using namespace std::chrono;

std::uint_fast64_t cycles = UINT_FAST64_MAX;

void calcinrange(std::uint_fast64_t start, std::uint_fast64_t end, std::promise<long double> && r, int TID) {
	std::uint_fast64_t cycle = start;
	long double dParts[3] = {2.0l+(long double)(start*2), 3.0l+(long double)(start*2), 4.0l+(long double)(start*2)};
	long double pi = 0.0l; // the smaller ones will start with 0, then they will all be added to 3 at the end
	bool add = true;
	while (cycle <= end) {
		long double addend = 4.0l/(dParts[0]*dParts[1]*dParts[2]);
		if (add) pi += addend;
		else pi -= addend;
		for (int i = 0; i<3; i++)
			dParts[i]+=2.0l;
		cycle++;
		add = !add;
	}
	r.set_value(pi);
	printf("Thread %d done.\n", TID);
}

int main(int argc, char* argv[]) {
	int threads = 1;
	int precision = 11; // this will be 10 decimal places. 1 is added for the 3
	if (argc >= 4) {
		precision = std::abs(atoi(argv[3]));
		if (precision > 50) {
			printf("Warning: %d is equivalent to a precision of 50.\n", precision);
			precision = 51; // again, add one for 3
		}
		threads = atoi(argv[1]);
		sscanf(argv[2], "%" SCNuFAST64 "", &cycles);
	} else if (argc == 3) {
		threads = atoi(argv[1]);
		sscanf(argv[2], "%" SCNuFAST64 "", &cycles);
	} else if (argc == 2) {
		threads = atoi(argv[1]);
	}

	if (threads <= 0)
		threads = (int)std::thread::hardware_concurrency();

	if (threads <= 0) { // this means that it couldn't figure out how many threads the system can have
		printf("Warning: could not determine hardware concurrency. Please specify a specific number of threads. Will use one thread.\n");
		threads = 1;
	}

	printf("Calculating pi over %" PRIuFAST64 " iterations.\nUsing %d threads.\nPrecision: %d decimal places.\n", cycles, threads, precision-1);

	high_resolution_clock::time_point t1 = high_resolution_clock::now();

	std::vector<std::thread> t(threads);
	std::vector<std::promise<long double> > p(threads);
	std::vector<std::future<long double> > futures(threads);
	for (int i = 0; i < threads; i++)
		futures[i] = p[i].get_future();

	for (int TID = 0; TID < threads; TID++) {
		// first iteration is 0, then the last is 'cycles'
		std::uint_fast64_t start = 0+(TID*(cycles/threads));
		std::uint_fast64_t end = start+(cycles/threads)-1;
		t[TID] = std::thread(calcinrange, start, end, std::move(p[TID]), TID);
		printf("Thread %d: %" PRIuFAST64 " to %" PRIuFAST64 "\n", TID, start, end);
	}
	printf("Started.\n");

	long double *returns = new long double[threads];
	for (int i = 0; i < threads; i++) {
		t[i].join();
		returns[i] = futures[i].get();
	}

	printf("All threads completed.\n");

	long double answer = 3.0l;
	for (int i = 0; i < threads; i++)
		answer += returns[i];

	high_resolution_clock::time_point t2 = high_resolution_clock::now();
	duration<double> time_span = duration_cast<duration<double>>(t2 - t1);

	std::cout << "Answer: " << std::setprecision(precision) << answer;
	printf(" (took %.2f seconds)\n", time_span.count());

	return 0;
}
<commit_msg>refactoring<commit_after>#include <cstdio>
#include <cstdlib>
// these two are to get maximums
#include <thread>
#include <future>
#include <chrono>
#include <cmath>
#include <iostream>
#include <iomanip> // for std::setprecision()
#include <vector>
#include <cinttypes> // for std::uint_fast64_t

// for time stuff
using namespace std::chrono;

std::uint_fast64_t cycles = UINT_FAST64_MAX;

void calcinrange(std::uint_fast64_t start, std::uint_fast64_t end, std::promise<long double> && r, int TID) {
	std::uint_fast64_t cycle = start;
	long double dParts[3] = {2.0l+static_cast<long double>(start*2), 3.0l+static_cast<long double>(start*2), 4.0l+static_cast<long double>(start*2)};
	long double pi = 0.0l; // the smaller ones will start with 0, then they will all be added to 3 at the end
	bool add = true;
	while (cycle <= end) {
		long double addend = 4.0l/(dParts[0]*dParts[1]*dParts[2]);
		if (add) pi += addend;
		else pi -= addend;
		for (int i = 0; i<3; i++)
			dParts[i]+=2.0l;
		cycle++;
		add = !add;
	}
	r.set_value(pi);
	std::printf("Thread %d done.\n", TID);
}

int main(int argc, char* argv[]) {
	int threads = 1;
	int precision = 11; // this will be 10 decimal places. 1 is added for the 3
	if (argc >= 4) {
	    precision = std::abs(std::atoi(argv[3]));
		if (precision > 50) {
			std::printf("Warning: %d is equivalent to a precision of 50.\n", precision);
			precision = 51; // again, add one for 3
		}
		threads = std::atoi(argv[1]);
		std::sscanf(argv[2], "%" SCNuFAST64 "", &cycles);
	} else if (argc == 3) {
		threads = std::atoi(argv[1]);
		std::sscanf(argv[2], "%" SCNuFAST64 "", &cycles);
	} else if (argc == 2) {
		threads = std::atoi(argv[1]);
	}

	if (threads <= 0)
	    threads = static_cast<int>(std::thread::hardware_concurrency());

	if (threads <= 0) { // this means that it couldn't figure out how many threads the system can have
		std::printf("Warning: could not determine hardware concurrency. Please specify a specific number of threads. Will use one thread.\n");
		threads = 1;
	}

	std::printf("Calculating pi over %" PRIuFAST64 " iterations.\nUsing %d threads.\nPrecision: %d decimal places.\n", cycles, threads, precision-1);

	steady_clock::time_point t1 = steady_clock::now();

	std::vector<std::thread> t(threads);
	std::vector<std::promise<long double> > p(threads);
	std::vector<std::future<long double> > futures(threads);
	for (int i = 0; i < threads; i++)
		futures[i] = p[i].get_future();

	for (int TID = 0; TID < threads; TID++) {
		// first iteration is 0, then the last is 'cycles'
		std::uint_fast64_t start = 0+(TID*(cycles/threads));
		std::uint_fast64_t end = start+(cycles/threads)-1;
		t[TID] = std::thread(calcinrange, start, end, std::move(p[TID]), TID);
		std::printf("Thread %d: %" PRIuFAST64 " to %" PRIuFAST64 "\n", TID, start, end);
	}
	std::printf("Started.\n");

	long double answer = 3.0l;
	for (int i = 0; i < threads; i++) {
		t[i].join();
		answer += futures[i].get();
	}

	std::printf("All threads completed.\n");

	steady_clock::time_point t2 = steady_clock::now();
	duration<double> time_span = duration_cast<duration<double>>(t2 - t1);

	std::cout << "Answer: " << std::setprecision(precision) << answer;
	std::printf(" (took %.2f seconds)\n", time_span.count());

	return 0;
}
<|endoftext|>


<commit_before>/*
 * =====================================================================================
 *
 *       Filename:  main.cpp
 *
 *    Description:  gaussian random number generator
 *
 *        Version:  1.0
 *        Created:  11/28/2015 12:18:30 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Gabe Jespersen (), gzackwebs@tfwno.gf
 *
 * =====================================================================================
 */

#include <vector>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cmath>

#include "parse.h"
#include "gaussian.h"

using namespace std;

int main(int argc, char** argv)
{
    srand(time(NULL));
    vector<int> parsed = parse(argc, argv);
    double temp;

    /*
    for(int i = 0; i < parsed.size(); i++)
    {
        cout << parsed.at(i) << endl;
    }
    */

    for(int i = 0; i < parsed.at(2); i++)
    {
        temp = gaussian(parsed.at(0),parsed.at(1),parsed.at(3));

        if(parsed.at(3))
        {
            temp = round(temp);
        }

        cout << temp << endl;
    }

    return 0;
}
<commit_msg>I think everything works fine<commit_after>/*
 * =====================================================================================
 *
 *       Filename:  main.cpp
 *
 *    Description:  gaussian random number generator
 *
 *        Version:  1.0
 *        Created:  11/28/2015 12:18:30 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Gabe Jespersen (), gzackwebs@tfwno.gf
 *
 * =====================================================================================
 */

#include <vector>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cmath>
#include <fstream>

#include "parse.h"
#include "gaussian.h"

using namespace std;

int main(int argc, char** argv)
{
    srand(time(NULL));
    vector<int> parsed = parse(argc, argv);
    double temp;

    /*
    for(int i = 0; i < parsed.size(); i++)
    {
        cout << parsed.at(i) << endl;
    }
    */

    if(parsed.at(4))
    {
        ofstream outputFile;
        outputFile.open("output.txt");
        for(int i = 0; i < parsed.at(2); i++)
        {
            temp = gaussian(parsed.at(0),parsed.at(1),parsed.at(3));

            if(parsed.at(3))
            {
                temp = round(temp);
            }

            outputFile << temp << endl;
        }
        outputFile.close();
    }
    else
    {
        for(int i = 0; i < parsed.at(2); i++)
        {
            temp = gaussian(parsed.at(0),parsed.at(1),parsed.at(3));

            if(parsed.at(3))
            {
                temp = round(temp);
            }

            cout << temp << endl;
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <SFML/Graphics.hpp>

#define PPB 32

sf::Font font;

int main()
{
	// set up text
	font.loadFromFile("/usr/share/fonts/TTF/VeraMono.ttf");

	sf::Color background(22, 22, 22);

	sf::RenderWindow window(sf::VideoMode(1024, 600), "Bananagrams", sf::Style::Titlebar);

	int pos[2] = {0, 0};
	int delta[2] = {0, 0};
	float held[2] = {0, 0};

	float repeat_delay = 0.5;
	float repeat_speed = 0.1;

	sf::RectangleShape cursor(sf::Vector2f(PPB, PPB));
	cursor.setFillColor(sf::Color(0, 0, 0, 0));
	cursor.setOutlineThickness(5);
	cursor.setOutlineColor(sf::Color(0, 200, 0));

	sf::Clock clock;
	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed || (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape))
				window.close();
			else if (event.type == sf::Event::KeyPressed)
			{
				switch (event.key.code)
				{
					case sf::Keyboard::Left:
						delta[0] = -1;
						break;
					case sf::Keyboard::Right:
						delta[0] = 1;
						break;
					case sf::Keyboard::Up:
						delta[1] = -1;
						break;
					case sf::Keyboard::Down:
						delta[1] = 1;
						break;
					default:
						break;
				}
			}
			else if (event.type == sf::Event::KeyReleased)
			{
				switch (event.key.code)
				{
					case sf::Keyboard::Left:
					case sf::Keyboard::Right:
						delta[0] = 0;
						break;
					case sf::Keyboard::Up:
					case sf::Keyboard::Down:
						delta[1] = 0;
						break;
					default:
						break;
				}
			}
		}

		float time = clock.getElapsedTime().asSeconds();
		clock.restart();

		for (unsigned int i = 0; i < 2; i++)
		{
			if (delta[i] == 0)
				held[i] = 0;
			else
			{
				if (held[i] == 0)
					pos[i] += delta[i];
				else
					while (held[i] > repeat_delay)
					{
						pos[i] += delta[i];
						held[i] -= repeat_speed;
					}
				held[i] += time;
			}
		}

		cursor.setPosition(pos[0] * PPB, pos[1] * PPB);

		window.clear(background);
		window.draw(cursor);

		window.display();
	}

	return 0;
}
<commit_msg>WIP add grid, tiles<commit_after>#include <sstream>
#include <dequeue>
#include <SFML/Graphics.hpp>

#define PPB 32

sf::Font font;

sf::RenderTexture tile_texture[26];

class Tile
{
	char character;
	sf::Sprite sprite;
public:
	Tile(char ch) :
		sprite(tile_texture[ch - 'A'].getTexture())
	{
		character = ch;
	}

	void set_pos(int x, int y)
	{
		sprite.setPosition(x * PPB, y * PPB);
	}

	void draw_on(sf::RenderWindow & window) const
	{
		window.draw(sprite);
	}
};

class InfiniteGrid
{
	int min[2];
	int max[2];
	std::dequeue<std::dequeue<Tile*>> grid;
public:
	InfiniteGrid() : min {0, 0}, max {-1, -1}, grid()
	{
	}

	Tile* get(int x, int y)
	{
		if (grid.size() == 0)
			return nullptr;
		if (min[0] <= x && x <= max[0] && min[1] <= y && y <= max[1])
			return grid[x][y];
		else
			return nullptr;
	}

	void set(int x, int y, Tile* tile)
	{
		if (grid.size() == 0)
		{
			grid.push_back(std::dequeue());
			grid[0].push_back(tile);
			min[0] = 0;
			min[1] = 0;
			max[0] = 0;
			max[1] = 0;
		}
		else
		{
			if (x < min[0])
			{
				for (int i = x; i < min[0]; i++)
					grid.push_front(std::dequeue(height));
				min[0] = x;
			}
			else if (x > max[0])
			{
				for (int i = x; i < max[0]; i++)
					grid.push_back(std::dequeue(height));
				max[0] = x;
			}
			if (y < min[1])
			{
				for (auto col : grid)
					for (int i = y; i < min[1]; i++)
						col->push_front(nullptr);
				min[1] = y;
			}
			else if (y > max[1])
			{
				for (auto col : grid)
					for (int i = y; i < min[1]; i++)
						col->push_back(nullptr);
				min[1] = y;
			}
		}
	}
};

int main()
{
	font.loadFromFile("/usr/share/fonts/TTF/VeraMono.ttf");

	// create tile textures
	for (char ch = 'A'; ch <= 'Z'; ch++)
	{
		sf::RectangleShape tile(sf::Vector2f(PPB, PPB));
		tile.setFillColor(sf::Color(255, 255, 175));
		tile_texture[ch - 'A'].draw(tile);

		std::stringstream string;
		string << ch;
		sf::Text letter(string.str(), font, 24);
		tile_texture[ch - 'A'].draw(letter);
		tile_texture[ch - 'A'].display();
	}

	sf::Color background(22, 22, 22);

	sf::RenderWindow window(sf::VideoMode(1024, 600), "Bananagrams", sf::Style::Titlebar);

	int pos[2] = {0, 0};
	int delta[2] = {0, 0};
	float held[2] = {0, 0};

	float repeat_delay = 0.5;
	float repeat_speed = 0.1;

	sf::RectangleShape cursor(sf::Vector2f(PPB, PPB));
	cursor.setFillColor(sf::Color(0, 0, 0, 0));
	cursor.setOutlineThickness(5);
	cursor.setOutlineColor(sf::Color(0, 200, 0));

	sf::Clock clock;
	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed || (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape))
				window.close();
			else if (event.type == sf::Event::KeyPressed)
			{
				switch (event.key.code)
				{
					case sf::Keyboard::Left:
						delta[0] = -1;
						break;
					case sf::Keyboard::Right:
						delta[0] = 1;
						break;
					case sf::Keyboard::Up:
						delta[1] = -1;
						break;
					case sf::Keyboard::Down:
						delta[1] = 1;
						break;
					default:
						break;
				}
			}
			else if (event.type == sf::Event::KeyReleased)
			{
				switch (event.key.code)
				{
					case sf::Keyboard::Left:
					case sf::Keyboard::Right:
						delta[0] = 0;
						break;
					case sf::Keyboard::Up:
					case sf::Keyboard::Down:
						delta[1] = 0;
						break;
					default:
						break;
				}
			}
		}

		float time = clock.getElapsedTime().asSeconds();
		clock.restart();

		for (unsigned int i = 0; i < 2; i++)
		{
			if (delta[i] == 0)
				held[i] = 0;
			else
			{
				if (held[i] == 0)
					pos[i] += delta[i];
				else
					while (held[i] > repeat_delay)
					{
						pos[i] += delta[i];
						held[i] -= repeat_speed;
					}
				held[i] += time;
			}
		}

		cursor.setPosition(pos[0] * PPB, pos[1] * PPB);

		window.clear(background);
		window.draw(cursor);

		window.display();
	}

	return 0;
}
<|endoftext|>


<commit_before>6198848a-2749-11e6-92a4-e0f84713e7b8<commit_msg>I hope I am done<commit_after>61c0bff3-2749-11e6-90d5-e0f84713e7b8<|endoftext|>