<commit_before>#include <SimFieldView.hpp>

#include <Constants.hpp>
#include <Network.hpp>

#include <QPainter>
#include <QMouseEvent>

using namespace boost;
using namespace Packet;

// Converts from meters to m/s for manually shooting the ball
static const float ShootScale = 5;

SimFieldView::SimFieldView(QWidget* parent) : FieldView(parent) {
    _dragMode = DRAG_NONE;
    _dragRobot = -1;
    _dragRobotBlue = false;
    setMouseTracking(true);

    _posLabel = new QLabel(this);
    QRect rect = QFontMetrics(_posLabel->font()).boundingRect("X: 999, Y: 999");
    _posLabel->setMinimumWidth(rect.width());
}

void SimFieldView::mousePressEvent(QMouseEvent* me) {
    Geometry2d::Point pos = _worldToTeam * _screenToWorld * me->pos();

    std::shared_ptr<LogFrame> frame = currentFrame();
    if (me->button() == Qt::LeftButton && frame) {
        _dragRobot = -1;
        for (const LogFrame::Robot& r : frame->self()) {
            if (pos.nearPoint(r.pos(), Robot_Radius)) {
                _dragRobot = r.shell();
                _dragRobotBlue = frame->blue_team();
                break;
            }
        }
        for (const LogFrame::Robot& r : frame->opp()) {
            if (pos.nearPoint(r.pos(), Robot_Radius)) {
                _dragRobot = r.shell();
                _dragRobotBlue = !frame->blue_team();
                break;
            }
        }

        if (_dragRobot < 0) {
            placeBall(me->pos());
        }

        _dragMode = DRAG_PLACE;
    } else if (me->button() == Qt::RightButton && frame) {
        if (frame->has_ball() &&
            pos.nearPoint(frame->ball().pos(), Ball_Radius)) {
            // Drag to shoot the ball
            _dragMode = DRAG_SHOOT;
            _dragTo = pos;
        } else {
            // Look for a robot selection
            int newID = -1;
            for (int i = 0; i < frame->self_size(); ++i) {
                if (pos.distTo(frame->self(i).pos()) < Robot_Radius) {
                    newID = frame->self(i).shell();
                    break;
                }
            }

            if (newID != frame->manual_id()) {
                robotSelected(newID);
            }
        }
    }
}

void SimFieldView::mouseMoveEvent(QMouseEvent* me) {
    _posLabel->move(QPoint(me->pos().x() + 12, me->pos().y()));
    QString s = "X: ";
    s += QString::number(me->pos().x());
    s += " Y: ";
    s += QString::number(me->pos().y());
    _posLabel->setText(s);

    switch (_dragMode) {
        case DRAG_SHOOT:
            _dragTo = _worldToTeam * _screenToWorld * me->pos();
            break;

        case DRAG_PLACE:
            if (_dragRobot >= 0) {
                SimCommand cmd;
                SimCommand::Robot* r = cmd.add_robots();
                r->set_shell(_dragRobot);
                r->set_blue_team(_dragRobotBlue);
                r->mutable_pos()->CopyFrom(_screenToWorld * me->pos());
                r->mutable_vel()->set_x(0);
                r->mutable_vel()->set_y(0);
                sendSimCommand(cmd);
            } else {
                placeBall(me->pos());
            }
            break;

        default:
            break;
    }
    update();
}

void SimFieldView::mouseReleaseEvent(QMouseEvent* me) {
    if (_dragMode == DRAG_SHOOT) {
        SimCommand cmd;
        *cmd.mutable_ball_vel() = _teamToWorld.transformDirection(_shot);
        sendSimCommand(cmd);

        update();
    }

    _dragMode = DRAG_NONE;
}

void SimFieldView::placeBall(QPointF pos) {
    SimCommand cmd;
    cmd.mutable_ball_pos()->CopyFrom(_screenToWorld * pos);
    cmd.mutable_ball_vel()->set_x(0);
    cmd.mutable_ball_vel()->set_y(0);
    sendSimCommand(cmd);
}

void SimFieldView::sendSimCommand(const Packet::SimCommand& cmd) {
    std::string out;
    cmd.SerializeToString(&out);
    _simCommandSocket.writeDatagram(&out[0], out.size(),
                                    QHostAddress(QHostAddress::LocalHost),
                                    SimCommandPort);
}

void SimFieldView::drawTeamSpace(QPainter& p) {
    FieldView::drawTeamSpace(p);

    // Simulator drag-to-shoot
    std::shared_ptr<LogFrame> frame = currentFrame();
    if (_dragMode == DRAG_SHOOT && frame) {
        p.setPen(QPen(Qt::white, 0.1f));
        Geometry2d::Point ball = frame->ball().pos();
        p.drawLine(ball.toQPointF(), _dragTo.toQPointF());

        if (ball != _dragTo) {
            p.setPen(QPen(Qt::gray, 0.1f));

            _shot = (ball - _dragTo) * ShootScale;
            float speed = _shot.mag();
            Geometry2d::Point shotExtension = ball + _shot / speed * 8;

            p.drawLine(ball.toQPointF(), shotExtension.toQPointF());

            p.setPen(Qt::black);
            drawText(p, _dragTo.toQPointF(),
                     QString("%1 m/s").arg(speed, 0, 'f', 1));
        }
    }
}
<commit_msg>scale coordinates to meters<commit_after>#include <SimFieldView.hpp>

#include <Constants.hpp>
#include <Network.hpp>

#include <QPainter>
#include <QMouseEvent>

using namespace boost;
using namespace Packet;

// Converts from meters to m/s for manually shooting the ball
static const float ShootScale = 5;

SimFieldView::SimFieldView(QWidget* parent) : FieldView(parent) {
    _dragMode = DRAG_NONE;
    _dragRobot = -1;
    _dragRobotBlue = false;
    setMouseTracking(true);

    _posLabel = new QLabel(this);
    QRect rect =
        QFontMetrics(_posLabel->font()).boundingRect("X: -9.99, Y: -9.99");
    _posLabel->setMinimumWidth(rect.width());
}

void SimFieldView::mousePressEvent(QMouseEvent* me) {
    Geometry2d::Point pos = _worldToTeam * _screenToWorld * me->pos();

    std::shared_ptr<LogFrame> frame = currentFrame();
    if (me->button() == Qt::LeftButton && frame) {
        _dragRobot = -1;
        for (const LogFrame::Robot& r : frame->self()) {
            if (pos.nearPoint(r.pos(), Robot_Radius)) {
                _dragRobot = r.shell();
                _dragRobotBlue = frame->blue_team();
                break;
            }
        }
        for (const LogFrame::Robot& r : frame->opp()) {
            if (pos.nearPoint(r.pos(), Robot_Radius)) {
                _dragRobot = r.shell();
                _dragRobotBlue = !frame->blue_team();
                break;
            }
        }

        if (_dragRobot < 0) {
            placeBall(me->pos());
        }

        _dragMode = DRAG_PLACE;
    } else if (me->button() == Qt::RightButton && frame) {
        if (frame->has_ball() &&
            pos.nearPoint(frame->ball().pos(), Ball_Radius)) {
            // Drag to shoot the ball
            _dragMode = DRAG_SHOOT;
            _dragTo = pos;
        } else {
            // Look for a robot selection
            int newID = -1;
            for (int i = 0; i < frame->self_size(); ++i) {
                if (pos.distTo(frame->self(i).pos()) < Robot_Radius) {
                    newID = frame->self(i).shell();
                    break;
                }
            }

            if (newID != frame->manual_id()) {
                robotSelected(newID);
            }
        }
    }
}

void SimFieldView::mouseMoveEvent(QMouseEvent* me) {
    _posLabel->move(QPoint(me->pos().x() - 45, me->pos().y() + 17));
    Geometry2d::Point pos = _worldToTeam * _screenToWorld * me->pos();
    QString s = "X: ";
    s += QString::number(roundf(pos.x * 100) / 100);
    s += " Y: ";
    s += QString::number(roundf(pos.y * 100) / 100);
    _posLabel->setText(s);

    switch (_dragMode) {
        case DRAG_SHOOT:
            _dragTo = pos;
            break;

        case DRAG_PLACE:
            if (_dragRobot >= 0) {
                SimCommand cmd;
                SimCommand::Robot* r = cmd.add_robots();
                r->set_shell(_dragRobot);
                r->set_blue_team(_dragRobotBlue);
                r->mutable_pos()->CopyFrom(_screenToWorld * me->pos());
                r->mutable_vel()->set_x(0);
                r->mutable_vel()->set_y(0);
                sendSimCommand(cmd);
            } else {
                placeBall(me->pos());
            }
            break;

        default:
            break;
    }
    update();
}

void SimFieldView::mouseReleaseEvent(QMouseEvent* me) {
    if (_dragMode == DRAG_SHOOT) {
        SimCommand cmd;
        *cmd.mutable_ball_vel() = _teamToWorld.transformDirection(_shot);
        sendSimCommand(cmd);

        update();
    }

    _dragMode = DRAG_NONE;
}

void SimFieldView::placeBall(QPointF pos) {
    SimCommand cmd;
    cmd.mutable_ball_pos()->CopyFrom(_screenToWorld * pos);
    cmd.mutable_ball_vel()->set_x(0);
    cmd.mutable_ball_vel()->set_y(0);
    sendSimCommand(cmd);
}

void SimFieldView::sendSimCommand(const Packet::SimCommand& cmd) {
    std::string out;
    cmd.SerializeToString(&out);
    _simCommandSocket.writeDatagram(&out[0], out.size(),
                                    QHostAddress(QHostAddress::LocalHost),
                                    SimCommandPort);
}

void SimFieldView::drawTeamSpace(QPainter& p) {
    FieldView::drawTeamSpace(p);

    // Simulator drag-to-shoot
    std::shared_ptr<LogFrame> frame = currentFrame();
    if (_dragMode == DRAG_SHOOT && frame) {
        p.setPen(QPen(Qt::white, 0.1f));
        Geometry2d::Point ball = frame->ball().pos();
        p.drawLine(ball.toQPointF(), _dragTo.toQPointF());

        if (ball != _dragTo) {
            p.setPen(QPen(Qt::gray, 0.1f));

            _shot = (ball - _dragTo) * ShootScale;
            float speed = _shot.mag();
            Geometry2d::Point shotExtension = ball + _shot / speed * 8;

            p.drawLine(ball.toQPointF(), shotExtension.toQPointF());

            p.setPen(Qt::black);
            drawText(p, _dragTo.toQPointF(),
                     QString("%1 m/s").arg(speed, 0, 'f', 1));
        }
    }
}
<|endoftext|>


<commit_before>// $Id: File_test.C,v 1.4 2000/06/29 18:26:11 amoll Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////
#include <BALL/SYSTEM/file.h>
#include <sys/types.h>
#include <sys/stat.h>
//#include <fstream>
///////////////////////////

START_TEST(class_name, "$Id: File_test.C,v 1.4 2000/06/29 18:26:11 amoll Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

File* f1;

CHECK(File())
	f1 = new File();
	TEST_NOT_EQUAL(f1, 0)
RESULT

CHECK(~File())
	delete f1;
RESULT

CHECK(File(const String& name, OpenMode open_mode = std::ios::in))
	File f("data/File_test.txt");
	TEST_EQUAL(f.getSize(), 100)
RESULT

File f("data/File_test.txt");

CHECK(File(const File& file))
	File f1(f);
	TEST_EQUAL(f1 == f, true)
RESULT

CHECK(close())
	TEST_EQUAL(f.getSize(), 100)
	f.close();
	TEST_EQUAL(f.isClosed(), true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(open(const String& name, OpenMode open_mode = std::ios::in))
	f.open("data/File_test.txt");
	TEST_EQUAL(f.isOpen(), true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(reopen())
	f.close();
	f.reopen();
	f.reopen();
	TEST_EQUAL(f.isOpen(), true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(getName())
	TEST_EQUAL(f.getName(), "data/File_test.txt")
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(getSize())
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(static getSize(String filename))
	TEST_EQUAL(f.getSize("data/File_test.txt"), 100)
	f.remove("XXX");
	TEST_EQUAL(f.getSize("XXX"), 0)
RESULT

CHECK(int getOpenMode() const)
	TEST_EQUAL(f.getOpenMode(), 1)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(static Type getType(String name, bool trace_link))
	TEST_EQUAL(f.getType("data/File_test.txt", false), 4)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(Type getType(bool trace_link) const;)
	TEST_EQUAL(f.getType(false), 4)
	TEST_EQUAL(f.getType(true), 4)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(std::fstream& getFileStream();)
//	fstream fs;
//	FILE file;
//	file = f.getFileStream(); //!!!
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(copy(String source_name, String destination_name, Size buffer_size = 4096))
	TEST_EQUAL(f.copy("data/File_test.txt", "data/File_test.txt"), false)
	TEST_EQUAL(f.copy("", "data/File_test.txt"), false)
	TEST_EQUAL(f.copy("data/File_test.txt", ""), false)
	TEST_EQUAL(f.copy("", ""), false)
	TEST_EQUAL(f.copy("ZZZZZZZZZZ", "XXX"), false)
	TEST_EQUAL(f.copy("data/File_test.txt", "XXX"), true)
	TEST_EQUAL(f.copy("data/File_test.txt", "XXX"), true)
	TEST_EQUAL(f.getSize(), 100)
	TEST_EQUAL(f.getSize("XXX"), 100)
	f.remove("XXX");
RESULT

CHECK(copyTo(const String& destination_name, Size buffer_size = 4096))
	TEST_EQUAL(f.copyTo("data/File_test.txt"), false)
	TEST_EQUAL(f.copyTo(""), false)
	TEST_EQUAL(f.copyTo("XXX"), true)
	TEST_EQUAL(f.copyTo("XXX"), true)
	TEST_EQUAL(f.getSize(), 100)
	TEST_EQUAL(f.getSize("XXX"), 100)
	f.remove("XXX");
RESULT

CHECK(move(const String& source_name, const String& destination_name))
	TEST_EQUAL(f.copyTo("XXX"), true)
	TEST_EQUAL(f.copyTo("YYY"), true)
	TEST_EQUAL(f.move("XXX", "XXX"), false)
	TEST_EQUAL(f.move("", "XXX"), false)
	TEST_EQUAL(f.move("XXX", ""), false)

	TEST_EQUAL(f.move("XXX", "YYY"), true)
	TEST_EQUAL(f.isAccessible("XXX"), false)
	TEST_EQUAL(f.getSize("YYY"), 100)

	f.copyTo("XXX");
	TEST_EQUAL(f.move("XXX", "YYY"), true)
	TEST_EQUAL(f.getSize(), 100)
	f.remove("XXX");
	f.remove("YYY");
RESULT

CHECK(moveTo(const String& destination_name))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.moveTo("XXX"), false)
	TEST_EQUAL(f1.moveTo(""), false)
	TEST_EQUAL(f1.moveTo("YYY"), true)
	TEST_EQUAL(f1.isAccessible(), true)
	TEST_EQUAL(f1.moveTo("YYY"), false)
	TEST_EQUAL(f1.isAccessible(), true)
	TEST_EQUAL(f.getSize("YYY"), 100)
RESULT

CHECK(remove(String name))
	f.copyTo("XXX");
	TEST_EQUAL(f.remove("XXX"), true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(remove())
	File f1 = File("XXX");
	f1.remove();
	TEST_EQUAL(f1.isAccessible(), false)
RESULT

CHECK(rename(String old_path, String new_path))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.rename("XXX", "XXX"), true)
	TEST_EQUAL(f1.rename("XXX", "YYY"), true)
	TEST_EQUAL(f1.isAccessible("XXX"), false)
	TEST_EQUAL(f1.isAccessible("YYY"), true)
	f1.remove();
	TEST_EQUAL(f.getSize(), 100)
	f.remove("YYY");
RESULT

CHECK(renameTo(const String& new_path))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.renameTo("XXX"), true)
	TEST_EQUAL(f1.isAccessible("XXX"), true)
	TEST_EQUAL(f1.renameTo("YYY"), true)
	TEST_EQUAL(f1.isAccessible("XXX"), false)
	TEST_EQUAL(f1.isAccessible("YYY"), true)
	f1.remove();
RESULT

CHECK(truncate(String path, Size size = 0))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.truncate("XXX", 50), true)
	TEST_EQUAL(f1.getSize(), 50)
	TEST_EQUAL(f1.truncate("XXX", 0), true)
	TEST_EQUAL(f1.getSize(), 0)
	f1.remove();
RESULT

CHECK(truncate(Size size = 0))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.truncate(50), true)
	TEST_EQUAL(f1.getSize(), 50)
	TEST_EQUAL(f1.truncate(0), true)
	TEST_EQUAL(f1.getSize(), 0)
	f1.remove();
RESULT

CHECK(createTemporaryFilename(String& temporary))
	String s;
	TEST_EQUAL(f.createTemporaryFilename(s), true)
	TEST_NOT_EQUAL(s, "")
RESULT

CHECK(operator == (const File& file))
	File f1(f);
	TEST_EQUAL(f1 == f, true)
	f.copyTo("XXX");
	File f2("XXX");
	TEST_EQUAL(f2 == f, false)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(operator != (const File& file))
	File f1(f);
	TEST_EQUAL(f1 != f, false)
	f.copyTo("XXX");
	File f2("XXX");
	TEST_EQUAL(f2 != f, true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(isOpen())
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.isOpen(), true)
	f1.close();
	TEST_EQUAL(f1.isOpen(), false)
RESULT

CHECK(isClosed())
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.isClosed(), false)
	f1.close();
	TEST_EQUAL(f1.isClosed(), true)
RESULT

CHECK(isAccessible(String name))
	TEST_EQUAL(f.isAccessible("data/File_test.txt"), true)
	f.remove("XXX");
	TEST_EQUAL(f.isAccessible("XXX"), false)
RESULT

CHECK(isAccessible())
	TEST_EQUAL(f.isAccessible(), true)
	f.copyTo("XXX");
	File f1("XXX");
	f1.remove();
	TEST_EQUAL(f1.isAccessible(), false)
RESULT

CHECK(isCanonized())
	File f1("../TEST/data/File_test.txt");
	TEST_EQUAL(f1.isValid(), true)
	TEST_EQUAL(f1.isCanonized(), true)

	File f2("data//File_test.txt");
	TEST_EQUAL(f2.isValid(), true)
	TEST_EQUAL(f2.isCanonized(), false)

	File f4("data/../data/File_test.txt");
	TEST_EQUAL(f4.isValid(), true)
	TEST_EQUAL(f4.isCanonized(), false)

	File f5("./data/File_test.txt");
	TEST_EQUAL(f5.isValid(), true)
	TEST_EQUAL(f5.isCanonized(), false)

	File f6("data/File_test.txt");
	TEST_EQUAL(f6.isValid(), true)
	TEST_EQUAL(f6.isCanonized(), true)

	File f7("~/File_test.txt");
	TEST_EQUAL(f7.isCanonized(), false)
RESULT

CHECK(isReadable(String name))
	TEST_EQUAL(f.isReadable("File_test.C"), true)
RESULT

CHECK(isReadable())
	File f2("File_test.C");
	TEST_EQUAL(f2.isReadable(), true)
RESULT

CHECK(isWritable(String name))
	TEST_EQUAL(f.isWritable("File_test.C"), true)
RESULT

CHECK(isWritable())
	File f2("File_test.C");
	TEST_EQUAL(f2.isWritable(), true)
RESULT

CHECK(isExecutable(String name))
	TEST_EQUAL(f.isExecutable("../configure"), true)
	TEST_EQUAL(f.isExecutable("File_test.C"), false)
RESULT

CHECK(isExecutable())
	File f1("../configure");
	TEST_EQUAL(f1.isExecutable(), true)
	File f2("File_test.C");
	TEST_EQUAL(f2.isExecutable(), false)
RESULT

CHECK(isValid())
	TEST_EQUAL(f.isValid(), true)
	File f1("XXX");
	TEST_EQUAL(f1.isValid(), false)
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>fixed: test for isCononized()<commit_after>// $Id: File_test.C,v 1.5 2000/06/30 15:44:35 amoll Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////
#include <BALL/SYSTEM/file.h>
#include <sys/types.h>
#include <sys/stat.h>
//#include <fstream>
///////////////////////////

START_TEST(class_name, "$Id: File_test.C,v 1.5 2000/06/30 15:44:35 amoll Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

File* f1;

CHECK(File())
	f1 = new File();
	TEST_NOT_EQUAL(f1, 0)
RESULT

CHECK(~File())
	delete f1;
RESULT

CHECK(File(const String& name, OpenMode open_mode = std::ios::in))
	File f("data/File_test.txt");
	TEST_EQUAL(f.getSize(), 100)
RESULT

File f("data/File_test.txt");

CHECK(File(const File& file))
	File f1(f);
	TEST_EQUAL(f1 == f, true)
RESULT

CHECK(close())
	TEST_EQUAL(f.getSize(), 100)
	f.close();
	TEST_EQUAL(f.isClosed(), true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(open(const String& name, OpenMode open_mode = std::ios::in))
	f.open("data/File_test.txt");
	TEST_EQUAL(f.isOpen(), true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(reopen())
	f.close();
	f.reopen();
	f.reopen();
	TEST_EQUAL(f.isOpen(), true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(getName())
	TEST_EQUAL(f.getName(), "data/File_test.txt")
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(getSize())
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(static getSize(String filename))
	TEST_EQUAL(f.getSize("data/File_test.txt"), 100)
	f.remove("XXX");
	TEST_EQUAL(f.getSize("XXX"), 0)
RESULT

CHECK(int getOpenMode() const)
	TEST_EQUAL(f.getOpenMode(), 1)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(static Type getType(String name, bool trace_link))
	TEST_EQUAL(f.getType("data/File_test.txt", false), 4)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(Type getType(bool trace_link) const;)
	TEST_EQUAL(f.getType(false), 4)
	TEST_EQUAL(f.getType(true), 4)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(std::fstream& getFileStream();)
//	fstream fs;
//	FILE file;
//	file = f.getFileStream(); //!!!
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(copy(String source_name, String destination_name, Size buffer_size = 4096))
	TEST_EQUAL(f.copy("data/File_test.txt", "data/File_test.txt"), false)
	TEST_EQUAL(f.copy("", "data/File_test.txt"), false)
	TEST_EQUAL(f.copy("data/File_test.txt", ""), false)
	TEST_EQUAL(f.copy("", ""), false)
	TEST_EQUAL(f.copy("ZZZZZZZZZZ", "XXX"), false)
	TEST_EQUAL(f.copy("data/File_test.txt", "XXX"), true)
	TEST_EQUAL(f.copy("data/File_test.txt", "XXX"), true)
	TEST_EQUAL(f.getSize(), 100)
	TEST_EQUAL(f.getSize("XXX"), 100)
	f.remove("XXX");
RESULT

CHECK(copyTo(const String& destination_name, Size buffer_size = 4096))
	TEST_EQUAL(f.copyTo("data/File_test.txt"), false)
	TEST_EQUAL(f.copyTo(""), false)
	TEST_EQUAL(f.copyTo("XXX"), true)
	TEST_EQUAL(f.copyTo("XXX"), true)
	TEST_EQUAL(f.getSize(), 100)
	TEST_EQUAL(f.getSize("XXX"), 100)
	f.remove("XXX");
RESULT

CHECK(move(const String& source_name, const String& destination_name))
	TEST_EQUAL(f.copyTo("XXX"), true)
	TEST_EQUAL(f.copyTo("YYY"), true)
	TEST_EQUAL(f.move("XXX", "XXX"), false)
	TEST_EQUAL(f.move("", "XXX"), false)
	TEST_EQUAL(f.move("XXX", ""), false)

	TEST_EQUAL(f.move("XXX", "YYY"), true)
	TEST_EQUAL(f.isAccessible("XXX"), false)
	TEST_EQUAL(f.getSize("YYY"), 100)

	f.copyTo("XXX");
	TEST_EQUAL(f.move("XXX", "YYY"), true)
	TEST_EQUAL(f.getSize(), 100)
	f.remove("XXX");
	f.remove("YYY");
RESULT

CHECK(moveTo(const String& destination_name))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.moveTo("XXX"), false)
	TEST_EQUAL(f1.moveTo(""), false)
	TEST_EQUAL(f1.moveTo("YYY"), true)
	TEST_EQUAL(f1.isAccessible(), true)
	TEST_EQUAL(f1.moveTo("YYY"), false)
	TEST_EQUAL(f1.isAccessible(), true)
	TEST_EQUAL(f.getSize("YYY"), 100)
RESULT

CHECK(remove(String name))
	f.copyTo("XXX");
	TEST_EQUAL(f.remove("XXX"), true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(remove())
	File f1 = File("XXX");
	f1.remove();
	TEST_EQUAL(f1.isAccessible(), false)
RESULT

CHECK(rename(String old_path, String new_path))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.rename("XXX", "XXX"), true)
	TEST_EQUAL(f1.rename("XXX", "YYY"), true)
	TEST_EQUAL(f1.isAccessible("XXX"), false)
	TEST_EQUAL(f1.isAccessible("YYY"), true)
	f1.remove();
	TEST_EQUAL(f.getSize(), 100)
	f.remove("YYY");
RESULT

CHECK(renameTo(const String& new_path))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.renameTo("XXX"), true)
	TEST_EQUAL(f1.isAccessible("XXX"), true)
	TEST_EQUAL(f1.renameTo("YYY"), true)
	TEST_EQUAL(f1.isAccessible("XXX"), false)
	TEST_EQUAL(f1.isAccessible("YYY"), true)
	f1.remove();
RESULT

CHECK(truncate(String path, Size size = 0))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.truncate("XXX", 50), true)
	TEST_EQUAL(f1.getSize(), 50)
	TEST_EQUAL(f1.truncate("XXX", 0), true)
	TEST_EQUAL(f1.getSize(), 0)
	f1.remove();
RESULT

CHECK(truncate(Size size = 0))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.truncate(50), true)
	TEST_EQUAL(f1.getSize(), 50)
	TEST_EQUAL(f1.truncate(0), true)
	TEST_EQUAL(f1.getSize(), 0)
	f1.remove();
RESULT

CHECK(createTemporaryFilename(String& temporary))
	String s;
	TEST_EQUAL(f.createTemporaryFilename(s), true)
	TEST_NOT_EQUAL(s, "")
RESULT

CHECK(operator == (const File& file))
	File f1(f);
	TEST_EQUAL(f1 == f, true)
	f.copyTo("XXX");
	File f2("XXX");
	TEST_EQUAL(f2 == f, false)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(operator != (const File& file))
	File f1(f);
	TEST_EQUAL(f1 != f, false)
	f.copyTo("XXX");
	File f2("XXX");
	TEST_EQUAL(f2 != f, true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(isOpen())
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.isOpen(), true)
	f1.close();
	TEST_EQUAL(f1.isOpen(), false)
RESULT

CHECK(isClosed())
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.isClosed(), false)
	f1.close();
	TEST_EQUAL(f1.isClosed(), true)
RESULT

CHECK(isAccessible(String name))
	TEST_EQUAL(f.isAccessible("data/File_test.txt"), true)
	f.remove("XXX");
	TEST_EQUAL(f.isAccessible("XXX"), false)
RESULT

CHECK(isAccessible())
	TEST_EQUAL(f.isAccessible(), true)
	f.copyTo("XXX");
	File f1("XXX");
	f1.remove();
	TEST_EQUAL(f1.isAccessible(), false)
RESULT

CHECK(isCanonized())
	File f1("../TEST/data/File_test.txt");
	TEST_EQUAL(f1.isValid(), true)
	TEST_EQUAL(f1.isCanonized(), true)

	File f2("data//File_test.txt");
	TEST_EQUAL(f2.isValid(), true)
	TEST_EQUAL(f2.isCanonized(), true)

	File f4("data/../data/File_test.txt");
	TEST_EQUAL(f4.isValid(), true)
	TEST_EQUAL(f4.isCanonized(), true)

	File f5("./data/File_test.txt");
	TEST_EQUAL(f5.isValid(), true)
	TEST_EQUAL(f5.isCanonized(), true)

	File f6("data/File_test.txt");
	TEST_EQUAL(f6.isValid(), true)
	TEST_EQUAL(f6.isCanonized(), true)

	File f7("~/File_test.txt");
	TEST_EQUAL(f7.isCanonized(), true)
RESULT

CHECK(isReadable(String name))
	TEST_EQUAL(f.isReadable("File_test.C"), true)
RESULT

CHECK(isReadable())
	File f2("File_test.C");
	TEST_EQUAL(f2.isReadable(), true)
RESULT

CHECK(isWritable(String name))
	TEST_EQUAL(f.isWritable("File_test.C"), true)
RESULT

CHECK(isWritable())
	File f2("File_test.C");
	TEST_EQUAL(f2.isWritable(), true)
RESULT

CHECK(isExecutable(String name))
	TEST_EQUAL(f.isExecutable("../configure"), true)
	TEST_EQUAL(f.isExecutable("File_test.C"), false)
RESULT

CHECK(isExecutable())
	File f1("../configure");
	TEST_EQUAL(f1.isExecutable(), true)
	File f2("File_test.C");
	TEST_EQUAL(f2.isExecutable(), false)
RESULT

CHECK(isValid())
	TEST_EQUAL(f.isValid(), true)
	File f1("XXX");
	TEST_EQUAL(f1.isValid(), false)
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>


<commit_before>/*
 * Shell.cpp
 *
 * This file is part of the "XieXie 2.0 Project" (Copyright (c) 2014 by Lukas Hermanns)
 * See "LICENSE.txt" for license information.
 */

#include "Shell.h"
#include "CommandFactory.h"
#include "Version.h"
#include "ConsoleManip.h"
#include "StringModifier.h"
#include "MakeUnique.h"

#include <sstream>
#include <xiexie/xiexie.h>

using namespace Platform::ConsoleManip;
using namespace XieXie;

void Shell::Execute(StreamParser parser)
{
    try
    {
        while (parser)
        {
            /* Read next command */
            auto cmdName = parser.Get();
            auto cmd = CommandFactory::Instance()->FindCommand(cmdName);

            /* Process command line */
            if (cmd)
            {
                parser.Accept();

                if (parser.Get() == "--help")
                {
                    /* Print help for command */
                    parser.Accept();
                    HelpPrinter printer;
                    cmd->Help(printer);
                    printer.Flush(log_);
                }
                else
                {
                    /* Execute command */
                    cmd->Execute(parser, log_);
                }
            }
            else
            {
                log_.Error("unknown command: " + cmdName);
                parser.Accept();
            }
        }
    }
    catch (const std::exception& err)
    {
        log_.Error(err.what());
    }
}

// Define the code for the default script
static void AppendDefaultScript(std::stringstream& sstr)
{
    sstr
        << "import MsgBox, Console, Integer, ASCII, Algo, Utils" << std::endl
        << "class Script { " << std::endl
        << "void print(bool val) { print(val ? \"true\" : \"false\") }" << std::endl
        << "void print(int val) { Intrinsics.printInt(val) }" << std::endl
        << "void print(float val) { Intrinsics.printFloat(val) }" << std::endl
        << "void print(String val) { Intrinsics.print(val.pointer()) }" << std::endl
        << "void printLn(bool val) { printLn(val ? \"true\" : \"false\") }" << std::endl
        << "void printLn(int val) { Intrinsics.printInt(val) Intrinsics.printLn(0) }" << std::endl
        << "void printLn(float val) { Intrinsics.printFloat(val) Intrinsics.printLn(0) }" << std::endl
        << "void printLn(String val) { Intrinsics.printLn(val.pointer()) }" << std::endl
        << "void print(int[] val) { foreach v : val { print(v) print(\" \") } }" << std::endl
        << "void print(float[] val) { foreach v : val { print(v) print(\" \") } }" << std::endl
        << "void print(String[] val) { foreach v : val { print(v) print(\" \") } }" << std::endl
        << "void printLn(int[] val) { foreach v : val { printLn(v) } }" << std::endl
        << "void printLn(float[] val) { foreach v : val { printLn(v) } }" << std::endl
        << "void printLn(String[] val) { foreach v : val { printLn(v) } }" << std::endl
        << "static void main() {" << std::endl
        << "    var script := new Script()" << std::endl
        << "}" << std::endl
        << "init() {" << std::endl
    ;
}

void Shell::Script(std::istream& stream, bool appendDefaultScript)
{
    /* Print info at start-up */
    std::cout << "XieXie Compiler " << Version::AsString() << std::endl;
    std::cout << "Copyright (c) 2014-2015 Lukas Hermanns" << std::endl;

    /* Read and print each line from input stream */
    std::string line;
    auto source = MakeUnique<std::stringstream>();

    size_t lineNum = 0;

    if (appendDefaultScript)
        AppendDefaultScript(*source);

    while (!stream.eof())
    {
        /* Print line number */
        {
            ScopedColor color(std::cout, Color::Green | Color::Blue);
            std::cout << NumberOffset(++lineNum, 10, '0') << "  ";
        }

        /* Print line */
        {
            ScopedColor color(std::cout, Color::Cyan);
            std::getline(stream, line);
            *source << line << std::endl;
        }
    }

    if (appendDefaultScript)
        *source << "}}" << std::endl;

    /* Run script immediately */
    auto exitCode = RunFromString(
        source->str(),
        CompileFlags::Warn,
        VirtualMachine::Stack::defaultSize,
        &log_.stream
    );

    if (exitCode != VirtualMachine::ExitCodes::Success)
        log_.Error(VirtualMachine::ExitCodeString(exitCode));
}

// ================================================================================<commit_msg>Added "Audio" module to shell default script.<commit_after>/*
 * Shell.cpp
 *
 * This file is part of the "XieXie 2.0 Project" (Copyright (c) 2014 by Lukas Hermanns)
 * See "LICENSE.txt" for license information.
 */

#include "Shell.h"
#include "CommandFactory.h"
#include "Version.h"
#include "ConsoleManip.h"
#include "StringModifier.h"
#include "MakeUnique.h"

#include <sstream>
#include <xiexie/xiexie.h>

using namespace Platform::ConsoleManip;
using namespace XieXie;

void Shell::Execute(StreamParser parser)
{
    try
    {
        while (parser)
        {
            /* Read next command */
            auto cmdName = parser.Get();
            auto cmd = CommandFactory::Instance()->FindCommand(cmdName);

            /* Process command line */
            if (cmd)
            {
                parser.Accept();

                if (parser.Get() == "--help")
                {
                    /* Print help for command */
                    parser.Accept();
                    HelpPrinter printer;
                    cmd->Help(printer);
                    printer.Flush(log_);
                }
                else
                {
                    /* Execute command */
                    cmd->Execute(parser, log_);
                }
            }
            else
            {
                log_.Error("unknown command: " + cmdName);
                parser.Accept();
            }
        }
    }
    catch (const std::exception& err)
    {
        log_.Error(err.what());
    }
}

// Define the code for the default script
static void AppendDefaultScript(std::stringstream& sstr)
{
    sstr
        << "import MsgBox, Console, Integer, ASCII, Algo, Utils, Audio" << std::endl
        << "class Script { " << std::endl
        << "void print(bool val) { print(val ? \"true\" : \"false\") }" << std::endl
        << "void print(int val) { Intrinsics.printInt(val) }" << std::endl
        << "void print(float val) { Intrinsics.printFloat(val) }" << std::endl
        << "void print(String val) { Intrinsics.print(val.pointer()) }" << std::endl
        << "void printLn(bool val) { printLn(val ? \"true\" : \"false\") }" << std::endl
        << "void printLn(int val) { Intrinsics.printInt(val) Intrinsics.printLn(0) }" << std::endl
        << "void printLn(float val) { Intrinsics.printFloat(val) Intrinsics.printLn(0) }" << std::endl
        << "void printLn(String val) { Intrinsics.printLn(val.pointer()) }" << std::endl
        << "void print(int[] val) { foreach v : val { print(v) print(\" \") } }" << std::endl
        << "void print(float[] val) { foreach v : val { print(v) print(\" \") } }" << std::endl
        << "void print(String[] val) { foreach v : val { print(v) print(\" \") } }" << std::endl
        << "void printLn(int[] val) { foreach v : val { printLn(v) } }" << std::endl
        << "void printLn(float[] val) { foreach v : val { printLn(v) } }" << std::endl
        << "void printLn(String[] val) { foreach v : val { printLn(v) } }" << std::endl
        << "static void main() {" << std::endl
        << "    var script := new Script()" << std::endl
        << "}" << std::endl
        << "init() {" << std::endl
    ;
}

void Shell::Script(std::istream& stream, bool appendDefaultScript)
{
    /* Print info at start-up */
    std::cout << "XieXie Compiler " << Version::AsString() << std::endl;
    std::cout << "Copyright (c) 2014-2015 Lukas Hermanns" << std::endl;

    /* Read and print each line from input stream */
    std::string line;
    auto source = MakeUnique<std::stringstream>();

    size_t lineNum = 0;

    if (appendDefaultScript)
        AppendDefaultScript(*source);

    while (!stream.eof())
    {
        /* Print line number */
        {
            ScopedColor color(std::cout, Color::Green | Color::Blue);
            std::cout << NumberOffset(++lineNum, 10, '0') << "  ";
        }

        /* Print line */
        {
            ScopedColor color(std::cout, Color::Cyan);
            std::getline(stream, line);
            *source << line << std::endl;
        }
    }

    if (appendDefaultScript)
        *source << "}}" << std::endl;

    /* Run script immediately */
    auto exitCode = RunFromString(
        source->str(),
        CompileFlags::Warn,
        VirtualMachine::Stack::defaultSize,
        &log_.stream
    );

    if (exitCode != VirtualMachine::ExitCodes::Success)
        log_.Error(VirtualMachine::ExitCodeString(exitCode));
}

// ================================================================================<|endoftext|>


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

  BARD: Basic Augmented Reality Demo.

  Copyright (c) University College London (UCL). All rights reserved.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.

  See LICENSE.txt in the top level directory for details.

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

#include <QApplication>
#include <tclap/CmdLine.h>
#include <cv.h>
#include <iostream>

#include "bardOpenCVVideoSource.h"
#include "bardArucoProcessor.h"
#include "bardPnPRegistration.h"
#include "bardTrackingModelData.h"
#include "bardMainWindow.h"
#include "bardMainRenderingWidget.h"
#include "bardVTKModelPipeline.h"
#include "bardFileIO.h"

int main(int argc, char** argv)
{
  try
  {
    TCLAP::CmdLine cmd("Basic Augmented Reality Demo", ' ', "0.1");
    TCLAP::ValueArg<std::string> intrinsicsArg("i","intrinsics","File containing (3x3) camera intrinsics then (1x4) distortion coefficients.",false,"","string");
    TCLAP::ValueArg<std::string> worldRefArg("w","world","File containing (nx4) points of a tracker board defining world coordinates.",true,"","string");
    TCLAP::ValueArg<std::string> pointerRefArg("p","pointer","File containing (nx4) points of a tracker board defining pointer coordinates.",false,"","string");
    TCLAP::ValueArg<std::string> modelArg("m","model","vtkPolyData file a model to be rendered in the scene.",false,"","string");
    TCLAP::ValueArg<std::string> outputDirArg("d", "directory", "Output directory to dump files.", false, "", "string");
    TCLAP::ValueArg<std::string> modelAlignArg("a", "align", "File containing (4x4) transform, to align models to world.", false, "", "string");
    TCLAP::ValueArg<float> imageOpacityArg("o","opacity","Image opacity.",false,0.5,"float");
    TCLAP::ValueArg<int> imageXSizeArg("x","xsize","xsize when calibrating.",true,1,"int");
    TCLAP::ValueArg<int> imageYSizeArg("y","ysize","ysize when calibrating.",true,1,"int");
    TCLAP::SwitchArg doDistortionArg("c","correct","Do distortion correction.", false);
    TCLAP::SwitchArg flipSwitchArg("f","flip","Flip in Y-axis.", false);
    TCLAP::SwitchArg pointerRecordMatrixArg("r","record","Record pointer matrix (e.g. for pivot calib).", false);
    TCLAP::SwitchArg pointerRecordTipArg("t","tip","Record pointer tip (e.g. for registration).", false);
    cmd.add( intrinsicsArg );
    cmd.add( worldRefArg );
    cmd.add( pointerRefArg );
    cmd.add( modelArg );
    cmd.add( outputDirArg );
    cmd.add( modelAlignArg );
    cmd.add( imageOpacityArg );
    cmd.add( imageXSizeArg );
    cmd.add( imageYSizeArg );
    cmd.add( doDistortionArg );
    cmd.add( flipSwitchArg );
    cmd.add( pointerRecordMatrixArg );
    cmd.add( pointerRecordTipArg );
    cmd.parse( argc, argv );
    std::string intrinsicsFile = intrinsicsArg.getValue();
    std::string worldRef = worldRefArg.getValue();
    std::string pointerRef = pointerRefArg.getValue();
    std::string modelFile = modelArg.getValue();
    std::string outputDir = outputDirArg.getValue();
    std::string modelAlignFile = modelAlignArg.getValue();
    float opacity = imageOpacityArg.getValue();
    int xSize = imageXSizeArg.getValue();
    int ySize = imageYSizeArg.getValue();
    bool doDistortionCorrection = doDistortionArg.getValue();
    bool doFlipY = flipSwitchArg.getValue();
    bool pointerRecordMatrix = pointerRecordMatrixArg.getValue();
    bool pointerRecordTip =pointerRecordTipArg.getValue();

    if ((pointerRecordMatrix || pointerRecordTip) && pointerRef.size() == 0)
    {
      throw std::runtime_error("You asked to record pointer movement, but did not provide a pointer reference model.");
    }
    if ((pointerRecordMatrix || pointerRecordTip) && outputDir.size() == 0)
    {
      throw std::runtime_error("You asked to record pointer movement, but did not provide an output directory.");
    }

    cv::Point2i imageSize;
    imageSize.x = xSize;
    imageSize.y = ySize;

    QApplication app(argc, argv);
    app.setOrganizationName("CMIC");
    app.setApplicationName("BARD");

    bard::OpenCVVideoSource mySource("");
    mySource.SetFlipY(doFlipY);
    mySource.SetUndistort(doDistortionCorrection);

    bard::ArucoProcessor myProcessor;
    bard::PnPRegistration myRegistration;
    bard::TrackingModelData myWorldTrackingModel(worldRef);

    bard::MainRenderingWidget myWidget;
    myWidget.SetCalibratedImageSize(imageSize);
    myWidget.SetVideoSource(&mySource);
    myWidget.SetTagProcessor(&myProcessor);
    myWidget.SetRegistrationAlgorithm(&myRegistration);
    myWidget.SetImageOpacity(opacity);
    myWidget.SetOutputDirectory(outputDir);
    myWidget.SetRecordMatrix(pointerRecordMatrix);
    myWidget.SetRecordPointOfInterest(pointerRecordTip);

    // Load intrinsic/distortion parameters
    cv::Matx33d intrinsicParameters;
    cv::Matx14d distortionParameters;
    if (intrinsicsFile.size() > 0)
    {
      bard::LoadCameraParameters(intrinsicsFile, intrinsicParameters, distortionParameters);
      myWidget.SetCameraIntrinsics(intrinsicParameters);
    }

    // Loads 4x4 registration matrix.
    cv::Matx44d registerModelsToWorld;
    if (modelAlignFile.size() > 0)
    {
      registerModelsToWorld = bard::LoadMatrixFromFile(modelAlignFile);
      myWidget.SetModelsToWorld(registerModelsToWorld);
    }

    // Adds data-files that enable us to do tag tracking of various objects.
    myWidget.AddTrackingModel(&myWorldTrackingModel);
    bard::TrackingModelData* pointerTrackingModel = NULL;
    if (pointerRef.size() > 0)
    {
      pointerTrackingModel = new bard::TrackingModelData(pointerRef);
      myWidget.AddTrackingModel(pointerTrackingModel);
    }

    // Add VTK files that enable us to visualise virtual objects in scene.
    bard::VTKModelPipeline *modelForVisualisation = NULL;
    if (modelFile.size() > 0)
    {
      modelForVisualisation = new bard::VTKModelPipeline(modelFile);
      myWidget.AddVTKModel(modelForVisualisation);
    }

    bard::MainWindow mainWin;
    mainWin.setCentralWidget(&myWidget);
    mainWin.show();

    myWidget.GetInteractor()->Disable();
    myWidget.SetEnableImage(true);
    myWidget.SetEnableTrackingModels(true);
    myWidget.SetEnableVTKModels(true);

    int status = app.exec();

    // Tidy up.
    if (pointerTrackingModel != NULL)
    {
      delete pointerTrackingModel;
    }
    if (modelForVisualisation != NULL)
    {
      delete modelForVisualisation;
    }
    return status;
  }
  catch (TCLAP::ArgException &e)
  {
    std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
  }
  catch (std::runtime_error& e)
  {
    std::cerr << "error: " << e.what() << std::endl;
  }
}
<commit_msg>Set bard main window to fixed size<commit_after>/*============================================================================

  BARD: Basic Augmented Reality Demo.

  Copyright (c) University College London (UCL). All rights reserved.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.

  See LICENSE.txt in the top level directory for details.

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

#include <QApplication>
#include <tclap/CmdLine.h>
#include <cv.h>
#include <iostream>

#include "bardOpenCVVideoSource.h"
#include "bardArucoProcessor.h"
#include "bardPnPRegistration.h"
#include "bardTrackingModelData.h"
#include "bardMainWindow.h"
#include "bardMainRenderingWidget.h"
#include "bardVTKModelPipeline.h"
#include "bardFileIO.h"

int main(int argc, char** argv)
{
  try
  {
    TCLAP::CmdLine cmd("Basic Augmented Reality Demo", ' ', "0.1");
    TCLAP::ValueArg<std::string> intrinsicsArg("i","intrinsics","File containing (3x3) camera intrinsics then (1x4) distortion coefficients.",false,"","string");
    TCLAP::ValueArg<std::string> worldRefArg("w","world","File containing (nx4) points of a tracker board defining world coordinates.",true,"","string");
    TCLAP::ValueArg<std::string> pointerRefArg("p","pointer","File containing (nx4) points of a tracker board defining pointer coordinates.",false,"","string");
    TCLAP::ValueArg<std::string> modelArg("m","model","vtkPolyData file a model to be rendered in the scene.",false,"","string");
    TCLAP::ValueArg<std::string> outputDirArg("d", "directory", "Output directory to dump files.", false, "", "string");
    TCLAP::ValueArg<std::string> modelAlignArg("a", "align", "File containing (4x4) transform, to align models to world.", false, "", "string");
    TCLAP::ValueArg<float> imageOpacityArg("o","opacity","Image opacity.",false,0.5,"float");
    TCLAP::ValueArg<int> imageXSizeArg("x","xsize","xsize when calibrating.",true,1,"int");
    TCLAP::ValueArg<int> imageYSizeArg("y","ysize","ysize when calibrating.",true,1,"int");
    TCLAP::SwitchArg doDistortionArg("c","correct","Do distortion correction.", false);
    TCLAP::SwitchArg flipSwitchArg("f","flip","Flip in Y-axis.", false);
    TCLAP::SwitchArg pointerRecordMatrixArg("r","record","Record pointer matrix (e.g. for pivot calib).", false);
    TCLAP::SwitchArg pointerRecordTipArg("t","tip","Record pointer tip (e.g. for registration).", false);
    cmd.add( intrinsicsArg );
    cmd.add( worldRefArg );
    cmd.add( pointerRefArg );
    cmd.add( modelArg );
    cmd.add( outputDirArg );
    cmd.add( modelAlignArg );
    cmd.add( imageOpacityArg );
    cmd.add( imageXSizeArg );
    cmd.add( imageYSizeArg );
    cmd.add( doDistortionArg );
    cmd.add( flipSwitchArg );
    cmd.add( pointerRecordMatrixArg );
    cmd.add( pointerRecordTipArg );
    cmd.parse( argc, argv );
    std::string intrinsicsFile = intrinsicsArg.getValue();
    std::string worldRef = worldRefArg.getValue();
    std::string pointerRef = pointerRefArg.getValue();
    std::string modelFile = modelArg.getValue();
    std::string outputDir = outputDirArg.getValue();
    std::string modelAlignFile = modelAlignArg.getValue();
    float opacity = imageOpacityArg.getValue();
    int xSize = imageXSizeArg.getValue();
    int ySize = imageYSizeArg.getValue();
    bool doDistortionCorrection = doDistortionArg.getValue();
    bool doFlipY = flipSwitchArg.getValue();
    bool pointerRecordMatrix = pointerRecordMatrixArg.getValue();
    bool pointerRecordTip =pointerRecordTipArg.getValue();

    if ((pointerRecordMatrix || pointerRecordTip) && pointerRef.size() == 0)
    {
      throw std::runtime_error("You asked to record pointer movement, but did not provide a pointer reference model.");
    }
    if ((pointerRecordMatrix || pointerRecordTip) && outputDir.size() == 0)
    {
      throw std::runtime_error("You asked to record pointer movement, but did not provide an output directory.");
    }

    cv::Point2i imageSize;
    imageSize.x = xSize;
    imageSize.y = ySize;

    QApplication app(argc, argv);
    app.setOrganizationName("CMIC");
    app.setApplicationName("BARD");

    bard::OpenCVVideoSource mySource("");
    mySource.SetFlipY(doFlipY);
    mySource.SetUndistort(doDistortionCorrection);

    bard::ArucoProcessor myProcessor;
    bard::PnPRegistration myRegistration;
    bard::TrackingModelData myWorldTrackingModel(worldRef);

    bard::MainRenderingWidget myWidget;
    myWidget.SetCalibratedImageSize(imageSize);
    myWidget.SetVideoSource(&mySource);
    myWidget.SetTagProcessor(&myProcessor);
    myWidget.SetRegistrationAlgorithm(&myRegistration);
    myWidget.SetImageOpacity(opacity);
    myWidget.SetOutputDirectory(outputDir);
    myWidget.SetRecordMatrix(pointerRecordMatrix);
    myWidget.SetRecordPointOfInterest(pointerRecordTip);

    // Load intrinsic/distortion parameters
    cv::Matx33d intrinsicParameters;
    cv::Matx14d distortionParameters;
    if (intrinsicsFile.size() > 0)
    {
      bard::LoadCameraParameters(intrinsicsFile, intrinsicParameters, distortionParameters);
      myWidget.SetCameraIntrinsics(intrinsicParameters);
    }

    // Loads 4x4 registration matrix.
    cv::Matx44d registerModelsToWorld;
    if (modelAlignFile.size() > 0)
    {
      registerModelsToWorld = bard::LoadMatrixFromFile(modelAlignFile);
      myWidget.SetModelsToWorld(registerModelsToWorld);
    }

    // Adds data-files that enable us to do tag tracking of various objects.
    myWidget.AddTrackingModel(&myWorldTrackingModel);
    bard::TrackingModelData* pointerTrackingModel = NULL;
    if (pointerRef.size() > 0)
    {
      pointerTrackingModel = new bard::TrackingModelData(pointerRef);
      myWidget.AddTrackingModel(pointerTrackingModel);
    }

    // Add VTK files that enable us to visualise virtual objects in scene.
    bard::VTKModelPipeline *modelForVisualisation = NULL;
    if (modelFile.size() > 0)
    {
      modelForVisualisation = new bard::VTKModelPipeline(modelFile);
      myWidget.AddVTKModel(modelForVisualisation);
    }

    bard::MainWindow mainWin;
    mainWin.setCentralWidget(&myWidget);
    mainWin.show();
    mainWin.setFixedSize(xSize, ySize);

    myWidget.GetInteractor()->Disable();
    myWidget.SetEnableImage(true);
    myWidget.SetEnableTrackingModels(true);
    myWidget.SetEnableVTKModels(true);

    int status = app.exec();

    // Tidy up.
    if (pointerTrackingModel != NULL)
    {
      delete pointerTrackingModel;
    }
    if (modelForVisualisation != NULL)
    {
      delete modelForVisualisation;
    }
    return status;
  }
  catch (TCLAP::ArgException &e)
  {
    std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
  }
  catch (std::runtime_error& e)
  {
    std::cerr << "error: " << e.what() << std::endl;
  }
}
<|endoftext|>


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


<commit_before><commit_msg>fix return code on windows<commit_after><|endoftext|>


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

#ifndef _BASIDE3_HXX
#define _BASIDE3_HXX

#ifndef _SVHEADER_HXX
//#include <svheader.hxx>
#endif

#include <bastypes.hxx>
#include <svtools/undo.hxx>

#ifndef _COM_SUN_STAR_SCRIPT_XLIBRYARYCONTAINER_HPP_
#include <com/sun/star/script/XLibraryContainer.hpp>
#endif

class Printer;
class StarBASIC;
class SfxItemSet;
class DlgEditor;
class DlgEdModel;
class DlgEdPage;
class DlgEdView;
class SfxUndoManager;

class DialogWindow: public IDEBaseWindow
{
private:
    DlgEditor*          pEditor;
    SfxUndoManager*     pUndoMgr;
    Link                aOldNotifyUndoActionHdl;

protected:
    virtual void        Paint( const Rectangle& );
    virtual void        Resize();

    virtual void        MouseButtonDown( const MouseEvent& rMEvt );
    virtual void        MouseButtonUp( const MouseEvent& rMEvt );
    virtual void        MouseMove( const MouseEvent& rMEvt );
    virtual void        KeyInput( const KeyEvent& rKEvt );
    virtual void        Command( const CommandEvent& rCEvt );
    virtual void        LoseFocus();

    DECL_LINK( NotifyUndoActionHdl, SfxUndoAction * );
    virtual void        DoInit();
    virtual void        DoScroll( ScrollBar* pCurScrollBar );
    virtual void        DataChanged( const DataChangedEvent& rDCEvt );
    void                InitSettings(BOOL bFont,BOOL bForeground,BOOL bBackground);

public:
                        TYPEINFO();
                        DialogWindow( Window* pParent, SfxObjectShell* pShell, String aLibName, String aName,
                            const com::sun::star::uno::Reference< com::sun::star::container::XNameContainer >& xDialogModel );
                        DialogWindow( DialogWindow* pCurView );
                        ~DialogWindow();

    virtual void        ExecuteCommand( SfxRequest& rReq );
    virtual void        GetState( SfxItemSet& );
    DlgEditor*          GetEditor() const   { return pEditor; }
    ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > GetDialog() const;
    DlgEdModel*         GetModel() const;
    DlgEdPage*          GetPage() const;
    DlgEdView*          GetView() const;
    BOOL                RenameDialog( const String& rNewName );
    void                DisableBrowser();
    void                UpdateBrowser();
    virtual String      GetTitle();
    virtual BasicEntryDescriptor CreateEntryDescriptor();
    virtual void        SetReadOnly( BOOL bReadOnly );
    virtual BOOL        IsReadOnly();

    virtual void        StoreData();
    virtual BOOL        IsModified();
    virtual BOOL        IsPasteAllowed();

    virtual SfxUndoManager* GetUndoManager();
    virtual void        PrintData( Printer* pPrinter );
    virtual void        Deactivating();

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();
};

#endif  // _BASIDE3_HXX
<commit_msg>INTEGRATION: CWS basmgr02 (1.6.144); FILE MERGED 2007/02/21 09:33:04 fs 1.6.144.1: #i73331# encapsulate (nearly) all usages of SfxObjectShell in the ScriptDocument class<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: baside3.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2007-03-15 16:01:16 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _BASIDE3_HXX
#define _BASIDE3_HXX

#ifndef _SVHEADER_HXX
//#include <svheader.hxx>
#endif

#include <bastypes.hxx>
#include <svtools/undo.hxx>

#ifndef _COM_SUN_STAR_SCRIPT_XLIBRYARYCONTAINER_HPP_
#include <com/sun/star/script/XLibraryContainer.hpp>
#endif

class Printer;
class StarBASIC;
class SfxItemSet;
class DlgEditor;
class DlgEdModel;
class DlgEdPage;
class DlgEdView;
class SfxUndoManager;

class DialogWindow: public IDEBaseWindow
{
private:
    DlgEditor*          pEditor;
    SfxUndoManager*     pUndoMgr;
    Link                aOldNotifyUndoActionHdl;

protected:
    virtual void        Paint( const Rectangle& );
    virtual void        Resize();

    virtual void        MouseButtonDown( const MouseEvent& rMEvt );
    virtual void        MouseButtonUp( const MouseEvent& rMEvt );
    virtual void        MouseMove( const MouseEvent& rMEvt );
    virtual void        KeyInput( const KeyEvent& rKEvt );
    virtual void        Command( const CommandEvent& rCEvt );
    virtual void        LoseFocus();

    DECL_LINK( NotifyUndoActionHdl, SfxUndoAction * );
    virtual void        DoInit();
    virtual void        DoScroll( ScrollBar* pCurScrollBar );
    virtual void        DataChanged( const DataChangedEvent& rDCEvt );
    void                InitSettings(BOOL bFont,BOOL bForeground,BOOL bBackground);

public:
                        TYPEINFO();
                        DialogWindow( Window* pParent, const ScriptDocument& rDocument, String aLibName, String aName,
                            const com::sun::star::uno::Reference< com::sun::star::container::XNameContainer >& xDialogModel );
                        DialogWindow( DialogWindow* pCurView ); // never implemented
                        ~DialogWindow();

    virtual void        ExecuteCommand( SfxRequest& rReq );
    virtual void        GetState( SfxItemSet& );
    DlgEditor*          GetEditor() const   { return pEditor; }
    ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > GetDialog() const;
    DlgEdModel*         GetModel() const;
    DlgEdPage*          GetPage() const;
    DlgEdView*          GetView() const;
    BOOL                RenameDialog( const String& rNewName );
    void                DisableBrowser();
    void                UpdateBrowser();
    virtual String      GetTitle();
    virtual BasicEntryDescriptor CreateEntryDescriptor();
    virtual void        SetReadOnly( BOOL bReadOnly );
    virtual BOOL        IsReadOnly();

    virtual void        StoreData();
    virtual BOOL        IsModified();
    virtual BOOL        IsPasteAllowed();

    virtual SfxUndoManager* GetUndoManager();
    virtual void        PrintData( Printer* pPrinter );
    virtual void        Deactivating();

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();
};

#endif  // _BASIDE3_HXX
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file contains unit tests for PEImage.

#include "testing/gtest/include/gtest/gtest.h"
#include "base/win/pe_image.h"
#include "base/win/windows_version.h"

namespace base {
namespace win {

// Just counts the number of invocations.
bool ExportsCallback(const PEImage &image,
                     DWORD ordinal,
                     DWORD hint,
                     LPCSTR name,
                     PVOID function,
                     LPCSTR forward,
                     PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool ImportsCallback(const PEImage &image,
                     LPCSTR module,
                     DWORD ordinal,
                     LPCSTR name,
                     DWORD hint,
                     PIMAGE_THUNK_DATA iat,
                     PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool SectionsCallback(const PEImage &image,
                       PIMAGE_SECTION_HEADER header,
                       PVOID section_start,
                       DWORD section_size,
                       PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool RelocsCallback(const PEImage &image,
                    WORD type,
                    PVOID address,
                    PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool ImportChunksCallback(const PEImage &image,
                          LPCSTR module,
                          PIMAGE_THUNK_DATA name_table,
                          PIMAGE_THUNK_DATA iat,
                          PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool DelayImportChunksCallback(const PEImage &image,
                               PImgDelayDescr delay_descriptor,
                               LPCSTR module,
                               PIMAGE_THUNK_DATA name_table,
                               PIMAGE_THUNK_DATA iat,
                               PIMAGE_THUNK_DATA bound_iat,
                               PIMAGE_THUNK_DATA unload_iat,
                               PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// We'll be using some known values for the tests.
enum Value {
  sections = 0,
  imports_dlls,
  delay_dlls,
  exports,
  imports,
  delay_imports,
  relocs
};

// Retrieves the expected value from advapi32.dll based on the OS.
int GetExpectedValue(Value value, DWORD os) {
  const int xp_delay_dlls = 2;
  const int xp_exports = 675;
  const int xp_imports = 422;
  const int xp_delay_imports = 8;
  const int xp_relocs = 9180;
  const int vista_delay_dlls = 4;
  const int vista_exports = 799;
  const int vista_imports = 476;
  const int vista_delay_imports = 24;
  const int vista_relocs = 10188;
  const int w2k_delay_dlls = 0;
  const int w2k_exports = 566;
  const int w2k_imports = 357;
  const int w2k_delay_imports = 0;
  const int w2k_relocs = 7388;
  const int win7_delay_dlls = 7;
  const int win7_exports = 806;
  const int win7_imports = 568;
  const int win7_delay_imports = 71;
  const int win7_relocs = 7812;

  // Contains the expected value, for each enumerated property (Value), and the
  // OS version: [Value][os_version]
  const int expected[][4] = {
    {4, 4, 4, 4},
    {3, 3, 3, 13},
    {w2k_delay_dlls, xp_delay_dlls, vista_delay_dlls, win7_delay_dlls},
    {w2k_exports, xp_exports, vista_exports, win7_exports},
    {w2k_imports, xp_imports, vista_imports, win7_imports},
    {w2k_delay_imports, xp_delay_imports,
     vista_delay_imports, win7_delay_imports},
    {w2k_relocs, xp_relocs, vista_relocs, win7_relocs}
  };

  if (value > relocs)
    return 0;
  if (50 == os)
    os = 0;  // 5.0
  else if (51 == os || 52 == os)
    os = 1;
  else if (os == 60)
    os = 2;  // 6.x
  else if (os >= 61)
    os = 3;
  else
    return 0;

  return expected[value][os];
}

// Tests that we are able to enumerate stuff from a PE file, and that
// the actual number of items found is within the expected range.
TEST(PEImageTest, EnumeratesPE) {
  // Windows Server 2003 is not supported as a test environment for this test.
  if (base::win::GetVersion() == base::win::VERSION_SERVER_2003)
    return;
  HMODULE module = LoadLibrary(L"advapi32.dll");
  ASSERT_TRUE(NULL != module);

  PEImage pe(module);
  int count = 0;
  EXPECT_TRUE(pe.VerifyMagic());

  DWORD os = pe.GetNTHeaders()->OptionalHeader.MajorOperatingSystemVersion;
  os = os * 10 + pe.GetNTHeaders()->OptionalHeader.MinorOperatingSystemVersion;

  pe.EnumSections(SectionsCallback, &count);
  EXPECT_EQ(GetExpectedValue(sections, os), count);

  count = 0;
  pe.EnumImportChunks(ImportChunksCallback, &count);
  EXPECT_EQ(GetExpectedValue(imports_dlls, os), count);

  count = 0;
  pe.EnumDelayImportChunks(DelayImportChunksCallback, &count);
  EXPECT_EQ(GetExpectedValue(delay_dlls, os), count);

  count = 0;
  pe.EnumExports(ExportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(exports, os) - 20);
  EXPECT_LT(count, GetExpectedValue(exports, os) + 100);

  count = 0;
  pe.EnumAllImports(ImportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(imports, os) - 20);
  EXPECT_LT(count, GetExpectedValue(imports, os) + 100);

  count = 0;
  pe.EnumAllDelayImports(ImportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(delay_imports, os) - 2);
  EXPECT_LT(count, GetExpectedValue(delay_imports, os) + 8);

  count = 0;
  pe.EnumRelocs(RelocsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(relocs, os) - 150);
  EXPECT_LT(count, GetExpectedValue(relocs, os) + 1500);

  FreeLibrary(module);
}

// Tests that we can locate an specific exported symbol, by name and by ordinal.
TEST(PEImageTest, RetrievesExports) {
  HMODULE module = LoadLibrary(L"advapi32.dll");
  ASSERT_TRUE(NULL != module);

  PEImage pe(module);
  WORD ordinal;

  EXPECT_TRUE(pe.GetProcOrdinal("RegEnumKeyExW", &ordinal));

  FARPROC address1 = pe.GetProcAddress("RegEnumKeyExW");
  FARPROC address2 = pe.GetProcAddress(reinterpret_cast<char*>(ordinal));
  EXPECT_TRUE(address1 != NULL);
  EXPECT_TRUE(address2 != NULL);
  EXPECT_TRUE(address1 == address2);

  FreeLibrary(module);
}

}  // namespace win
}  // namespace base
<commit_msg>Fixes for the EnumeratesPE base_unittest failures seen on Windows 8. The values used by this test for expected imports/exports, etc on Windows 8 needed to be changed.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file contains unit tests for PEImage.

#include "testing/gtest/include/gtest/gtest.h"
#include "base/win/pe_image.h"
#include "base/win/windows_version.h"

namespace base {
namespace win {

// Just counts the number of invocations.
bool ExportsCallback(const PEImage &image,
                     DWORD ordinal,
                     DWORD hint,
                     LPCSTR name,
                     PVOID function,
                     LPCSTR forward,
                     PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool ImportsCallback(const PEImage &image,
                     LPCSTR module,
                     DWORD ordinal,
                     LPCSTR name,
                     DWORD hint,
                     PIMAGE_THUNK_DATA iat,
                     PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool SectionsCallback(const PEImage &image,
                       PIMAGE_SECTION_HEADER header,
                       PVOID section_start,
                       DWORD section_size,
                       PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool RelocsCallback(const PEImage &image,
                    WORD type,
                    PVOID address,
                    PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool ImportChunksCallback(const PEImage &image,
                          LPCSTR module,
                          PIMAGE_THUNK_DATA name_table,
                          PIMAGE_THUNK_DATA iat,
                          PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool DelayImportChunksCallback(const PEImage &image,
                               PImgDelayDescr delay_descriptor,
                               LPCSTR module,
                               PIMAGE_THUNK_DATA name_table,
                               PIMAGE_THUNK_DATA iat,
                               PIMAGE_THUNK_DATA bound_iat,
                               PIMAGE_THUNK_DATA unload_iat,
                               PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// We'll be using some known values for the tests.
enum Value {
  sections = 0,
  imports_dlls,
  delay_dlls,
  exports,
  imports,
  delay_imports,
  relocs
};

// Retrieves the expected value from advapi32.dll based on the OS.
int GetExpectedValue(Value value, DWORD os) {
  const int xp_delay_dlls = 2;
  const int xp_exports = 675;
  const int xp_imports = 422;
  const int xp_delay_imports = 8;
  const int xp_relocs = 9180;
  const int vista_delay_dlls = 4;
  const int vista_exports = 799;
  const int vista_imports = 476;
  const int vista_delay_imports = 24;
  const int vista_relocs = 10188;
  const int w2k_delay_dlls = 0;
  const int w2k_exports = 566;
  const int w2k_imports = 357;
  const int w2k_delay_imports = 0;
  const int w2k_relocs = 7388;
  const int win7_delay_dlls = 7;
  const int win7_exports = 806;
  const int win7_imports = 568;
  const int win7_delay_imports = 71;
  const int win7_relocs = 7812;
  const int win8_delay_dlls = 9;
  const int win8_exports = 806;
  const int win8_imports = 568;
  const int win8_delay_imports = 113;
  const int win8_relocs = 9478;

  // Contains the expected value, for each enumerated property (Value), and the
  // OS version: [Value][os_version]
  const int expected[][5] = {
    {4, 4, 4, 4, 5},
    {3, 3, 3, 13, 19},
    {w2k_delay_dlls, xp_delay_dlls, vista_delay_dlls, win7_delay_dlls,
     win8_delay_dlls},
    {w2k_exports, xp_exports, vista_exports, win7_exports, win8_exports},
    {w2k_imports, xp_imports, vista_imports, win7_imports, win8_imports},
    {w2k_delay_imports, xp_delay_imports,
     vista_delay_imports, win7_delay_imports, win8_delay_imports},
    {w2k_relocs, xp_relocs, vista_relocs, win7_relocs, win8_relocs}
  };

  if (value > relocs)
    return 0;
  if (50 == os)
    os = 0;  // 5.0
  else if (51 == os || 52 == os)
    os = 1;
  else if (os == 60)
    os = 2;  // 6.x
  else if (os == 61)
    os = 3;
  else if (os >= 62)
    os = 4;
  else
    return 0;

  return expected[value][os];
}

// Tests that we are able to enumerate stuff from a PE file, and that
// the actual number of items found is within the expected range.
TEST(PEImageTest, EnumeratesPE) {
  // Windows Server 2003 is not supported as a test environment for this test.
  if (base::win::GetVersion() == base::win::VERSION_SERVER_2003)
    return;
  HMODULE module = LoadLibrary(L"advapi32.dll");
  ASSERT_TRUE(NULL != module);

  PEImage pe(module);
  int count = 0;
  EXPECT_TRUE(pe.VerifyMagic());

  DWORD os = pe.GetNTHeaders()->OptionalHeader.MajorOperatingSystemVersion;
  os = os * 10 + pe.GetNTHeaders()->OptionalHeader.MinorOperatingSystemVersion;

  pe.EnumSections(SectionsCallback, &count);
  EXPECT_EQ(GetExpectedValue(sections, os), count);

  count = 0;
  pe.EnumImportChunks(ImportChunksCallback, &count);
  EXPECT_EQ(GetExpectedValue(imports_dlls, os), count);

  count = 0;
  pe.EnumDelayImportChunks(DelayImportChunksCallback, &count);
  EXPECT_EQ(GetExpectedValue(delay_dlls, os), count);

  count = 0;
  pe.EnumExports(ExportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(exports, os) - 20);
  EXPECT_LT(count, GetExpectedValue(exports, os) + 100);

  count = 0;
  pe.EnumAllImports(ImportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(imports, os) - 20);
  EXPECT_LT(count, GetExpectedValue(imports, os) + 100);

  count = 0;
  pe.EnumAllDelayImports(ImportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(delay_imports, os) - 2);
  EXPECT_LT(count, GetExpectedValue(delay_imports, os) + 8);

  count = 0;
  pe.EnumRelocs(RelocsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(relocs, os) - 150);
  EXPECT_LT(count, GetExpectedValue(relocs, os) + 1500);

  FreeLibrary(module);
}

// Tests that we can locate an specific exported symbol, by name and by ordinal.
TEST(PEImageTest, RetrievesExports) {
  HMODULE module = LoadLibrary(L"advapi32.dll");
  ASSERT_TRUE(NULL != module);

  PEImage pe(module);
  WORD ordinal;

  EXPECT_TRUE(pe.GetProcOrdinal("RegEnumKeyExW", &ordinal));

  FARPROC address1 = pe.GetProcAddress("RegEnumKeyExW");
  FARPROC address2 = pe.GetProcAddress(reinterpret_cast<char*>(ordinal));
  EXPECT_TRUE(address1 != NULL);
  EXPECT_TRUE(address2 != NULL);
  EXPECT_TRUE(address1 == address2);

  FreeLibrary(module);
}

}  // namespace win
}  // namespace base
<|endoftext|>


<commit_before>
// (c) COPYRIGHT URI/MIT 1997
// Please read the full copyright statement in the file COPYRIGH.
//
// Authors:
//      jhrg,jimg       James Gallagher (jgallagher@gso.uri.edu)

// Implementation of the DODSFilter class. This class is used to build dods
// filter programs which, along with a CGI program, comprise DODS servers.
// jhrg 8/26/97

// $Log: DODSFilter.cc,v $
// Revision 1.2  1998/02/11 22:00:46  jimg
// Added call to util.cc:deflate_exists() to send_data(). This means that
// send_data() will only try to start the compressor if an executable copy of
// deflate can be found. If, for any reason a copy of deflate cannot be found
// data is sent without trying to compress it.
//
// Revision 1.1  1997/08/28 20:39:02  jimg
// Created
//

#ifdef __GNUG__
#pragma "implemenation"
#endif

#include "config_dap.h"

static char rcsid[] __unused__ = {"$Id: DODSFilter.cc,v 1.2 1998/02/11 22:00:46 jimg Exp $"};

#include <iostream.h>
#include <strstream.h>
#include <String.h>
#include <GetOpt.h>

#include "DAS.h"
#include "DDS.h"
#include "debug.h"
#include "cgi_util.h"
#include "DODSFilter.h"

DODSFilter::DODSFilter(int argc,char *argv[]) : comp(false), ver(false),
    bad_options(false), dataset(""), ce(""), cgi_ver(""),
    anc_dir(""), anc_file("")
{
    program_name = argv[0];

    int option_char;
    GetOpt getopt (argc, argv, "ce:v:d:f:");

    while ((option_char = getopt()) != EOF)
	switch (option_char) {
	  case 'c': comp = true; break;
	  case 'e': ce = getopt.optarg; break;
	  case 'v': ver = true; cgi_ver = getopt.optarg; break;
	  case 'd': anc_dir = getopt.optarg; break;
	  case 'f': anc_file = getopt.optarg; break;
	  default: bad_options = true; break;
	}

    int next_arg = getopt.optind;
    if(next_arg < argc)
	dataset = argv[next_arg];
    else
	bad_options = true;
}

DODSFilter::~DODSFilter()
{
}

bool
DODSFilter::OK()
{

    return !bad_options;
}

bool
DODSFilter::version()
{
    return ver;
}

String
DODSFilter::get_ce()
{
    return ce;
}

String
DODSFilter::get_dataset_name()
{
    return dataset;
}

String
DODSFilter::get_dataset_version()
{
    return "";
}

bool
DODSFilter::read_ancillary_das(DAS &das)
{
    String name = find_ancillary_file(dataset, "das", anc_dir, anc_file);
    FILE *in = fopen((const char *)name, "r");

    if (in) {
	int status = das.parse(in);
	fclose(in);

	if(!status) {
	    String msg = "Parse error in external file " + dataset + ".das";

	    // server error message
	    ErrMsgT(msg);

	    // client error message
	    set_mime_text(dods_error);
	    Error e(malformed_expr, msg);
	    e.print();

	    return false;
	}
    }

    return true;
}

bool
DODSFilter::read_ancillary_dds(DDS &dds)
{
    String name = find_ancillary_file(dataset, "dds", anc_dir, anc_file);
    FILE *in = fopen((const char *)name, "r");

    if (in) {
	int status = dds.parse(in);
	fclose(in);

	if(!status) {
	    String msg = "Parse error in external file " + dataset + ".dds";

	    // server error message
	    ErrMsgT(msg);

	    // client error message
	    set_mime_text(dods_error);
	    Error e(malformed_expr, msg);
	    e.print();

	    return false;
	}
    }

    return true;
}

static const char *emessage = \
"DODS internal server error. Please report this to the dataset maintainer, \
or to support@dods.gso.uri.edu.";

void
DODSFilter::print_usage()
{
    // Write a message to the WWW server error log file.
    ostrstream oss;
    oss << "Usage: " << program_name
	<< " [-c] [-v <cgi version>] [-e <ce>]"
	<< " [-d <ancillary file directory>] [-f <ancillary file name>]"
	<< " <dataset>";
    ErrMsgT(oss.str());
    oss.freeze(0);

    // Build an error object to return to the user.
    Error e(unknown_error, emessage);
    set_mime_text(dods_error);
    e.print();
}

void
DODSFilter::send_version_info()
{
    cout << "HTTP/1.0 200 OK" << endl
	 << "Server: " << DVR << endl
	 << "Content-Type: text/plain" << endl
	 << endl;

    cout << "Core software version: " << DVR << endl;

    if (cgi_ver != "")
	cout << "Server Script Revision: " << cgi_ver << endl;

    String v = get_dataset_version();
    if (v != "")
	cout << "Dataset version: " << v << endl;
}

bool
DODSFilter::send_das(DAS &das)
{
    set_mime_text(dods_das);
    das.print();

    return true;
}

bool
DODSFilter::send_dds(DDS &dds, bool constrained)
{
    if (constrained) {
	if (!dds.parse_constraint(ce, cout, true)) {
	    String m = program_name + ": parse error in constraint: "
		+  ce;
	    ErrMsgT(m);

	    set_mime_text(dods_error);
	    Error e(unknown_error, m);
	    e.print();

	    return false;
	}
	set_mime_text(dods_dds);
	dds.print_constrained();  // send constrained DDS
    }
    else {
	set_mime_text(dods_dds);
	dds.print();
    }

    return true;
}

bool
DODSFilter::send_data(DDS &dds, FILE *data_stream)
{
    if (comp && deflate_exists()) {
	int childpid;
	FILE *data_sink = compressor(data_stream, childpid);
	if (!dds.send(dataset, ce, data_sink, true)) {
	    ErrMsgT("Could not send compressed data");
	    // DDS::send() sends the Error object.
	    return false;
	}
	fclose(data_sink);
	int pid;
	while ((pid = waitpid(childpid, 0, 0)) > 0) {
	    DBG(cerr << "pid: " << pid << endl);
	}
    }
    else {
	if (!dds.send(dataset, ce, data_stream, false)) {
	    ErrMsgT("Could not send data");
	    // DDS::send() sends the Error object.
	    return false;
	}
    }

    return true;
}

<commit_msg>Fixed calls to set_mime_*(). Removed the compression code (it is now in DDS::send(). Removed old code (that was surrounded by #if 0 ... #endif).<commit_after>
// (c) COPYRIGHT URI/MIT 1997
// Please read the full copyright statement in the file COPYRIGH.
//
// Authors:
//      jhrg,jimg       James Gallagher (jgallagher@gso.uri.edu)

// Implementation of the DODSFilter class. This class is used to build dods
// filter programs which, along with a CGI program, comprise DODS servers.
// jhrg 8/26/97

// $Log: DODSFilter.cc,v $
// Revision 1.3  1998/03/19 23:34:21  jimg
// Fixed calls to set_mime_*().
// Removed the compression code (it is now in DDS::send().
// Removed old code (that was surrounded by #if 0 ... #endif).
//
// Revision 1.2  1998/02/11 22:00:46  jimg
// Added call to util.cc:deflate_exists() to send_data(). This means that
// send_data() will only try to start the compressor if an executable copy of
// deflate can be found. If, for any reason a copy of deflate cannot be found
// data is sent without trying to compress it.
//
// Revision 1.1  1997/08/28 20:39:02  jimg
// Created
//

#ifdef __GNUG__
#pragma "implemenation"
#endif

#include "config_dap.h"

static char rcsid[] __unused__ = {"$Id: DODSFilter.cc,v 1.3 1998/03/19 23:34:21 jimg Exp $"};

#include <iostream.h>
#include <strstream.h>
#include <String.h>
#include <GetOpt.h>

#include "DAS.h"
#include "DDS.h"
#include "debug.h"
#include "cgi_util.h"
#include "DODSFilter.h"

DODSFilter::DODSFilter(int argc,char *argv[]) : comp(false), ver(false),
    bad_options(false), dataset(""), ce(""), cgi_ver(""),
    anc_dir(""), anc_file("")
{
    program_name = argv[0];

    int option_char;
    GetOpt getopt (argc, argv, "ce:v:d:f:");

    while ((option_char = getopt()) != EOF)
	switch (option_char) {
	  case 'c': comp = true; break;
	  case 'e': ce = getopt.optarg; break;
	  case 'v': ver = true; cgi_ver = getopt.optarg; break;
	  case 'd': anc_dir = getopt.optarg; break;
	  case 'f': anc_file = getopt.optarg; break;
	  default: bad_options = true; break;
	}

    int next_arg = getopt.optind;
    if(next_arg < argc)
	dataset = argv[next_arg];
    else
	bad_options = true;
}

DODSFilter::~DODSFilter()
{
}

bool
DODSFilter::OK()
{

    return !bad_options;
}

bool
DODSFilter::version()
{
    return ver;
}

String
DODSFilter::get_ce()
{
    return ce;
}

String
DODSFilter::get_dataset_name()
{
    return dataset;
}

String
DODSFilter::get_dataset_version()
{
    return "";
}

bool
DODSFilter::read_ancillary_das(DAS &das)
{
    String name = find_ancillary_file(dataset, "das", anc_dir, anc_file);
    FILE *in = fopen((const char *)name, "r");

    if (in) {
	int status = das.parse(in);
	fclose(in);

	if(!status) {
	    String msg = "Parse error in external file " + dataset + ".das";

	    // server error message
	    ErrMsgT(msg);

	    // client error message
	    set_mime_text(cout, dods_error);
	    Error e(malformed_expr, msg);
	    e.print(cout);

	    return false;
	}
    }

    return true;
}

bool
DODSFilter::read_ancillary_dds(DDS &dds)
{
    String name = find_ancillary_file(dataset, "dds", anc_dir, anc_file);
    FILE *in = fopen((const char *)name, "r");

    if (in) {
	int status = dds.parse(in);
	fclose(in);

	if(!status) {
	    String msg = "Parse error in external file " + dataset + ".dds";

	    // server error message
	    ErrMsgT(msg);

	    // client error message
	    set_mime_text(cout, dods_error);
	    Error e(malformed_expr, msg);
	    e.print(cout);

	    return false;
	}
    }

    return true;
}

static const char *emessage = \
"DODS internal server error. Please report this to the dataset maintainer, \
or to support@dods.gso.uri.edu.";

void
DODSFilter::print_usage()
{
    // Write a message to the WWW server error log file.
    ostrstream oss;
    oss << "Usage: " << program_name
	<< " [-c] [-v <cgi version>] [-e <ce>]"
	<< " [-d <ancillary file directory>] [-f <ancillary file name>]"
	<< " <dataset>";
    ErrMsgT(oss.str());
    oss.freeze(0);

    // Build an error object to return to the user.
    Error e(unknown_error, emessage);
    set_mime_text(cout, dods_error);
    e.print(cout);
}

void
DODSFilter::send_version_info()
{
    cout << "HTTP/1.0 200 OK" << endl
	 << "Server: " << DVR << endl
	 << "Content-Type: text/plain" << endl
	 << endl;

    cout << "Core software version: " << DVR << endl;

    if (cgi_ver != "")
	cout << "Server Script Revision: " << cgi_ver << endl;

    String v = get_dataset_version();
    if (v != "")
	cout << "Dataset version: " << v << endl;
}

bool
DODSFilter::send_das(DAS &das)
{
    set_mime_text(cout, dods_das);
    das.print(cout);

    return true;
}

bool
DODSFilter::send_dds(DDS &dds, bool constrained)
{
    if (constrained) {
	if (!dds.parse_constraint(ce, cout, true)) {
	    String m = program_name + ": parse error in constraint: "
		+  ce;
	    ErrMsgT(m);

	    set_mime_text(cout, dods_error);
	    Error e(unknown_error, m);
	    e.print(cout);

	    return false;
	}
	set_mime_text(cout, dods_dds);
	dds.print_constrained(cout);  // send constrained DDS
    }
    else {
	set_mime_text(cout, dods_dds);
	dds.print(cout);
    }

    return true;
}

bool
DODSFilter::send_data(DDS &dds, FILE *data_stream)
{
    bool compress = comp && deflate_exists();

    if (!dds.send(dataset, ce, data_stream, compress)) {
	ErrMsgT((compress) ? "Could not send compressed data" : "Could not send data");
	return false;
    }

    return true;
}

<|endoftext|>


<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s

/* Copyright (c) FFLAS-FFPACK
* Written by Clément Pernet <clement.pernet@imag.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the  GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
* ========LICENCE========
*/

#ifndef __FFLASFFPACK_HAVE_DGETRF
#define __FFLASFFPACK_HAVE_DGETRF 1
#endif
#include "fflas-ffpack/fflas-ffpack-config.h"

#include <iostream>
#include <vector>
#include <givaro/modular.h>

#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/fflas_io.h"
#include "fflas-ffpack/utils/args-parser.h"

using namespace std;

#ifdef __FFLASFFPACK_USE_OPENMP
typedef FFLAS::OMPTimer TTimer;
#else
typedef FFLAS::Timer TTimer;
#endif

#define EFFGFF(n,t,i) ( (double(n)/1000.*double(n)/1000.*double(n)/1000.0) / double(t) * double(i) / 3.)

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

	size_t iter = 3;
	int    q    = 1009;
	int    algo = 1;
	size_t    n    = 2000;
	std::string file = "";

	size_t NBK = MAX_THREADS;

	Argument as[] = {
		{ 'q', "-q Q", "Set the field characteristic (-1 for random).",  TYPE_INT , &q },
		{ 'n', "-n N", "Set the dimension of the matrix.",               TYPE_INT , &n },
		{ 'i', "-i R", "Set number of repetitions.",                     TYPE_INT , &iter },
		{ 'f', "-f FILE", "Set the input file (empty for random).",  TYPE_STR , &file },
		{ 'a', "-a Algorithm", "Set the algorithm (0 for default, 1 for Aasen, 2 for rook, 3 for rk.",  TYPE_INT , &algo },
		END_OF_ARGUMENTS
	};

	FFLAS::parseArguments(argc,argv,as);

    typedef Givaro::Modular<double> Field;
    typedef Field::Element Element;

    Field F(q);
    Field::Element * A;

    TTimer chrono;
    double *time=new double[iter];

    std::vector<int> Piv(n,0);
    std::vector<double> Diag(n,0.0);
    for (size_t it=0;it <= iter;++it){
        if (!file.empty()){
            FFLAS::ReadMatrix (file.c_str(),F,n,n,A);
        }
        else {
            A = FFLAS::fflas_new<Element>(n*n);
            Field::RandIter G(F);
            PAR_BLOCK{ FFLAS::pfrand(F,G,n,n,A,n/NBK); }
        }

        chrono.clear();
        switch(algo) {
            case 0:
                if (it) chrono.start();
                LAPACKE_dsytrf(101,'U',n,A,n,&Piv[0]);
                if (it) chrono.stop();
                break;
            case 1:
                if (it) chrono.start();
                LAPACKE_dsytrf_aa(101,'U',n,A,n,&Piv[0]);
                if (it) chrono.stop();
                break;
            case 2:
                if (it) chrono.start();
                LAPACKE_dsytrf_rook(101,'U',n,A,n,&Piv[0]);
                if (it) chrono.stop();
                break;
            default:
                if (it) chrono.start();
                LAPACKE_dsytrf_rk(101,'U',n,A,n,&Diag[0],&Piv[0]);
                if (it) chrono.stop();
        }
        if (it) time[it-1] = chrono.realtime();
        FFLAS::fflas_delete( A);
    }

    for(size_t i=0; i<iter; ++i)
        std::cerr << "time" << i << " : " << time[i] << std::endl;

    std::sort(time, time+iter);
    double mediantime = time[iter/2];
    delete[] time;

        // -----------
        // Standard output for benchmark - Alexis Breust 2014/11/14
    switch(algo) {
        case 0:
            std::cout << "DSYTRFtime: ";
            break;
        case 1:
            std::cout << "DSYTRFAAtime: ";
            break;
        case 2:
            std::cout << "DSYTRFROOKtime: ";
            break;
        default:
            std::cout << "DSYTRFRKtime: ";
    }

    std::cout << mediantime
              << " Gfops: " << EFFGFF(n,mediantime,1);
    FFLAS::writeCommandString(std::cout, as) << std::endl;

    return 0;
}

<commit_msg>no stdcerr<commit_after>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s

/* Copyright (c) FFLAS-FFPACK
* Written by Clément Pernet <clement.pernet@imag.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the  GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
* ========LICENCE========
*/

#ifndef __FFLASFFPACK_HAVE_DGETRF
#define __FFLASFFPACK_HAVE_DGETRF 1
#endif
#include "fflas-ffpack/fflas-ffpack-config.h"

#include <iostream>
#include <vector>
#include <givaro/modular.h>

#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/fflas_io.h"
#include "fflas-ffpack/utils/args-parser.h"

using namespace std;

#ifdef __FFLASFFPACK_USE_OPENMP
typedef FFLAS::OMPTimer TTimer;
#else
typedef FFLAS::Timer TTimer;
#endif

#define EFFGFF(n,t,i) ( (double(n)/1000.*double(n)/1000.*double(n)/1000.0) / double(t) * double(i) / 3.)

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

	size_t iter = 3;
	int    q    = 1009;
	int    algo = 1;
	size_t    n    = 2000;
	std::string file = "";

	size_t NBK = MAX_THREADS;

	Argument as[] = {
		{ 'q', "-q Q", "Set the field characteristic (-1 for random).",  TYPE_INT , &q },
		{ 'n', "-n N", "Set the dimension of the matrix.",               TYPE_INT , &n },
		{ 'i', "-i R", "Set number of repetitions.",                     TYPE_INT , &iter },
		{ 'f', "-f FILE", "Set the input file (empty for random).",  TYPE_STR , &file },
		{ 'a', "-a Algorithm", "Set the algorithm (0 for default, 1 for Aasen, 2 for rook, 3 for rk.",  TYPE_INT , &algo },
		END_OF_ARGUMENTS
	};

	FFLAS::parseArguments(argc,argv,as);

    typedef Givaro::Modular<double> Field;
    typedef Field::Element Element;

    Field F(q);
    Field::Element * A;

    TTimer chrono;
    double *time=new double[iter];

    std::vector<int> Piv(n,0);
    std::vector<double> Diag(n,0.0);
    for (size_t it=0;it <= iter;++it){
        if (!file.empty()){
            FFLAS::ReadMatrix (file.c_str(),F,n,n,A);
        }
        else {
            A = FFLAS::fflas_new<Element>(n*n);
            Field::RandIter G(F);
            PAR_BLOCK{ FFLAS::pfrand(F,G,n,n,A,n/NBK); }
        }

        chrono.clear();
        switch(algo) {
            case 0:
                if (it) chrono.start();
                LAPACKE_dsytrf(101,'U',n,A,n,&Piv[0]);
                if (it) chrono.stop();
                break;
            case 1:
                if (it) chrono.start();
                LAPACKE_dsytrf_aa(101,'U',n,A,n,&Piv[0]);
                if (it) chrono.stop();
                break;
            case 2:
                if (it) chrono.start();
                LAPACKE_dsytrf_rook(101,'U',n,A,n,&Piv[0]);
                if (it) chrono.stop();
                break;
            default:
                if (it) chrono.start();
                LAPACKE_dsytrf_rk(101,'U',n,A,n,&Diag[0],&Piv[0]);
                if (it) chrono.stop();
        }
        if (it) time[it-1] = chrono.realtime();
        FFLAS::fflas_delete( A);
    }

    std::sort(time, time+iter);
    double mediantime = time[iter/2];
    delete[] time;

        // -----------
        // Standard output for benchmark - Alexis Breust 2014/11/14
    switch(algo) {
        case 0:
            std::cout << "DSYTRFtime: ";
            break;
        case 1:
            std::cout << "DSYTRFAAtime: ";
            break;
        case 2:
            std::cout << "DSYTRFROOKtime: ";
            break;
        default:
            std::cout << "DSYTRFRKtime: ";
    }

    std::cout << mediantime
              << " Gfops: " << EFFGFF(n,mediantime,1);
    FFLAS::writeCommandString(std::cout, as) << std::endl;

    return 0;
}

<|endoftext|>