<commit_before>/*
 * predixy - A high performance and full features proxy for redis.
 * Copyright (C) 2017 Joyield, Inc. <joyield.com@gmail.com>
 * All rights reserved.
 */

#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <stdlib.h>
#include <sys/types.h>
#include <iostream>
#include <thread>
#include "Proxy.h"
#include "Handler.h"
#include "Socket.h"
#include "Alloc.h"
#include "ListenSocket.h"
#include "AcceptSocket.h"
#include "RequestParser.h"
#include "Backtrace.h"

static bool Running = false;
static bool Abort = false;
static bool Stop = false;

static void abortHandler(int sig)
{
    Abort = true;
    if (sig == SIGABRT) {
        traceInfo();
    }
    if (!Running) {
        abort();
    }
}

static void stopHandler(int sig)
{
    Stop = true;
    if (!Running) {
        abort();
    }
}

Proxy::Proxy():
    mListener(nullptr),
    mDataCenter(nullptr),
    mServPool(nullptr),
    mStartTime(time(nullptr)),
    mStatsVer(0)
{
}

Proxy::~Proxy()
{
    for (auto h : mHandlers) {
        delete h;
    }
    delete mServPool;
    delete mDataCenter;
    delete mListener;
    delete mConf;
}

bool Proxy::init(int argc, char* argv[])
{
    signal(SIGPIPE, SIG_IGN);
    signal(SIGFPE, abortHandler);
    signal(SIGILL, abortHandler);
    signal(SIGSEGV, abortHandler);
    signal(SIGABRT, abortHandler);
    signal(SIGBUS, abortHandler);
    signal(SIGQUIT, abortHandler);
    signal(SIGHUP, abortHandler);
    signal(SIGINT, stopHandler);
    signal(SIGTERM, stopHandler);

    Command::init();
    mConf = new Conf();
    if (!mConf->init(argc, argv)) {
        return false;
    }
    Logger::gInst = new Logger();
    Logger::gInst->setLogFile(mConf->log(), mConf->logRotateSecs(), mConf->logRotateBytes());
    Logger::gInst->setAllowMissLog(mConf->allowMissLog());
    for (int i = 0; i < LogLevel::Sentinel; ++i) {
        LogLevel::Type lvl = LogLevel::Type(i);
        Logger::gInst->setLogSample(lvl, mConf->logSample(lvl));
    }
    Logger::gInst->start();
    for (auto& ac : mConf->authConfs()) {
        mAuthority.add(ac);
    }
    if (!mConf->localDC().empty()) {
        mDataCenter = new DataCenter();
        mDataCenter->init(mConf);
    }
    AllocBase::setMaxMemory(mConf->maxMemory());
    if (mConf->bufSize() > 0) {
        Buffer::setSize(mConf->bufSize());
    }

    mLatencyMonitorSet.init(mConf->latencyMonitors());
    ListenSocket* s = new ListenSocket(mConf->bind(), SOCK_STREAM);
    if (!s->setNonBlock()) {
        logError("proxy listener set nonblock fail:%s", StrError());
        Throw(InitFail, "listener set nonblock", StrError());
    }
    s->listen();
    mListener = s;
    logNotice("predixy listen in %s", mConf->bind());
    switch (mConf->serverPoolType()) {
    case ServerPool::Cluster:
        {
            ClusterServerPool* p = new ClusterServerPool(this);
            p->init(mConf->clusterServerPool());
            mServPool = p;
        }
        break;
    case ServerPool::Sentinel:
        {
            SentinelServerPool* p = new SentinelServerPool(this);
            p->init(mConf->sentinelServerPool());
            mServPool = p;
        }
        break;
    default:
        Throw(InitFail, "unknown server pool type");
        break;
    }
    for (int i = 0; i < mConf->workerThreads(); ++i) {
        Handler* h = new Handler(this);
        mHandlers.push_back(h);
    }
    return true;
}

int Proxy::run()
{
    logNotice("predixy running with Name:%s Workers:%d",
            mConf->name(),
            (int)mHandlers.size());
    std::vector<std::shared_ptr<std::thread>> tasks;
    for (auto h : mHandlers) {
        std::shared_ptr<std::thread> t(new std::thread([=](){h->run();}));
        tasks.push_back(t);
    }
    Running = true;
    bool stop = false;
    while (!stop) {
        if (Abort) {
            stop = true;
            abort();
        } else if (Stop) {
            fprintf(stderr, "predixy will quit ASAP Bye!\n");
            stop = true;
        }
        if (!stop) {
            sleep(1);
            TimerPoint::report();
        }
    }
    for (auto h : mHandlers) {
        h->stop();
    }
    for (auto t : tasks) {
        t->join();
    }
    Logger::gInst->stop();
    TimerPoint::report();
    if (*mConf->bind() == '/') {
        unlink(mConf->bind());
    }
    return 0;
}

<commit_msg>fix backtrace bug<commit_after>/*
 * predixy - A high performance and full features proxy for redis.
 * Copyright (C) 2017 Joyield, Inc. <joyield.com@gmail.com>
 * All rights reserved.
 */

#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <stdlib.h>
#include <sys/types.h>
#include <iostream>
#include <thread>
#include "Proxy.h"
#include "Handler.h"
#include "Socket.h"
#include "Alloc.h"
#include "ListenSocket.h"
#include "AcceptSocket.h"
#include "RequestParser.h"
#include "Backtrace.h"

static bool Running = false;
static bool Abort = false;
static bool Stop = false;

static void abortHandler(int sig)
{
    if (!Abort) {
        traceInfo();
    }
    Abort = true;
    if (!Running) {
        abort();
    }
}

static void stopHandler(int sig)
{
    Stop = true;
    if (!Running) {
        abort();
    }
}

Proxy::Proxy():
    mListener(nullptr),
    mDataCenter(nullptr),
    mServPool(nullptr),
    mStartTime(time(nullptr)),
    mStatsVer(0)
{
}

Proxy::~Proxy()
{
    for (auto h : mHandlers) {
        delete h;
    }
    delete mServPool;
    delete mDataCenter;
    delete mListener;
    delete mConf;
}

bool Proxy::init(int argc, char* argv[])
{
    signal(SIGPIPE, SIG_IGN);
    signal(SIGFPE, abortHandler);
    signal(SIGILL, abortHandler);
    signal(SIGSEGV, abortHandler);
    signal(SIGABRT, abortHandler);
    signal(SIGBUS, abortHandler);
    signal(SIGQUIT, abortHandler);
    signal(SIGHUP, abortHandler);
    signal(SIGINT, stopHandler);
    signal(SIGTERM, stopHandler);

    Command::init();
    mConf = new Conf();
    if (!mConf->init(argc, argv)) {
        return false;
    }
    Logger::gInst = new Logger();
    Logger::gInst->setLogFile(mConf->log(), mConf->logRotateSecs(), mConf->logRotateBytes());
    Logger::gInst->setAllowMissLog(mConf->allowMissLog());
    for (int i = 0; i < LogLevel::Sentinel; ++i) {
        LogLevel::Type lvl = LogLevel::Type(i);
        Logger::gInst->setLogSample(lvl, mConf->logSample(lvl));
    }
    Logger::gInst->start();
    for (auto& ac : mConf->authConfs()) {
        mAuthority.add(ac);
    }
    if (!mConf->localDC().empty()) {
        mDataCenter = new DataCenter();
        mDataCenter->init(mConf);
    }
    AllocBase::setMaxMemory(mConf->maxMemory());
    if (mConf->bufSize() > 0) {
        Buffer::setSize(mConf->bufSize());
    }

    mLatencyMonitorSet.init(mConf->latencyMonitors());
    ListenSocket* s = new ListenSocket(mConf->bind(), SOCK_STREAM);
    if (!s->setNonBlock()) {
        logError("proxy listener set nonblock fail:%s", StrError());
        Throw(InitFail, "listener set nonblock", StrError());
    }
    s->listen();
    mListener = s;
    logNotice("predixy listen in %s", mConf->bind());
    switch (mConf->serverPoolType()) {
    case ServerPool::Cluster:
        {
            ClusterServerPool* p = new ClusterServerPool(this);
            p->init(mConf->clusterServerPool());
            mServPool = p;
        }
        break;
    case ServerPool::Sentinel:
        {
            SentinelServerPool* p = new SentinelServerPool(this);
            p->init(mConf->sentinelServerPool());
            mServPool = p;
        }
        break;
    default:
        Throw(InitFail, "unknown server pool type");
        break;
    }
    for (int i = 0; i < mConf->workerThreads(); ++i) {
        Handler* h = new Handler(this);
        mHandlers.push_back(h);
    }
    return true;
}

int Proxy::run()
{
    logNotice("predixy running with Name:%s Workers:%d",
            mConf->name(),
            (int)mHandlers.size());
    std::vector<std::shared_ptr<std::thread>> tasks;
    for (auto h : mHandlers) {
        std::shared_ptr<std::thread> t(new std::thread([=](){h->run();}));
        tasks.push_back(t);
    }
    Running = true;
    bool stop = false;
    while (!stop) {
        if (Abort) {
            stop = true;
            abort();
        } else if (Stop) {
            fprintf(stderr, "predixy will quit ASAP Bye!\n");
            stop = true;
        }
        if (!stop) {
            sleep(1);
            TimerPoint::report();
        }
    }
    for (auto h : mHandlers) {
        h->stop();
    }
    for (auto t : tasks) {
        t->join();
    }
    Logger::gInst->stop();
    TimerPoint::report();
    if (*mConf->bind() == '/') {
        unlink(mConf->bind());
    }
    return 0;
}

<|endoftext|>


<commit_before>#include <iostream>

#include "pbge/exceptions/exceptions.h"
#include "pbge/core/Manager.h"

#include "pbge/gfx/Buffer.h"
#include "pbge/gfx/Node.h"
#include "pbge/gfx/Model.h"
#include "pbge/gfx/Renderer.h"
#include "pbge/gfx/TextureRendererFactory.h"
#include "pbge/gfx/VBO.h"

#include <GL/glew.h>
#include <GL/glut.h>

pbge::Node * root, * child;
pbge::TransformationNode * cam_node;
pbge::OpenGL * ogl = new pbge::OpenGL;
pbge::Renderer renderer(ogl);
pbge::SceneManager manager;

pbge::Camera camera;

pbge::OpenGL * gl;

class UmModelo : public pbge::Model {
public:
    UmModelo(pbge::VertexBuffer * _vbo, GLenum _primitive) {
        vbo = _vbo;
        primitive = _primitive;
    }

    void render(pbge::ModelInstance * instance, pbge::OpenGL * ogl) {
        glEnable(GL_VERTEX_ARRAY);
        vbo->bind(ogl);
        glDrawArrays(primitive, 0, vbo->getNVertices());
        vbo->unbind(ogl);
        glDisable(GL_VERTEX_ARRAY);
    }

private:
    GLenum primitive;
    pbge::VertexBuffer * vbo;
};

pbge::ModelInstance * vboModel = NULL;

void display() {
    glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
    renderer.render();
    GLenum error;
    while((error = glGetError()) != GL_NO_ERROR) {
        std::cout << gluErrorString(error) << std::endl;
    }
    glutSwapBuffers();
}

void createNormalIndexes(std::vector<unsigned short> & ni) {
    unsigned short indexes[] = {3,3,3,3, 5,5,5,5, 0,0,0,0, 2,2,2,2, 1,1,1,1, 4,4,4,4};
    ni = std::vector<unsigned short>(indexes, indexes + 24);
}

std::vector<unsigned short> make(unsigned short * p, int n) {
    return std::vector<unsigned short>(p, p + n);
}

void createVertexIndexes(std::vector<unsigned short> & vi) {
    unsigned short indexes[] = {0,1,2,3, 7,4,1,0, 6,5,4,7, 3,2,5,6, 5,2,1,4, 0,3,6,7};
    vi = std::vector<unsigned short>(indexes, indexes + 24);
}

void createVBOInstance() {
    float v = 0.5f;
    std::vector<unsigned short> vIndexes;
    std::vector<unsigned short> nIndexes;
    createNormalIndexes(nIndexes);
    createVertexIndexes(vIndexes);
    pbge::VertexBufferBuilder builder(24);
    pbge::VertexAttribBuilder vertex = builder.addAttrib(3, pbge::VertexAttrib::VERTEX);
    pbge::VertexAttribBuilder normal = builder.addAttrib(3, pbge::VertexAttrib::NORMAL);

    builder.pushValue(normal,1,0,0).pushValue(normal,0,1,0).pushValue(normal,0,0,1).pushValue(normal,-1,0,0).pushValue(normal,0,-1,0).pushValue(normal,0,0,-1);
    builder.pushValue(vertex,-v,-v,-v).pushValue(vertex,-v,v,-v).pushValue(vertex,-v,v,v).pushValue(vertex,-v,-v,v);
    builder.pushValue(vertex,v,v,-v).pushValue(vertex,v,v,v).pushValue(vertex,v,-v,v).pushValue(vertex,v,-v,-v);
    builder.setAttribIndex(normal, nIndexes).setAttribIndex(vertex, vIndexes);
    pbge::VertexBuffer * vbo = builder.done();
    vboModel = new pbge::ModelInstance(new UmModelo(vbo, GL_QUADS));
}

void setUp() {
    glewInit();
    glEnable(GL_DEPTH_TEST);
    glClearColor(0,0,0,0);
    glColor3f(1,0,0);

    createVBOInstance();
    pbge::TransformationNode * node = new pbge::TransformationNode;

    math3d::matrix44 m = math3d::identity44;
    root = new pbge::TransformationNode;
    cam_node = new pbge::TransformationNode;

    child = node;
    node->setTransformationMatrix(&m);
    root->addChild(child);
    root->addChild(cam_node);
    child->addModelInstance(vboModel);

    math3d::matrix44 cam_matrix = math3d::identity44;
    cam_matrix[2][3] = 8.0f;
    cam_node->setTransformationMatrix(&cam_matrix);

    camera.setParent(cam_node);
    camera.lookAt(math3d::vector4(0,1,0), math3d::vector4(0,0,-1));
    camera.frustum.setPerspective(30, 1, 0.1f, 10);

    manager.setSceneGraph(root);
    manager.addCamera(&camera);

    renderer.setScene(&manager);
    gl = pbge::Manager::getInstance()->getOpenGL();

}

typedef unsigned short XXX;
int main(int argc, char ** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_DOUBLE);
    glutInitWindowSize(500,500);
    glutCreateWindow("ahahah");
    setUp();
    glutDisplayFunc(display);

    glutMainLoop();
    return 0;
}<commit_msg>refactoring main_tester<commit_after>#include <iostream>

#include "pbge/exceptions/exceptions.h"
#include "pbge/core/Manager.h"
#include "pbge/gfx/Buffer.h"
#include "pbge/gfx/Node.h"
#include "pbge/gfx/Model.h"
#include "pbge/gfx/Renderer.h"
#include "pbge/gfx/VBO.h"

#include <GL/glew.h>
#include <GL/glut.h>

pbge::Node * root, * child;
pbge::TransformationNode * cam_node;
pbge::Renderer * renderer;
pbge::SceneManager manager;
pbge::Camera camera;

class UmModelo : public pbge::Model {
public:
    UmModelo(pbge::VertexBuffer * _vbo, GLenum _primitive) {
        vbo = _vbo;
        primitive = _primitive;
    }

    void render(pbge::ModelInstance * instance, pbge::OpenGL * ogl) {
        glEnable(GL_VERTEX_ARRAY);
        vbo->bind(ogl);
        glDrawArrays(primitive, 0, vbo->getNVertices());
        vbo->unbind(ogl);
        glDisable(GL_VERTEX_ARRAY);
    }

private:
    GLenum primitive;
    pbge::VertexBuffer * vbo;
};

pbge::ModelInstance * vboModel = NULL;

void display() {
    glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
    renderer->render();
    GLenum error;
    while((error = glGetError()) != GL_NO_ERROR) {
        std::cout << gluErrorString(error) << std::endl;
    }
    glutSwapBuffers();
}

void createNormalIndexes(std::vector<unsigned short> & ni) {
    unsigned short indexes[] = {3,3,3,3, 5,5,5,5, 0,0,0,0, 2,2,2,2, 1,1,1,1, 4,4,4,4};
    ni = std::vector<unsigned short>(indexes, indexes + 24);
}

std::vector<unsigned short> make(unsigned short * p, int n) {
    return std::vector<unsigned short>(p, p + n);
}

void createVertexIndexes(std::vector<unsigned short> & vi) {
    unsigned short indexes[] = {0,1,2,3, 7,4,1,0, 6,5,4,7, 3,2,5,6, 5,2,1,4, 0,3,6,7};
    vi = std::vector<unsigned short>(indexes, indexes + 24);
}

void createVBOInstance() {
    float v = 0.5f;
    std::vector<unsigned short> vIndexes;
    std::vector<unsigned short> nIndexes;
    createNormalIndexes(nIndexes);
    createVertexIndexes(vIndexes);
    pbge::VertexBufferBuilder builder(24);
    pbge::VertexAttribBuilder vertex = builder.addAttrib(3, pbge::VertexAttrib::VERTEX);
    pbge::VertexAttribBuilder normal = builder.addAttrib(3, pbge::VertexAttrib::NORMAL);

    builder.pushValue(normal,1,0,0).pushValue(normal,0,1,0).pushValue(normal,0,0,1).pushValue(normal,-1,0,0).pushValue(normal,0,-1,0).pushValue(normal,0,0,-1);
    builder.pushValue(vertex,-v,-v,-v).pushValue(vertex,-v,v,-v).pushValue(vertex,-v,v,v).pushValue(vertex,-v,-v,v);
    builder.pushValue(vertex,v,v,-v).pushValue(vertex,v,v,v).pushValue(vertex,v,-v,v).pushValue(vertex,v,-v,-v);
    builder.setAttribIndex(normal, nIndexes).setAttribIndex(vertex, vIndexes);
    pbge::VertexBuffer * vbo = builder.done();
    vboModel = new pbge::ModelInstance(new UmModelo(vbo, GL_QUADS));
}

void setUp() {
    glewInit();
    glEnable(GL_DEPTH_TEST);
    glClearColor(0,0,0,0);
    glColor3f(1,0,0);

    createVBOInstance();
    renderer = new pbge::Renderer(pbge::Manager::getInstance()->getOpenGL());
    pbge::TransformationNode * node = new pbge::TransformationNode;

    math3d::matrix44 m = math3d::identity44;
    root = new pbge::TransformationNode;
    cam_node = new pbge::TransformationNode;

    child = node;
    node->setTransformationMatrix(&m);
    root->addChild(child);
    root->addChild(cam_node);
    child->addModelInstance(vboModel);

    math3d::matrix44 cam_matrix = math3d::identity44;
    cam_matrix[2][3] = 8.0f;
    cam_node->setTransformationMatrix(&cam_matrix);

    camera.setParent(cam_node);
    camera.lookAt(math3d::vector4(0,1,0), math3d::vector4(0,0,-1));
    camera.frustum.setPerspective(30, 1, 0.1f, 10);

    manager.setSceneGraph(root);
    manager.addCamera(&camera);
    renderer->setScene(&manager);
}

int main(int argc, char ** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_DOUBLE);
    glutInitWindowSize(500,500);
    glutCreateWindow("ahahah");
    setUp();
    glutDisplayFunc(display);
    glutMainLoop();
    return 0;
}<|endoftext|>


<commit_before>#include <Subsystems/ElevatorAutomatic.hpp>
#include "Robot.hpp"
#include <cmath>
#include "DriverStation.h"
#include <iostream>
#include <iomanip>

Robot::Robot() : settings("/home/lvuser/RobotSettings.txt"),
                 drive1Buttons(0),
                 drive2Buttons(1),
                 elevatorButtons(2),
                 dsDisplay(DSDisplay::getInstance(
                               settings.getInt("DS_Port"))),
                 insight(Insight::getInstance(settings.getInt("Insight_Port"))),
                 pidGraph(3513) {
    robotDrive = std::make_unique<DriveTrain>();

    driveStick1 = std::make_unique<Joystick>(0);
    driveStick2 = std::make_unique<Joystick>(1);
    shootStick = std::make_unique<Joystick>(2);
    autonTimer = std::make_unique<Timer>();
    displayTimer = std::make_unique<Timer>();
    ev = std::make_unique<ElevatorAutomatic>();

    dsDisplay.addAutonMethod("MotionProfile",
                             &Robot::AutonMotionProfile,
                             this);
    dsDisplay.addAutonMethod("Noop Auton", &Robot::NoopAuton, this);

    pidGraph.setSendInterval(10);

    displayTimer->Start();
}

Robot::~Robot() {
}

void Robot::OperatorControl() {
    robotDrive->reloadPID();
    ev->reloadPID();

    while (IsEnabled() && IsOperatorControl()) {
        if (driveStick2->GetRawButton(2)) {
            robotDrive->drive(driveStick1->GetY(), driveStick2->GetX(),
                              true);
        }
        else {
            robotDrive->drive(driveStick1->GetY(), driveStick2->GetX());
        }

        // Manual state machine
        if (elevatorButtons.releasedButton(2)) {
            ev->setManualMode(!ev->isManualMode());
        }

        // Automatic preset buttons (7-12)
        if (elevatorButtons.releasedButton(7)) {
            ev->raiseElevator(0);
        }
        if (elevatorButtons.releasedButton(8)) {
            ev->raiseElevator(1);
        }
        if (elevatorButtons.releasedButton(9)) {
            ev->raiseElevator(2);
        }
        if (elevatorButtons.releasedButton(10)) {
            ev->raiseElevator(3);
        }
        if (elevatorButtons.releasedButton(11)) {
            ev->raiseElevator(4);
        }
        if (elevatorButtons.releasedButton(12)) {
            ev->raiseElevator(5);
        }

        // Set manual value
        ev->setManualLiftSpeed(shootStick->GetY());

        if (elevatorButtons.releasedButton(1)) {
            ev->elevatorGrab(!ev->getElevatorGrab());
        }
        if (elevatorButtons.releasedButton(5)) {
            ev->intakeGrab(!ev->getIntakeGrab());
        }
        if (elevatorButtons.releasedButton(6)) {
            ev->stowIntake(!ev->isIntakeStowed());
        }

        if (shootStick->GetPOV() == 180) {
            ev->setIntakeDirection(Elevator::S_FORWARD);
        }
        else if (shootStick->GetPOV() == 0) {
            ev->setIntakeDirection(Elevator::S_REVERSED);
        }
        else {
            ev->setIntakeDirection(Elevator::S_STOPPED);
        }

        if (drive2Buttons.releasedButton(12)) {
            ev->resetEncoder();
        }

        // Opens intake if the elevator is at the same level as it
        if (ev->getHeight() < 11 && !ev->isManualMode() &&
            ev->getIntakeGrab()) {
            ev->intakeGrab(false);
        }

        drive1Buttons.updateButtons();
        drive2Buttons.updateButtons();
        elevatorButtons.updateButtons();

        DS_PrintOut();

        Wait(0.01);
    }
}

void Robot::Autonomous() {
    autonTimer->Reset();
    autonTimer->Start();

    dsDisplay.execAutonomous();

    autonTimer->Stop();
}

void Robot::Disabled() {
    while (IsDisabled()) {
        DS_PrintOut();
        Wait(0.1);
    }
}

void Robot::DS_PrintOut() {
    if (pidGraph.hasIntervalPassed()) {
        pidGraph.graphData(ev->getHeight(), "Distance (EV)");
        pidGraph.graphData(ev->getSetpoint(), "Setpoint (EV)");

        pidGraph.resetInterval();
    }
    if (pidGraph.hasIntervalPassed()) {
        pidGraph.graphData(ev->getHeight(), "Distance (EV)");
        pidGraph.graphData(ev->getSetpoint(), "Setpoint (EV)");

        pidGraph.resetInterval();
    }

    if (displayTimer->HasPeriodPassed(0.5)) {
        dsDisplay.clear();

        dsDisplay.addData("EV_LEVEL_INCHES", ev->getHeight());
        dsDisplay.addData("INTAKE_ARMS_CLOSED", ev->getIntakeGrab());
        dsDisplay.addData("ARMS_CLOSED", ev->getElevatorGrab());
        dsDisplay.addData("ENCODER_LEFT", robotDrive->getLeftDist());
        dsDisplay.addData("ENCODER_RIGHT", robotDrive->getRightDist());
        std::cout << std::setw(40) << "EV_LEVEL_INCHES=" << ev->getHeight()
                  << "INTAKE_ARMS_CLOSED" << ev->getIntakeGrab()
                  << "ARMS_CLOSED" << ev->getElevatorGrab() << std::endl;

        std::string name("EL_LEVEL_");
        for (int i = 0; i < 6; i++) {
            std::string name("EL_LEVEL_");

            if (ev->getHeight() == ev->getLevel(i) && ev->onTarget()) {
                dsDisplay.addData(name + std::to_string(i), DSDisplay::active);
            }
            else if (ev->getHeight() < ev->getLevel(i + 1)) {
                dsDisplay.addData(name + std::to_string(i), DSDisplay::standby);
                dsDisplay.addData(name + std::to_string(
                                      i + 1), DSDisplay::standby);
            }
            else {
                dsDisplay.addData(name + std::to_string(i),
                                  DSDisplay::inactive);
            }
        }
        dsDisplay.sendToDS();
    }

    dsDisplay.receiveFromDS();
    insight.receiveFromDS();
}

START_ROBOT_CLASS(Robot);

<commit_msg>Reverted accidental duplication of graph data sending code<commit_after>#include <Subsystems/ElevatorAutomatic.hpp>
#include "Robot.hpp"
#include <cmath>
#include "DriverStation.h"
#include <iostream>
#include <iomanip>

Robot::Robot() : settings("/home/lvuser/RobotSettings.txt"),
                 drive1Buttons(0),
                 drive2Buttons(1),
                 elevatorButtons(2),
                 dsDisplay(DSDisplay::getInstance(
                               settings.getInt("DS_Port"))),
                 insight(Insight::getInstance(settings.getInt("Insight_Port"))),
                 pidGraph(3513) {
    robotDrive = std::make_unique<DriveTrain>();

    driveStick1 = std::make_unique<Joystick>(0);
    driveStick2 = std::make_unique<Joystick>(1);
    shootStick = std::make_unique<Joystick>(2);
    autonTimer = std::make_unique<Timer>();
    displayTimer = std::make_unique<Timer>();
    ev = std::make_unique<ElevatorAutomatic>();

    dsDisplay.addAutonMethod("MotionProfile",
                             &Robot::AutonMotionProfile,
                             this);
    dsDisplay.addAutonMethod("Noop Auton", &Robot::NoopAuton, this);

    pidGraph.setSendInterval(10);

    displayTimer->Start();
}

Robot::~Robot() {
}

void Robot::OperatorControl() {
    robotDrive->reloadPID();
    ev->reloadPID();

    while (IsEnabled() && IsOperatorControl()) {
        if (driveStick2->GetRawButton(2)) {
            robotDrive->drive(driveStick1->GetY(), driveStick2->GetX(),
                              true);
        }
        else {
            robotDrive->drive(driveStick1->GetY(), driveStick2->GetX());
        }

        // Manual state machine
        if (elevatorButtons.releasedButton(2)) {
            ev->setManualMode(!ev->isManualMode());
        }

        // Automatic preset buttons (7-12)
        if (elevatorButtons.releasedButton(7)) {
            ev->raiseElevator(0);
        }
        if (elevatorButtons.releasedButton(8)) {
            ev->raiseElevator(1);
        }
        if (elevatorButtons.releasedButton(9)) {
            ev->raiseElevator(2);
        }
        if (elevatorButtons.releasedButton(10)) {
            ev->raiseElevator(3);
        }
        if (elevatorButtons.releasedButton(11)) {
            ev->raiseElevator(4);
        }
        if (elevatorButtons.releasedButton(12)) {
            ev->raiseElevator(5);
        }

        // Set manual value
        ev->setManualLiftSpeed(shootStick->GetY());

        if (elevatorButtons.releasedButton(1)) {
            ev->elevatorGrab(!ev->getElevatorGrab());
        }
        if (elevatorButtons.releasedButton(5)) {
            ev->intakeGrab(!ev->getIntakeGrab());
        }
        if (elevatorButtons.releasedButton(6)) {
            ev->stowIntake(!ev->isIntakeStowed());
        }

        if (shootStick->GetPOV() == 180) {
            ev->setIntakeDirection(Elevator::S_FORWARD);
        }
        else if (shootStick->GetPOV() == 0) {
            ev->setIntakeDirection(Elevator::S_REVERSED);
        }
        else {
            ev->setIntakeDirection(Elevator::S_STOPPED);
        }

        if (drive2Buttons.releasedButton(12)) {
            ev->resetEncoder();
        }

        // Opens intake if the elevator is at the same level as it
        if (ev->getHeight() < 11 && !ev->isManualMode() &&
            ev->getIntakeGrab()) {
            ev->intakeGrab(false);
        }

        drive1Buttons.updateButtons();
        drive2Buttons.updateButtons();
        elevatorButtons.updateButtons();

        DS_PrintOut();

        Wait(0.01);
    }
}

void Robot::Autonomous() {
    autonTimer->Reset();
    autonTimer->Start();

    dsDisplay.execAutonomous();

    autonTimer->Stop();
}

void Robot::Disabled() {
    while (IsDisabled()) {
        DS_PrintOut();
        Wait(0.1);
    }
}

void Robot::DS_PrintOut() {
    if (pidGraph.hasIntervalPassed()) {
        pidGraph.graphData(ev->getHeight(), "Distance (EV)");
        pidGraph.graphData(ev->getSetpoint(), "Setpoint (EV)");

        pidGraph.resetInterval();
    }

    if (displayTimer->HasPeriodPassed(0.5)) {
        dsDisplay.clear();

        dsDisplay.addData("EV_LEVEL_INCHES", ev->getHeight());
        dsDisplay.addData("INTAKE_ARMS_CLOSED", ev->getIntakeGrab());
        dsDisplay.addData("ARMS_CLOSED", ev->getElevatorGrab());
        dsDisplay.addData("ENCODER_LEFT", robotDrive->getLeftDist());
        dsDisplay.addData("ENCODER_RIGHT", robotDrive->getRightDist());
        std::cout << std::setw(40) << "EV_LEVEL_INCHES=" << ev->getHeight()
                  << "INTAKE_ARMS_CLOSED" << ev->getIntakeGrab()
                  << "ARMS_CLOSED" << ev->getElevatorGrab() << std::endl;

        std::string name("EL_LEVEL_");
        for (int i = 0; i < 6; i++) {
            std::string name("EL_LEVEL_");

            if (ev->getHeight() == ev->getLevel(i) && ev->onTarget()) {
                dsDisplay.addData(name + std::to_string(i), DSDisplay::active);
            }
            else if (ev->getHeight() < ev->getLevel(i + 1)) {
                dsDisplay.addData(name + std::to_string(i), DSDisplay::standby);
                dsDisplay.addData(name + std::to_string(
                                      i + 1), DSDisplay::standby);
            }
            else {
                dsDisplay.addData(name + std::to_string(i),
                                  DSDisplay::inactive);
            }
        }
        dsDisplay.sendToDS();
    }

    dsDisplay.receiveFromDS();
    insight.receiveFromDS();
}

START_ROBOT_CLASS(Robot);

<|endoftext|>


<commit_before>#include <stddef.h>
#include <list>
#include "prelude.hpp"

namespace rubinius {
  class ObjectHeader;
  class InflatedHeader;
  class VM;

  /**
   * Manages a list of InflatedHeader instances.
   *
   * Storage for InflatedHeader objects are allocated in chunks, and these are
   * in turn stored in a linked list. As ObjectHeader instances are inflated,
   * they are added to the next free spot, or if no slots exist, a new chunk
   * is allocated.
   *
   * As InflatedHeader instances are deflated, they are added to free_list_,
   * which re-uses the storage of the InflatedHeader to link to the next free
   * InflatedHeader slot.
   */

  class InflatedHeaders {
  public:
    typedef std::list<InflatedHeader*> Chunks;

    /// Storage for InflatedHeader references is allocated in chunks.
    static const size_t cChunkSize = 1024;
    static const size_t cChunkLimit = 16;

  private:
    VM* state_;
    /// Linked list of InflatedHeader pointers.
    Chunks chunks_;
    /// Pointer to the first free InflatedHeader slot in the list.
    InflatedHeader* free_list_;
    /// Number of chunks allocated since last GC cycle
    size_t allocations_;
    /// Number of in-use slots
    int in_use_;

  public:
    InflatedHeaders(VM* state)
      : state_(state)
      , free_list_(0)
      , allocations_(0)
      , in_use_(0)
    {}

    ~InflatedHeaders();

    InflatedHeader* allocate(ObjectHeader* obj);
    void deallocate_headers(int mark);
    void allocate_chunk();
  };
}
<commit_msg>Change how often a full GC is triggered to improve CAPI perf<commit_after>#include <stddef.h>
#include <list>
#include "prelude.hpp"

namespace rubinius {
  class ObjectHeader;
  class InflatedHeader;
  class VM;

  /**
   * Manages a list of InflatedHeader instances.
   *
   * Storage for InflatedHeader objects are allocated in chunks, and these are
   * in turn stored in a linked list. As ObjectHeader instances are inflated,
   * they are added to the next free spot, or if no slots exist, a new chunk
   * is allocated.
   *
   * As InflatedHeader instances are deflated, they are added to free_list_,
   * which re-uses the storage of the InflatedHeader to link to the next free
   * InflatedHeader slot.
   */

  class InflatedHeaders {
  public:
    typedef std::list<InflatedHeader*> Chunks;

    /// Storage for InflatedHeader references is allocated in chunks.
    static const size_t cChunkSize = 1024;
    static const size_t cChunkLimit = 32;

  private:
    VM* state_;
    /// Linked list of InflatedHeader pointers.
    Chunks chunks_;
    /// Pointer to the first free InflatedHeader slot in the list.
    InflatedHeader* free_list_;
    /// Number of chunks allocated since last GC cycle
    size_t allocations_;
    /// Number of in-use slots
    int in_use_;

  public:
    InflatedHeaders(VM* state)
      : state_(state)
      , free_list_(0)
      , allocations_(0)
      , in_use_(0)
    {}

    ~InflatedHeaders();

    InflatedHeader* allocate(ObjectHeader* obj);
    void deallocate_headers(int mark);
    void allocate_chunk();
  };
}
<|endoftext|>


<commit_before>/*****************************************************************************
 * PokerTH - The open source texas holdem engine                             *
 * Copyright (C) 2006-2011 Felix Hammer, Florian Thauer, Lothar May          *
 *                                                                           *
 * This program is free software: you can redistribute it and/or modify      *
 * it under the terms of the GNU Affero General Public License as            *
 * published by the Free Software Foundation, either version 3 of the        *
 * License, or (at your option) any later version.                           *
 *                                                                           *
 * This program 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 Affero General Public License for more details.                       *
 *                                                                           *
 * You should have received a copy of the GNU Affero General Public License  *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.     *
 *****************************************************************************/

#include <net/netpacket.h>
#include "session.h"
#include "configfile.h"
#include <qttoolsinterface.h>
#include <gui/generic/serverguiwrapper.h>
#include <net/socket_startup.h>
#include <core/loghelper.h>
#include <core/thread.h>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>

#include <iostream>
#include <fstream>
#include <csignal>

#ifdef _MSC_VER
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>

#define ENABLE_LEAK_CHECK() \
			{ \
				int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); \
				tmpFlag |= _CRTDBG_LEAK_CHECK_DF; \
				_CrtSetDbgFlag(tmpFlag); \
			}
#endif
#endif

#ifndef ENABLE_LEAK_CHECK
#define ENABLE_LEAK_CHECK()
#endif

using namespace std;
namespace po = boost::program_options;
using namespace boost::filesystem;

volatile int g_pokerthTerminate = 0;

void
TerminateHandler(int /*signal*/)
{
	g_pokerthTerminate = 1;
}

// TODO: Hack
#ifdef _WIN32
#include <process.h>
#else
#include <unistd.h>
#ifndef daemon
int daemon(int, int);
#endif
#endif

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

	//_CrtSetBreakAlloc(10260);

	bool readonlyConfig = false;
	string pidFile;
	int logLevel = 1;
	{
		// Check command line options.
		po::options_description desc("Allowed options");
		desc.add_options()
		("help,h", "produce help message")
		("version,v", "print version string")
		("log-level,l", po::value<int>(), "set log level (0=minimal, 1=default, 2=verbose)")
		("pid-file,p", po::value<string>(), "create pid-file in different location")
		("readonly-config", "treat config file as read-only")
		;

		po::variables_map vm;
		po::store(po::parse_command_line(argc, argv, desc), vm);
		po::notify(vm);

		if (vm.count("help")) {
			cout << desc << endl;
			return 1;
		}
		if (vm.count("version")) {
			cout << "PokerTH server version   " << POKERTH_BETA_RELEASE_STRING << endl
				 << "Network protocol version " << NET_VERSION_MAJOR << "." << NET_VERSION_MINOR << endl;
			return 1;
		}
		if (vm.count("log-level")) {
			logLevel = vm["log-level"].as<int>();
			if (logLevel < 0 || logLevel > 2) {
				cout << "Invalid log-level: \"" << logLevel << "\", allowed range 0-2." << endl;
				return 1;
			}
		}
		if (vm.count("pid-file"))
			pidFile = vm["pid-file"].as<string>();
		if (vm.count("readonly-config"))
			readonlyConfig = true;
	}

	boost::shared_ptr<QtToolsInterface> myQtToolsInterface(CreateQtToolsWrapper());
	//create defaultconfig
	boost::shared_ptr<ConfigFile> myConfig(new ConfigFile(argv[0], readonlyConfig));
	loghelper_init(myQtToolsInterface->stringFromUtf8(myConfig->readConfigString("LogDir")), logLevel);

	// TODO: Hack
#ifndef _WIN32
	if (daemon(0, 0) != 0) {
		cout << "Failed to start daemon." << endl;
		return 1;
	}
#endif

	signal(SIGTERM, TerminateHandler);
	signal(SIGINT, TerminateHandler);

	socket_startup();

	LOG_MSG("Starting PokerTH dedicated server. Availability: IPv6 "
			<< socket_has_ipv6() << ", SCTP " << socket_has_sctp() << ", Dual Stack " << socket_has_dual_stack() << ".");

	// Store pid in file.
	if (pidFile.empty()) {
		path tmpPidPath(myConfig->readConfigString("LogDir"));
		tmpPidPath /= "pokerth.pid";
		pidFile = tmpPidPath.directory_string();
	}
	{
		ofstream pidStream(pidFile.c_str(), ios_base::out | ios_base::trunc);
		if (!pidStream.fail())
			pidStream << getpid();
		else
			LOG_ERROR("Could not create process id file \"" << pidFile << "\"!");
	}

	// Create pseudo Gui Wrapper for the server.
	boost::shared_ptr<GuiInterface> myServerGuiInterface(new ServerGuiWrapper(myConfig.get(), NULL, NULL, NULL));
	boost::shared_ptr<Session> session(new Session(myServerGuiInterface.get(), myConfig.get()));
	if (!session->init())
		LOG_ERROR("Missing files - please check your directory settings!");
	myServerGuiInterface->setSession(session);

	myServerGuiInterface->getSession()->startNetworkServer(true);
	while (!g_pokerthTerminate) {
		Thread::Msleep(100);
		if (myServerGuiInterface->getSession()->pollNetworkServerTerminated())
			g_pokerthTerminate = true;
	}
	myServerGuiInterface->getSession()->terminateNetworkServer();
	session.reset();
	myServerGuiInterface.reset();
	myConfig.reset();

	LOG_MSG("Terminating PokerTH dedicated server." << endl);
	socket_cleanup();
	return 0;
}

<commit_msg>Start daemon mode only in non-debug server.<commit_after>/*****************************************************************************
 * PokerTH - The open source texas holdem engine                             *
 * Copyright (C) 2006-2011 Felix Hammer, Florian Thauer, Lothar May          *
 *                                                                           *
 * This program is free software: you can redistribute it and/or modify      *
 * it under the terms of the GNU Affero General Public License as            *
 * published by the Free Software Foundation, either version 3 of the        *
 * License, or (at your option) any later version.                           *
 *                                                                           *
 * This program 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 Affero General Public License for more details.                       *
 *                                                                           *
 * You should have received a copy of the GNU Affero General Public License  *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.     *
 *****************************************************************************/

#include <net/netpacket.h>
#include "session.h"
#include "configfile.h"
#include <qttoolsinterface.h>
#include <gui/generic/serverguiwrapper.h>
#include <net/socket_startup.h>
#include <core/loghelper.h>
#include <core/thread.h>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>

#include <iostream>
#include <fstream>
#include <csignal>

#ifdef _MSC_VER
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>

#define ENABLE_LEAK_CHECK() \
			{ \
				int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); \
				tmpFlag |= _CRTDBG_LEAK_CHECK_DF; \
				_CrtSetDbgFlag(tmpFlag); \
			}
#endif
#endif

#ifndef ENABLE_LEAK_CHECK
#define ENABLE_LEAK_CHECK()
#endif

using namespace std;
namespace po = boost::program_options;
using namespace boost::filesystem;

volatile int g_pokerthTerminate = 0;

void
TerminateHandler(int /*signal*/)
{
	g_pokerthTerminate = 1;
}

// TODO: Hack
#ifdef _WIN32
#include <process.h>
#else
#include <unistd.h>
#ifndef daemon
int daemon(int, int);
#endif
#endif

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

	//_CrtSetBreakAlloc(10260);

	bool readonlyConfig = false;
	string pidFile;
	int logLevel = 1;
	{
		// Check command line options.
		po::options_description desc("Allowed options");
		desc.add_options()
		("help,h", "produce help message")
		("version,v", "print version string")
		("log-level,l", po::value<int>(), "set log level (0=minimal, 1=default, 2=verbose)")
		("pid-file,p", po::value<string>(), "create pid-file in different location")
		("readonly-config", "treat config file as read-only")
		;

		po::variables_map vm;
		po::store(po::parse_command_line(argc, argv, desc), vm);
		po::notify(vm);

		if (vm.count("help")) {
			cout << desc << endl;
			return 1;
		}
		if (vm.count("version")) {
			cout << "PokerTH server version   " << POKERTH_BETA_RELEASE_STRING << endl
				 << "Network protocol version " << NET_VERSION_MAJOR << "." << NET_VERSION_MINOR << endl;
			return 1;
		}
		if (vm.count("log-level")) {
			logLevel = vm["log-level"].as<int>();
			if (logLevel < 0 || logLevel > 2) {
				cout << "Invalid log-level: \"" << logLevel << "\", allowed range 0-2." << endl;
				return 1;
			}
		}
		if (vm.count("pid-file"))
			pidFile = vm["pid-file"].as<string>();
		if (vm.count("readonly-config"))
			readonlyConfig = true;
	}

	boost::shared_ptr<QtToolsInterface> myQtToolsInterface(CreateQtToolsWrapper());
	//create defaultconfig
	boost::shared_ptr<ConfigFile> myConfig(new ConfigFile(argv[0], readonlyConfig));
	loghelper_init(myQtToolsInterface->stringFromUtf8(myConfig->readConfigString("LogDir")), logLevel);

	// TODO: Hack
#ifndef _WIN32
#ifdef QT_NO_DEBUG
	if (daemon(0, 0) != 0) {
		cout << "Failed to start daemon." << endl;
		return 1;
	}
#endif
#endif

	signal(SIGTERM, TerminateHandler);
	signal(SIGINT, TerminateHandler);

	socket_startup();

	LOG_MSG("Starting PokerTH dedicated server. Availability: IPv6 "
			<< socket_has_ipv6() << ", SCTP " << socket_has_sctp() << ", Dual Stack " << socket_has_dual_stack() << ".");

	// Store pid in file.
	if (pidFile.empty()) {
		path tmpPidPath(myConfig->readConfigString("LogDir"));
		tmpPidPath /= "pokerth.pid";
		pidFile = tmpPidPath.directory_string();
	}
	{
		ofstream pidStream(pidFile.c_str(), ios_base::out | ios_base::trunc);
		if (!pidStream.fail())
			pidStream << getpid();
		else
			LOG_ERROR("Could not create process id file \"" << pidFile << "\"!");
	}

	// Create pseudo Gui Wrapper for the server.
	boost::shared_ptr<GuiInterface> myServerGuiInterface(new ServerGuiWrapper(myConfig.get(), NULL, NULL, NULL));
	boost::shared_ptr<Session> session(new Session(myServerGuiInterface.get(), myConfig.get()));
	if (!session->init())
		LOG_ERROR("Missing files - please check your directory settings!");
	myServerGuiInterface->setSession(session);

	myServerGuiInterface->getSession()->startNetworkServer(true);
	while (!g_pokerthTerminate) {
		Thread::Msleep(100);
		if (myServerGuiInterface->getSession()->pollNetworkServerTerminated())
			g_pokerthTerminate = true;
	}
	myServerGuiInterface->getSession()->terminateNetworkServer();
	session.reset();
	myServerGuiInterface.reset();
	myConfig.reset();

	LOG_MSG("Terminating PokerTH dedicated server." << endl);
	socket_cleanup();
	return 0;
}

<|endoftext|>


<commit_before>#include "FGame.hpp"

//Images were downloaded from opengameart.org

FGame::FGame(std::shared_ptr<FEngine> engine)
{
	m_engine = engine;
	auto level = engine->getLevel();

	m_width = level->getWidth();
	m_height = level->getHeight();
	m_tileSize = level->getTileSize();

	sf::RenderWindow *window = new sf::RenderWindow(
		sf::VideoMode(m_width * m_tileSize, m_height * m_tileSize),
		"FightR 2.0"
	);
	m_window = std::unique_ptr<sf::RenderWindow>(window);
}

std::shared_ptr<sf::Sprite> FGame::loadSprite(std::string fileName, int width, int height)
{
	auto exists = m_sprites.find(fileName);
	if (exists == m_sprites.end())
	{
		auto texture = std::make_shared<sf::Texture>();
		if (!texture->loadFromFile(fileName, sf::IntRect(0, 0, width, height)))
		{
			std::cout << "ERROR trying to load " << fileName;
		}
		auto sprite = std::make_shared<sf::Sprite>();
		sprite->setTexture(*texture);
		m_sprites[fileName] = sprite;
		m_textures[fileName] = texture;
		return sprite;
	}
	else
	{
		return exists->second;
	}
}

void FGame::run()
{
	sf::Clock clock;
	sf::Time accumulator = sf::Time::Zero;
	sf::Time ups = sf::seconds(1.f / 60.f);

	while (m_window->isOpen() && m_engine->isRunning())
	{
		processEvents();

		while (accumulator > ups)
		{
			accumulator -= ups;
			m_engine->tick(ups.asSeconds());
			m_engine->print();
		}

		render();
		accumulator += clock.restart();
	}
}

void FGame::processEvents()
{
	// Check events
	sf::Event event;
	while (m_window->pollEvent(event))
	{
		if (event.type == sf::Event::Closed)
			m_window->close();
	}

	// Check keyboard press
	auto &characters = m_engine->getCharacters();
	auto it = std::find_if(characters.begin(), characters.end(), [] (FCharacter& character) { return character.isHuman(); } );
	if (it != characters.end())
	{
		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
			it->move(FDirection::left);
		else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
			it->move(FDirection::right);

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
			it->move(FDirection::up);
		else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
			it->move(FDirection::down);

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
			it->fire();
	}
}

void FGame::render()
{
	m_window->clear();

	// Render all tiles
	for (int y = 0; y < m_height; y++)
	{
		for (int x = 0; x < m_width; x++)
		{
			auto data = m_engine->getLevel()->get(x, y);
			auto sprite = loadSprite(m_tileMap[data], m_tileSize, m_tileSize);
			sprite->setPosition(sf::Vector2f(x * m_tileSize, y * m_tileSize));
			m_window->draw(*sprite);
		}
	}

	// Render characters and their weapons
	for (auto &character : m_engine->getCharacters())
	{
		if (character.getHealth() > 0)
		{
			auto sprite = loadSprite(m_characterTypeMap[character.getType()], character.getSize().x, character.getSize().y);
			sprite->setPosition(sf::Vector2f(character.getPosition().x, character.getPosition().y));
			m_window->draw(*sprite);

			auto weapon = character.getWeapon();
			auto weaponSprite = loadSprite(m_weaponTypeMap[weapon.getType()], weapon.getSize().x, weapon.getSize().y);
			weaponSprite->setPosition(sf::Vector2f(character.getPosition().x + character.getSize().x / 2.f, character.getPosition().y + character.getSize().y / 2.f));
			m_window->draw(*weaponSprite);
		}
	}

	// Render projectiles
	for (auto &projectile : m_engine->getProjectiles())
	{
		auto sprite = loadSprite(m_projectileTypeMap[projectile.getType()], projectile.getSize().x, projectile.getSize().y);
		sprite->setPosition(sf::Vector2f(projectile.getPosition().x, projectile.getPosition().y));
		m_window->draw(*sprite);
	}

	// Render powerups
	for (auto &powerup : m_engine->getPowerups())
	{
		auto sprite = loadSprite(m_powerupTypeMap[powerup.getType()], powerup.getSize().x, powerup.getSize().y);
		sprite->setPosition(sf::Vector2f(powerup.getPosition().x, powerup.getPosition().y));
		m_window->draw(*sprite);
	}

	// Render effects
	//TODO

	m_window->display();
}

void FGame::setTile(FTile typeName, std::string filename)
{
	m_tileMap[typeName] = filename;
}

void FGame::setCharacterType(FCharacterType typeName, std::string filename)
{
	m_characterTypeMap[typeName] = filename;
}

void FGame::setWeaponType(FWeaponType typeName, std::string filename)
{
	m_weaponTypeMap[typeName] = filename;
}

void FGame::setProjectileType(FProjectileType typeName, std::string filename)
{
	m_projectileTypeMap[typeName] = filename;
}

void FGame::setPowerupType(FPowerupType typeName, std::string filename)
{
	m_powerupTypeMap[typeName] = filename;
}
<commit_msg>Added buttons for changing current weapon<commit_after>#include "FGame.hpp"

FGame::FGame(std::shared_ptr<FEngine> engine)
{
	m_engine = engine;
	auto level = engine->getLevel();

	m_width = level->getWidth();
	m_height = level->getHeight();
	m_tileSize = level->getTileSize();

	sf::RenderWindow *window = new sf::RenderWindow(
		sf::VideoMode(m_width * m_tileSize, m_height * m_tileSize),
		"FightR 2.0"
	);
	m_window = std::unique_ptr<sf::RenderWindow>(window);
}

std::shared_ptr<sf::Sprite> FGame::loadSprite(std::string fileName, int width, int height)
{
	auto exists = m_sprites.find(fileName);
	if (exists == m_sprites.end())
	{
		auto texture = std::make_shared<sf::Texture>();
		if (!texture->loadFromFile(fileName, sf::IntRect(0, 0, width, height)))
		{
			std::cout << "ERROR trying to load " << fileName;
		}
		auto sprite = std::make_shared<sf::Sprite>();
		sprite->setTexture(*texture);
		m_sprites[fileName] = sprite;
		m_textures[fileName] = texture;
		return sprite;
	}
	else
	{
		return exists->second;
	}
}

void FGame::run()
{
	sf::Clock clock;
	sf::Time accumulator = sf::Time::Zero;
	sf::Time ups = sf::seconds(1.f / 60.f);

	while (m_window->isOpen() && m_engine->isRunning())
	{
		processEvents();

		while (accumulator > ups)
		{
			accumulator -= ups;
			m_engine->tick(ups.asSeconds());
			m_engine->print();
		}

		render();
		accumulator += clock.restart();
	}
}

void FGame::processEvents()
{
	// Check events
	sf::Event event;
	while (m_window->pollEvent(event))
	{
		if (event.type == sf::Event::Closed)
			m_window->close();
	}

	// Check keyboard press
	auto &characters = m_engine->getCharacters();
	auto it = std::find_if(characters.begin(), characters.end(), [] (FCharacter& character) { return character.isHuman(); } );
	if (it != characters.end())
	{
		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
			it->move(FDirection::left);
		else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
			it->move(FDirection::right);

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
			it->move(FDirection::up);
		else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
			it->move(FDirection::down);

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Z))
			it->setWeaponIndex(it->getWeaponIndex() - 1);
		else if (sf::Keyboard::isKeyPressed(sf::Keyboard::X))
			it->setWeaponIndex(it->getWeaponIndex() + 1);

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
			it->fire();
	}
}

void FGame::render()
{
	m_window->clear();

	// Render all tiles
	for (int y = 0; y < m_height; y++)
	{
		for (int x = 0; x < m_width; x++)
		{
			auto data = m_engine->getLevel()->get(x, y);
			auto sprite = loadSprite(m_tileMap[data], m_tileSize, m_tileSize);
			sprite->setPosition(sf::Vector2f(x * m_tileSize, y * m_tileSize));
			m_window->draw(*sprite);
		}
	}

	// Render characters and their weapons
	for (auto &character : m_engine->getCharacters())
	{
		if (character.getHealth() > 0)
		{
			auto sprite = loadSprite(m_characterTypeMap[character.getType()], character.getSize().x, character.getSize().y);
			sprite->setPosition(sf::Vector2f(character.getPosition().x, character.getPosition().y));
			m_window->draw(*sprite);

			auto weapon = character.getWeapon();
			auto weaponSprite = loadSprite(m_weaponTypeMap[weapon.getType()], weapon.getSize().x, weapon.getSize().y);
			weaponSprite->setPosition(sf::Vector2f(character.getPosition().x + character.getSize().x / 2.f, character.getPosition().y + character.getSize().y / 2.f));
			m_window->draw(*weaponSprite);
		}
	}

	// Render projectiles
	for (auto &projectile : m_engine->getProjectiles())
	{
		auto sprite = loadSprite(m_projectileTypeMap[projectile.getType()], projectile.getSize().x, projectile.getSize().y);
		sprite->setPosition(sf::Vector2f(projectile.getPosition().x, projectile.getPosition().y));
		m_window->draw(*sprite);
	}

	// Render powerups
	for (auto &powerup : m_engine->getPowerups())
	{
		auto sprite = loadSprite(m_powerupTypeMap[powerup.getType()], powerup.getSize().x, powerup.getSize().y);
		sprite->setPosition(sf::Vector2f(powerup.getPosition().x, powerup.getPosition().y));
		m_window->draw(*sprite);
	}

	// Render effects
	//TODO

	m_window->display();
}

void FGame::setTile(FTile typeName, std::string filename)
{
	m_tileMap[typeName] = filename;
}

void FGame::setCharacterType(FCharacterType typeName, std::string filename)
{
	m_characterTypeMap[typeName] = filename;
}

void FGame::setWeaponType(FWeaponType typeName, std::string filename)
{
	m_weaponTypeMap[typeName] = filename;
}

void FGame::setProjectileType(FProjectileType typeName, std::string filename)
{
	m_projectileTypeMap[typeName] = filename;
}

void FGame::setPowerupType(FPowerupType typeName, std::string filename)
{
	m_powerupTypeMap[typeName] = filename;
}
<|endoftext|>


<commit_before>// ***************************************************************************
// FastaIndex.cpp (c) 2010 Erik Garrison <erik.garrison@bc.edu>
// Marth Lab, Department of Biology, Boston College
// All rights reserved.
// ---------------------------------------------------------------------------
// Last modified: 9 February 2010 (EG)
// ---------------------------------------------------------------------------

#include "Fasta.h"

FastaIndexEntry::FastaIndexEntry(string name, int length, long long offset, int line_blen, int line_len)
    : name(name)
    , length(length)
    , offset(offset)
    , line_blen(line_blen)
    , line_len(line_len)
{}

FastaIndexEntry::FastaIndexEntry(void) // empty constructor
{ clear(); }

FastaIndexEntry::~FastaIndexEntry(void)
{}

void FastaIndexEntry::clear(void)
{
    name = "";
    length = NULL;
    offset = -1;  // no real offset will ever be below 0, so this allows us to
                  // check if we have already recorded a real offset
    line_blen = NULL;
    line_len = NULL;
}

ostream& operator<<(ostream& output, const FastaIndexEntry& e) {
    // just write the first component of the name, for compliance with other tools
    output << split(e.name, ' ').at(0) << "\t" << e.length << "\t" << e.offset << "\t" <<
        e.line_blen << "\t" << e.line_len;
    return output;  // for multiple << operators.
}

FastaIndex::FastaIndex(void)
{}

void FastaIndex::readIndexFile(string fname) {
    string line;
    long long linenum = 0;
    indexFile.open(fname.c_str(), ifstream::in);
    if (indexFile.is_open()) {
        while (getline (indexFile, line)) {
            ++linenum;
            // the fai format defined in samtools is tab-delimited, every line being:
            // fai->name[i], (int)x.len, (long long)x.offset, (int)x.line_blen, (int)x.line_len
            vector<string> fields = split(line, '\t');
            if (fields.size() == 5) {  // if we don't get enough fields then there is a problem with the file
                // note that fields[0] is the sequence name
                char* end;
                string name = split(fields[0], " \t").at(0);  // key by first token of name
                sequenceNames.push_back(name);
                this->insert(make_pair(name, FastaIndexEntry(fields[0], atoi(fields[1].c_str()),
                                                    strtoll(fields[2].c_str(), &end, 10),
                                                    atoi(fields[3].c_str()),
                                                    atoi(fields[4].c_str()))));
            } else {
                cerr << "Warning: malformed fasta index file " << fname <<
                    "does not have enough fields @ line " << linenum << endl;
                cerr << line << endl;
                exit(1);
            }
        }
    } else {
        cerr << "could not open index file " << fname << endl;
        exit(1);
    }
}

// for consistency this should be a class method
bool fastaIndexEntryCompare ( FastaIndexEntry a, FastaIndexEntry b) { return (a.offset<b.offset); }

ostream& operator<<(ostream& output, FastaIndex& fastaIndex) {
    vector<FastaIndexEntry> sortedIndex;
    for(vector<string>::const_iterator it = fastaIndex.sequenceNames.begin(); it != fastaIndex.sequenceNames.end(); ++it)
    {
        sortedIndex.push_back(fastaIndex[*it]);
    }
    sort(sortedIndex.begin(), sortedIndex.end(), fastaIndexEntryCompare);
    for( vector<FastaIndexEntry>::iterator fit = sortedIndex.begin(); fit != sortedIndex.end(); ++fit) {
        output << *fit << endl;
    }
}

void FastaIndex::indexReference(string refname) {
    // overview:
    //  for line in the reference fasta file
    //  track byte offset from the start of the file
    //  if line is a fasta header, take the name and dump the last sequnece to the index
    //  if line is a sequence, add it to the current sequence
    //cerr << "indexing fasta reference " << refname << endl;
    string line;
    FastaIndexEntry entry;  // an entry buffer used in processing
    entry.clear();
    int line_length = 0;
    long long offset = 0;  // byte offset from start of file
    long long line_number = 0; // current line number
    bool mismatchedLineLengths = false; // flag to indicate if our line length changes mid-file
                                        // this will be used to raise an error
                                        // if we have a line length change at
                                        // any line other than the last line in
                                        // the sequence
    bool emptyLine = false;  // flag to catch empty lines, which we allow for
                             // index generation only on the last line of the sequence
    ifstream refFile;
    refFile.open(refname.c_str());
    if (refFile.is_open()) {
        while (getline(refFile, line)) {
            ++line_number;
            line_length = line.length();
            if (line[0] == ';') {
                // fasta comment, skip
            } else if (line[0] == '+') {
                // fastq quality header
                getline(refFile, line);
                line_length = line.length();
                offset += line_length + 1;
                // get and don't handle the quality line
                getline(refFile, line);
                line_length = line.length();
            } else if (line[0] == '>' || line[0] == '@') { // fasta /fastq header
                // if we aren't on the first entry, push the last sequence into the index
                if (entry.name != "") {
                    mismatchedLineLengths = false; // reset line length error tracker for every new sequence
                    emptyLine = false;
                    flushEntryToIndex(entry);
                    entry.clear();
                }
                entry.name = line.substr(1, line_length - 1);
            } else { // we assume we have found a sequence line
                if (entry.offset == -1) // NB initially the offset is -1
                    entry.offset = offset;
                entry.length += line_length;
                if (entry.line_len) {
                    //entry.line_len = entry.line_len ? entry.line_len : line_length + 1;
                    if (mismatchedLineLengths || emptyLine) {
                        if (line_length == 0) {
                            emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence
                        } else {
                            if (emptyLine) {
                                cerr << "ERROR: embedded newline";
                            } else {
                                cerr << "ERROR: mismatched line lengths";
                            }
                            cerr << " at line " << line_number << " within sequence " << entry.name <<
                                endl << "File not suitable for fasta index generation." << endl;
                            exit(1);
                        }
                    }
                    // this flag is set here and checked on the next line
                    // because we may have reached the end of the sequence, in
                    // which case a mismatched line length is OK
                    if (entry.line_len != line_length + 1) {
                        mismatchedLineLengths = true;
                        if (line_length == 0) {
                            emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence
                        }
                    }
                } else {
                    entry.line_len = line_length + 1; // first line
                }
                entry.line_blen = entry.line_len - 1;
            }
            offset += line_length + 1;
        }
        // we've hit the end of the fasta file!
        // flush the last entry
        flushEntryToIndex(entry);
    } else {
        cerr << "could not open reference file " << refname << " for indexing!" << endl;
        exit(1);
    }
}

void FastaIndex::flushEntryToIndex(FastaIndexEntry& entry) {
    string name = split(entry.name, " \t").at(0);  // key by first token of name
    sequenceNames.push_back(name);
    this->insert(make_pair(name, FastaIndexEntry(entry.name, entry.length,
                        entry.offset, entry.line_blen,
                        entry.line_len)));

}

void FastaIndex::writeIndexFile(string fname) {
    //cerr << "writing fasta index file " << fname << endl;
    ofstream file;
    file.open(fname.c_str());
    if (file.is_open()) {
        file << *this;
    } else {
        cerr << "could not open index file " << fname << " for writing!" << endl;
        exit(1);
    }
}

FastaIndex::~FastaIndex(void) {
    indexFile.close();
}

FastaIndexEntry FastaIndex::entry(string name) {
    FastaIndex::iterator e = this->find(name);
    if (e == this->end()) {
        cerr << "unable to find FASTA index entry for '" << name << "'" << endl;
        exit(1);
    } else {
        return e->second;
    }
}

string FastaIndex::indexFileExtension() { return ".fai"; }

/*
FastaReference::FastaReference(string reffilename) {
}
*/

void FastaReference::open(string reffilename) {
    filename = reffilename;
    if (!(file = fopen(filename.c_str(), "r"))) {
        cerr << "could not open " << filename << endl;
        exit(1);
    }
    index = new FastaIndex();
    struct stat stFileInfo;
    string indexFileName = filename + index->indexFileExtension();
    // if we can find an index file, use it
    if(stat(indexFileName.c_str(), &stFileInfo) == 0) {
        index->readIndexFile(indexFileName);
    } else { // otherwise, read the reference and generate the index file in the cwd
        cerr << "index file " << indexFileName << " not found, generating..." << endl;
        index->indexReference(filename);
        index->writeIndexFile(indexFileName);
    }
}

FastaReference::~FastaReference(void) {
    fclose(file);
    delete index;
}

string FastaReference::getSequence(string seqname) {
    FastaIndexEntry entry = index->entry(seqname);
    int newlines_in_sequence = entry.length / entry.line_blen;
    int seqlen = newlines_in_sequence  + entry.length;
    char* seq = (char*) calloc (seqlen + 1, sizeof(char));
    fseek64(file, entry.offset, SEEK_SET);
    fread(seq, sizeof(char), seqlen, file);
    seq[seqlen] = '\0';
    char* pbegin = seq;
    char* pend = seq + (seqlen/sizeof(char));
    pend = remove(pbegin, pend, '\n');
    pend = remove(pbegin, pend, '\0');
    string s = seq;
    free(seq);
    s.resize((pend - pbegin)/sizeof(char));
    return s;
}

// TODO cleanup; odd function.  use a map
string FastaReference::sequenceNameStartingWith(string seqnameStart) {
    try {
        return (*index)[seqnameStart].name;
    } catch (exception& e) {
        cerr << e.what() << ": unable to find index entry for " << seqnameStart << endl;
        exit(1);
    }
}

string FastaReference::getSubSequence(string seqname, int start, int length) {
    FastaIndexEntry entry = index->entry(seqname);
    if (start < 0 || length < 1) {
        cerr << "Error: cannot construct subsequence with negative offset or length < 1" << endl;
        exit(1);
    }
    // we have to handle newlines
    // approach: count newlines before start
    //           count newlines by end of read
    //             subtracting newlines before start find count of embedded newlines
    int newlines_before = start > 0 ? (start - 1) / entry.line_blen : 0;
    int newlines_by_end = (start + length - 1) / entry.line_blen;
    int newlines_inside = newlines_by_end - newlines_before;
    int seqlen = length + newlines_inside;
    char* seq = (char*) calloc (seqlen + 1, sizeof(char));
    fseek64(file, (off_t) (entry.offset + newlines_before + start), SEEK_SET);
    fread(seq, sizeof(char), (off_t) seqlen, file);
    seq[seqlen] = '\0';
    char* pbegin = seq;
    char* pend = seq + (seqlen/sizeof(char));
    pend = remove(pbegin, pend, '\n');
    pend = remove(pbegin, pend, '\0');
    string s = seq;
    free(seq);
    s.resize((pend - pbegin)/sizeof(char));
    return s;
}

long unsigned int FastaReference::sequenceLength(string seqname) {
    FastaIndexEntry entry = index->entry(seqname);
    return entry.length;
}

<commit_msg>clean up Fasta.cpp compile, NULL -> 0<commit_after>// ***************************************************************************
// FastaIndex.cpp (c) 2010 Erik Garrison <erik.garrison@bc.edu>
// Marth Lab, Department of Biology, Boston College
// All rights reserved.
// ---------------------------------------------------------------------------
// Last modified: 9 February 2010 (EG)
// ---------------------------------------------------------------------------

#include "Fasta.h"

FastaIndexEntry::FastaIndexEntry(string name, int length, long long offset, int line_blen, int line_len)
    : name(name)
    , length(length)
    , offset(offset)
    , line_blen(line_blen)
    , line_len(line_len)
{}

FastaIndexEntry::FastaIndexEntry(void) // empty constructor
{ clear(); }

FastaIndexEntry::~FastaIndexEntry(void)
{}

void FastaIndexEntry::clear(void)
{
    name = "";
    length = 0;
    offset = -1;  // no real offset will ever be below 0, so this allows us to
                  // check if we have already recorded a real offset
    line_blen = 0;
    line_len = 0;
}

ostream& operator<<(ostream& output, const FastaIndexEntry& e) {
    // just write the first component of the name, for compliance with other tools
    output << split(e.name, ' ').at(0) << "\t" << e.length << "\t" << e.offset << "\t" <<
        e.line_blen << "\t" << e.line_len;
    return output;  // for multiple << operators.
}

FastaIndex::FastaIndex(void)
{}

void FastaIndex::readIndexFile(string fname) {
    string line;
    long long linenum = 0;
    indexFile.open(fname.c_str(), ifstream::in);
    if (indexFile.is_open()) {
        while (getline (indexFile, line)) {
            ++linenum;
            // the fai format defined in samtools is tab-delimited, every line being:
            // fai->name[i], (int)x.len, (long long)x.offset, (int)x.line_blen, (int)x.line_len
            vector<string> fields = split(line, '\t');
            if (fields.size() == 5) {  // if we don't get enough fields then there is a problem with the file
                // note that fields[0] is the sequence name
                char* end;
                string name = split(fields[0], " \t").at(0);  // key by first token of name
                sequenceNames.push_back(name);
                this->insert(make_pair(name, FastaIndexEntry(fields[0], atoi(fields[1].c_str()),
                                                    strtoll(fields[2].c_str(), &end, 10),
                                                    atoi(fields[3].c_str()),
                                                    atoi(fields[4].c_str()))));
            } else {
                cerr << "Warning: malformed fasta index file " << fname <<
                    "does not have enough fields @ line " << linenum << endl;
                cerr << line << endl;
                exit(1);
            }
        }
    } else {
        cerr << "could not open index file " << fname << endl;
        exit(1);
    }
}

// for consistency this should be a class method
bool fastaIndexEntryCompare ( FastaIndexEntry a, FastaIndexEntry b) { return (a.offset<b.offset); }

ostream& operator<<(ostream& output, FastaIndex& fastaIndex) {
    vector<FastaIndexEntry> sortedIndex;
    for(vector<string>::const_iterator it = fastaIndex.sequenceNames.begin(); it != fastaIndex.sequenceNames.end(); ++it)
    {
        sortedIndex.push_back(fastaIndex[*it]);
    }
    sort(sortedIndex.begin(), sortedIndex.end(), fastaIndexEntryCompare);
    for( vector<FastaIndexEntry>::iterator fit = sortedIndex.begin(); fit != sortedIndex.end(); ++fit) {
        output << *fit << endl;
    }
}

void FastaIndex::indexReference(string refname) {
    // overview:
    //  for line in the reference fasta file
    //  track byte offset from the start of the file
    //  if line is a fasta header, take the name and dump the last sequnece to the index
    //  if line is a sequence, add it to the current sequence
    //cerr << "indexing fasta reference " << refname << endl;
    string line;
    FastaIndexEntry entry;  // an entry buffer used in processing
    entry.clear();
    int line_length = 0;
    long long offset = 0;  // byte offset from start of file
    long long line_number = 0; // current line number
    bool mismatchedLineLengths = false; // flag to indicate if our line length changes mid-file
                                        // this will be used to raise an error
                                        // if we have a line length change at
                                        // any line other than the last line in
                                        // the sequence
    bool emptyLine = false;  // flag to catch empty lines, which we allow for
                             // index generation only on the last line of the sequence
    ifstream refFile;
    refFile.open(refname.c_str());
    if (refFile.is_open()) {
        while (getline(refFile, line)) {
            ++line_number;
            line_length = line.length();
            if (line[0] == ';') {
                // fasta comment, skip
            } else if (line[0] == '+') {
                // fastq quality header
                getline(refFile, line);
                line_length = line.length();
                offset += line_length + 1;
                // get and don't handle the quality line
                getline(refFile, line);
                line_length = line.length();
            } else if (line[0] == '>' || line[0] == '@') { // fasta /fastq header
                // if we aren't on the first entry, push the last sequence into the index
                if (entry.name != "") {
                    mismatchedLineLengths = false; // reset line length error tracker for every new sequence
                    emptyLine = false;
                    flushEntryToIndex(entry);
                    entry.clear();
                }
                entry.name = line.substr(1, line_length - 1);
            } else { // we assume we have found a sequence line
                if (entry.offset == -1) // NB initially the offset is -1
                    entry.offset = offset;
                entry.length += line_length;
                if (entry.line_len) {
                    //entry.line_len = entry.line_len ? entry.line_len : line_length + 1;
                    if (mismatchedLineLengths || emptyLine) {
                        if (line_length == 0) {
                            emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence
                        } else {
                            if (emptyLine) {
                                cerr << "ERROR: embedded newline";
                            } else {
                                cerr << "ERROR: mismatched line lengths";
                            }
                            cerr << " at line " << line_number << " within sequence " << entry.name <<
                                endl << "File not suitable for fasta index generation." << endl;
                            exit(1);
                        }
                    }
                    // this flag is set here and checked on the next line
                    // because we may have reached the end of the sequence, in
                    // which case a mismatched line length is OK
                    if (entry.line_len != line_length + 1) {
                        mismatchedLineLengths = true;
                        if (line_length == 0) {
                            emptyLine = true; // flag empty lines, raise error only if this is embedded in the sequence
                        }
                    }
                } else {
                    entry.line_len = line_length + 1; // first line
                }
                entry.line_blen = entry.line_len - 1;
            }
            offset += line_length + 1;
        }
        // we've hit the end of the fasta file!
        // flush the last entry
        flushEntryToIndex(entry);
    } else {
        cerr << "could not open reference file " << refname << " for indexing!" << endl;
        exit(1);
    }
}

void FastaIndex::flushEntryToIndex(FastaIndexEntry& entry) {
    string name = split(entry.name, " \t").at(0);  // key by first token of name
    sequenceNames.push_back(name);
    this->insert(make_pair(name, FastaIndexEntry(entry.name, entry.length,
                        entry.offset, entry.line_blen,
                        entry.line_len)));

}

void FastaIndex::writeIndexFile(string fname) {
    //cerr << "writing fasta index file " << fname << endl;
    ofstream file;
    file.open(fname.c_str());
    if (file.is_open()) {
        file << *this;
    } else {
        cerr << "could not open index file " << fname << " for writing!" << endl;
        exit(1);
    }
}

FastaIndex::~FastaIndex(void) {
    indexFile.close();
}

FastaIndexEntry FastaIndex::entry(string name) {
    FastaIndex::iterator e = this->find(name);
    if (e == this->end()) {
        cerr << "unable to find FASTA index entry for '" << name << "'" << endl;
        exit(1);
    } else {
        return e->second;
    }
}

string FastaIndex::indexFileExtension() { return ".fai"; }

/*
FastaReference::FastaReference(string reffilename) {
}
*/

void FastaReference::open(string reffilename) {
    filename = reffilename;
    if (!(file = fopen(filename.c_str(), "r"))) {
        cerr << "could not open " << filename << endl;
        exit(1);
    }
    index = new FastaIndex();
    struct stat stFileInfo;
    string indexFileName = filename + index->indexFileExtension();
    // if we can find an index file, use it
    if(stat(indexFileName.c_str(), &stFileInfo) == 0) {
        index->readIndexFile(indexFileName);
    } else { // otherwise, read the reference and generate the index file in the cwd
        cerr << "index file " << indexFileName << " not found, generating..." << endl;
        index->indexReference(filename);
        index->writeIndexFile(indexFileName);
    }
}

FastaReference::~FastaReference(void) {
    fclose(file);
    delete index;
}

string FastaReference::getSequence(string seqname) {
    FastaIndexEntry entry = index->entry(seqname);
    int newlines_in_sequence = entry.length / entry.line_blen;
    int seqlen = newlines_in_sequence  + entry.length;
    char* seq = (char*) calloc (seqlen + 1, sizeof(char));
    fseek64(file, entry.offset, SEEK_SET);
    fread(seq, sizeof(char), seqlen, file);
    seq[seqlen] = '\0';
    char* pbegin = seq;
    char* pend = seq + (seqlen/sizeof(char));
    pend = remove(pbegin, pend, '\n');
    pend = remove(pbegin, pend, '\0');
    string s = seq;
    free(seq);
    s.resize((pend - pbegin)/sizeof(char));
    return s;
}

// TODO cleanup; odd function.  use a map
string FastaReference::sequenceNameStartingWith(string seqnameStart) {
    try {
        return (*index)[seqnameStart].name;
    } catch (exception& e) {
        cerr << e.what() << ": unable to find index entry for " << seqnameStart << endl;
        exit(1);
    }
}

string FastaReference::getSubSequence(string seqname, int start, int length) {
    FastaIndexEntry entry = index->entry(seqname);
    if (start < 0 || length < 1) {
        cerr << "Error: cannot construct subsequence with negative offset or length < 1"
           << "(attempting start = " << start << " and length = " << length << ")" << endl;
        exit(1);
    }
    // we have to handle newlines
    // approach: count newlines before start
    //           count newlines by end of read
    //             subtracting newlines before start find count of embedded newlines
    int newlines_before = start > 0 ? (start - 1) / entry.line_blen : 0;
    int newlines_by_end = (start + length - 1) / entry.line_blen;
    int newlines_inside = newlines_by_end - newlines_before;
    int seqlen = length + newlines_inside;
    char* seq = (char*) calloc (seqlen + 1, sizeof(char));
    fseek64(file, (off_t) (entry.offset + newlines_before + start), SEEK_SET);
    fread(seq, sizeof(char), (off_t) seqlen, file);
    seq[seqlen] = '\0';
    char* pbegin = seq;
    char* pend = seq + (seqlen/sizeof(char));
    pend = remove(pbegin, pend, '\n');
    pend = remove(pbegin, pend, '\0');
    string s = seq;
    free(seq);
    s.resize((pend - pbegin)/sizeof(char));
    return s;
}

long unsigned int FastaReference::sequenceLength(string seqname) {
    FastaIndexEntry entry = index->entry(seqname);
    return entry.length;
}

<|endoftext|>


<commit_before><commit_msg>Don't check for pWin when drawing the Scrollbar<commit_after><|endoftext|>


<commit_before><commit_msg>tdf#91380 add WB_MOVEABLE bit to docking windows<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2009 Josh A. Beam <josh@joshbeam.com>
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 CONTACT, 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.
 */

#include <cstdio>
#include <cstring>
#include <DromeAudio/Exception.h>
#include <DromeAudio/Sound.h>
#ifdef WITH_VORBIS
	#include <DromeAudio/VorbisSound.h>
#endif /* WITH_VORBIS */
#include <DromeAudio/WavSound.h>
#include <DromeAudio/Util.h>
#include "Wav.h"

namespace DromeAudio {

/*
 * Sound class
 */
Sound::Sound()
{
}

Sample
Sound::getSample(unsigned int index, unsigned int targetRate) const
{
	unsigned int rate = getSampleRate();

	// map index from target sample rate if necessary
	if(targetRate != rate) {
		float f = (float)rate / (float)targetRate;
		index = (unsigned int)((float)index * f);
	}

	return getSample(index);
}

void
Sound::save(const char *filename, unsigned int numSamples)
{
	const unsigned char bytesPerSample = 2;
	const unsigned char numChannels = 2;

	// make sure the number of samples to save is good
	if(numSamples == 0) {
		if(getNumSamples() == 0)
			throw Exception("Sound::Save(): Cannot save %s; sound has unlimited number of samples and the number of samples to save was not provided", filename);

		numSamples = getNumSamples();
	}

	// open file for writing
	FILE *fp = fopen(filename, "wb");
	if(!fp)
		throw Exception("Sound::Save(): Unable to open %s for writing", filename);

	// calculate length of sample data
	unsigned int dataLength = numSamples * (unsigned int)bytesPerSample * (unsigned int)numChannels;

	// create riff header
	WavChunkHeader hdr;
	hdr.chunk_id[0] = 'R'; hdr.chunk_id[1] = 'I';
	hdr.chunk_id[2] = 'F'; hdr.chunk_id[3] = 'F';
	hdr.chunk_size = nativeToLittleUInt32(4 + (sizeof(WavChunkHeader) * 2) + sizeof(WavFmtChunk));
	fwrite(&hdr, sizeof(hdr), 1, fp);

	// write riff type
	char tmp[4];
	tmp[0] = 'W'; tmp[1] = 'A'; tmp[2] = 'V'; tmp[3] = 'E';
	fwrite(tmp, 4, 1, fp);

	// write fmt header
	hdr.chunk_id[0] = 'f'; hdr.chunk_id[1] = 'm';
	hdr.chunk_id[2] = 't'; hdr.chunk_id[3] = ' ';
	hdr.chunk_size = nativeToLittleUInt32(sizeof(WavFmtChunk));
	fwrite(&hdr, sizeof(hdr), 1, fp);

	// write fmt chunk
	WavFmtChunk fmt;
	fmt.type = nativeToLittleUInt16(1);
	fmt.channels = nativeToLittleUInt16(numChannels);
	fmt.rate = nativeToLittleUInt32(getSampleRate());
	fmt.bytes_per_second = nativeToLittleUInt32((unsigned int)bytesPerSample * (unsigned int)numChannels * getSampleRate());
	fmt.block_align = nativeToLittleUInt16((uint16_t)bytesPerSample * (uint16_t)numChannels);
	fmt.bits_per_sample = nativeToLittleUInt16((uint16_t)bytesPerSample * 8);
	fwrite(&fmt, sizeof(fmt), 1, fp);

	// write data header
	hdr.chunk_id[0] = 'd'; hdr.chunk_id[1] = 'a';
	hdr.chunk_id[2] = 't'; hdr.chunk_id[3] = 'a';
	hdr.chunk_size = nativeToLittleUInt32(dataLength);
	fwrite(&hdr, sizeof(hdr), 1, fp);

	// write data
	for(unsigned int i = 0; i < numSamples; i++) {
		uint16_t s[2];
		Sample sample = getSample(i);

		s[0] = nativeToLittleUInt16((uint16_t)(32767.0f * sample[0]));
		s[1] = nativeToLittleUInt16((uint16_t)(32767.0f * sample[1]));

		fwrite(s, sizeof(s), 1, fp);
	}

	// done
	fclose(fp);
}

SoundPtr
Sound::create(const char *filename)
{
	// look for file extension
	const char *tmp = filename + strlen(filename);
	while(tmp != filename && *tmp != '.')
		--tmp;
	if(tmp == filename)
		throw Exception("Sound::New(): filename has no extension");

	// create sound based on extension
#ifdef WITH_VORBIS
	if(strCaseCmp(tmp, ".ogg") == 0)
		return VorbisSound::create(filename);
#endif /* WITH_VORBIS */
	if(strCaseCmp(tmp, ".wav") == 0)
		return WavSound::create(filename);

	throw Exception("Sound::New(): Unsupported file extension (%s)", tmp);
	return NULL;
}

} // namespace DromeAudio
<commit_msg>Fixed outdated function names in Exception messages.<commit_after>/*
 * Copyright (C) 2008-2009 Josh A. Beam <josh@joshbeam.com>
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 CONTACT, 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.
 */

#include <cstdio>
#include <cstring>
#include <DromeAudio/Exception.h>
#include <DromeAudio/Sound.h>
#ifdef WITH_VORBIS
	#include <DromeAudio/VorbisSound.h>
#endif /* WITH_VORBIS */
#include <DromeAudio/WavSound.h>
#include <DromeAudio/Util.h>
#include "Wav.h"

namespace DromeAudio {

/*
 * Sound class
 */
Sound::Sound()
{
}

Sample
Sound::getSample(unsigned int index, unsigned int targetRate) const
{
	unsigned int rate = getSampleRate();

	// map index from target sample rate if necessary
	if(targetRate != rate) {
		float f = (float)rate / (float)targetRate;
		index = (unsigned int)((float)index * f);
	}

	return getSample(index);
}

void
Sound::save(const char *filename, unsigned int numSamples)
{
	const unsigned char bytesPerSample = 2;
	const unsigned char numChannels = 2;

	// make sure the number of samples to save is good
	if(numSamples == 0) {
		if(getNumSamples() == 0)
			throw Exception("Sound::Save(): Cannot save %s; sound has unlimited number of samples and the number of samples to save was not provided", filename);

		numSamples = getNumSamples();
	}

	// open file for writing
	FILE *fp = fopen(filename, "wb");
	if(!fp)
		throw Exception("Sound::Save(): Unable to open %s for writing", filename);

	// calculate length of sample data
	unsigned int dataLength = numSamples * (unsigned int)bytesPerSample * (unsigned int)numChannels;

	// create riff header
	WavChunkHeader hdr;
	hdr.chunk_id[0] = 'R'; hdr.chunk_id[1] = 'I';
	hdr.chunk_id[2] = 'F'; hdr.chunk_id[3] = 'F';
	hdr.chunk_size = nativeToLittleUInt32(4 + (sizeof(WavChunkHeader) * 2) + sizeof(WavFmtChunk));
	fwrite(&hdr, sizeof(hdr), 1, fp);

	// write riff type
	char tmp[4];
	tmp[0] = 'W'; tmp[1] = 'A'; tmp[2] = 'V'; tmp[3] = 'E';
	fwrite(tmp, 4, 1, fp);

	// write fmt header
	hdr.chunk_id[0] = 'f'; hdr.chunk_id[1] = 'm';
	hdr.chunk_id[2] = 't'; hdr.chunk_id[3] = ' ';
	hdr.chunk_size = nativeToLittleUInt32(sizeof(WavFmtChunk));
	fwrite(&hdr, sizeof(hdr), 1, fp);

	// write fmt chunk
	WavFmtChunk fmt;
	fmt.type = nativeToLittleUInt16(1);
	fmt.channels = nativeToLittleUInt16(numChannels);
	fmt.rate = nativeToLittleUInt32(getSampleRate());
	fmt.bytes_per_second = nativeToLittleUInt32((unsigned int)bytesPerSample * (unsigned int)numChannels * getSampleRate());
	fmt.block_align = nativeToLittleUInt16((uint16_t)bytesPerSample * (uint16_t)numChannels);
	fmt.bits_per_sample = nativeToLittleUInt16((uint16_t)bytesPerSample * 8);
	fwrite(&fmt, sizeof(fmt), 1, fp);

	// write data header
	hdr.chunk_id[0] = 'd'; hdr.chunk_id[1] = 'a';
	hdr.chunk_id[2] = 't'; hdr.chunk_id[3] = 'a';
	hdr.chunk_size = nativeToLittleUInt32(dataLength);
	fwrite(&hdr, sizeof(hdr), 1, fp);

	// write data
	for(unsigned int i = 0; i < numSamples; i++) {
		uint16_t s[2];
		Sample sample = getSample(i);

		s[0] = nativeToLittleUInt16((uint16_t)(32767.0f * sample[0]));
		s[1] = nativeToLittleUInt16((uint16_t)(32767.0f * sample[1]));

		fwrite(s, sizeof(s), 1, fp);
	}

	// done
	fclose(fp);
}

SoundPtr
Sound::create(const char *filename)
{
	// look for file extension
	const char *tmp = filename + strlen(filename);
	while(tmp != filename && *tmp != '.')
		--tmp;
	if(tmp == filename)
		throw Exception("Sound::create(): filename has no extension");

	// create sound based on extension
#ifdef WITH_VORBIS
	if(strCaseCmp(tmp, ".ogg") == 0)
		return VorbisSound::create(filename);
#endif /* WITH_VORBIS */
	if(strCaseCmp(tmp, ".wav") == 0)
		return WavSound::create(filename);

	throw Exception("Sound::create(): Unsupported file extension (%s)", tmp);
	return NULL;
}

} // namespace DromeAudio
<|endoftext|>


<commit_before>#include "SqrtX.hpp"

#include <climits>

using namespace std;

int SqrtX::mySqrt(int x) {
    if (x == 0)
        return 0;

    int left = 1, right = INT_MAX;

    while (true) {
        int mid = left + (right - left) / 2;

        if (mid > x / mid)
            right = mid - 1;
        else if (mid + 1 > x / (mid + 1))
            return mid;
        else
            left = mid + 1;
    }
}<commit_msg>Refine Problem 69. Sqrt(x)<commit_after>#include "SqrtX.hpp"

#include <cstdint>

using namespace std;

int SqrtX::mySqrt(int x) {
    int64_t l = 1, r = x;

    while (l + 1 < r) {
        int64_t m = l + (r - l) / 2;
        if (m * m < x)
            l = m;
        else
            r = m;
    }

    return r * r <= x ? r : l;
}<|endoftext|>


<commit_before>#ifndef VPP_OPENCV_BRIDGE_HH__
# define VPP_OPENCV_BRIDGE_HH__

# include <opencv2/opencv.hpp>
# include <vpp/core/image2d.hh>

namespace vpp
{

  template <typename T>
  struct opencv_typeof;

#define OPENCV_TYPEOF(T, V)			\
  template <>					\
  struct opencv_typeof<T>                       \
  {						\
    enum { ret = V };				\
  };

#define OPENCV_TYPEOF_(BT, T, CV)		\
  OPENCV_TYPEOF(BT, CV_##CV##C1);		\
  OPENCV_TYPEOF(v##T##1, CV_##CV##C1);		\
  OPENCV_TYPEOF(v##T##2, CV_##CV##C2);		\
  OPENCV_TYPEOF(v##T##3, CV_##CV##C3);		\
  OPENCV_TYPEOF(v##T##4, CV_##CV##C4);

  OPENCV_TYPEOF_(unsigned char, uchar, 8U);
  OPENCV_TYPEOF_(char, char, 8S);
  OPENCV_TYPEOF_(unsigned short, ushort, 16U);
  OPENCV_TYPEOF_(short, short, 16S);
  OPENCV_TYPEOF_(float, float, 32F);
  OPENCV_TYPEOF_(int, int, 32S);

  struct opencv_data_holder
  {
    int* refcount;
    void* data;
  };

  static void opencv_data_deleter(void* data)
  {
    opencv_data_holder* d = (opencv_data_holder*) data;

    if (d->refcount and *(d->refcount) > 1)
      *(d->refcount) -= 1;
    else if (d->refcount and *(d->refcount) == 1)
      cv::fastFree(d->data);
    delete d;
  }

  template <typename V>
  image2d<V> from_opencv(cv::Mat m)
  {
    if (!m.data) return image2d<V>();

    image2d<V> res(make_box2d(m.rows, m.cols), _data = m.data, _pitch = m.step);

    #if CV_VERSION_MAJOR == 2
    res.set_external_data_holder(new opencv_data_holder{m.refcount, m.data}, opencv_data_deleter);
    #else
    res.set_external_data_holder(new opencv_data_holder{&m.u->refcount, m.data}, opencv_data_deleter);
    #endif

    m.addref();
    return res;
  }

  template <typename V>
  cv::Mat to_opencv(image2d<V>& v)
  {
    if (!v.has_data()) return cv::Mat();

    cv::Mat m(v.nrows(), v.ncols(), opencv_typeof<V>::ret, (void*) v.address_of(vint2(0,0)), v.pitch());
    return m;
  }

};

#endif
<commit_msg>Fix compilation with opencv2.<commit_after>#ifndef VPP_OPENCV_BRIDGE_HH__
# define VPP_OPENCV_BRIDGE_HH__

# include <opencv2/opencv.hpp>
# include <vpp/core/image2d.hh>

namespace vpp
{

  template <typename T>
  struct opencv_typeof;

#define OPENCV_TYPEOF(T, V)			\
  template <>					\
  struct opencv_typeof<T>                       \
  {						\
    enum { ret = V };				\
  };

#define OPENCV_TYPEOF_(BT, T, CV)		\
  OPENCV_TYPEOF(BT, CV_##CV##C1);		\
  OPENCV_TYPEOF(v##T##1, CV_##CV##C1);		\
  OPENCV_TYPEOF(v##T##2, CV_##CV##C2);		\
  OPENCV_TYPEOF(v##T##3, CV_##CV##C3);		\
  OPENCV_TYPEOF(v##T##4, CV_##CV##C4);

  OPENCV_TYPEOF_(unsigned char, uchar, 8U);
  OPENCV_TYPEOF_(char, char, 8S);
  OPENCV_TYPEOF_(unsigned short, ushort, 16U);
  OPENCV_TYPEOF_(short, short, 16S);
  OPENCV_TYPEOF_(float, float, 32F);
  OPENCV_TYPEOF_(int, int, 32S);

  struct opencv_data_holder
  {
    int* refcount;
    void* data;
  };

  static void opencv_data_deleter(void* data)
  {
    opencv_data_holder* d = (opencv_data_holder*) data;

    if (d->refcount and *(d->refcount) > 1)
      *(d->refcount) -= 1;
    else if (d->refcount and *(d->refcount) == 1)
      cv::fastFree(d->data);
    delete d;
  }

  template <typename V>
  image2d<V> from_opencv(cv::Mat m)
  {
    if (!m.data) return image2d<V>();

    image2d<V> res(make_box2d(m.rows, m.cols), _data = m.data, _pitch = m.step);

    #if CV_VERSION_EPOCH == 2
    res.set_external_data_holder(new opencv_data_holder{m.refcount, m.data}, opencv_data_deleter);
    #else
    res.set_external_data_holder(new opencv_data_holder{&m.u->refcount, m.data}, opencv_data_deleter);
    #endif

    m.addref();
    return res;
  }

  template <typename V>
  cv::Mat to_opencv(image2d<V>& v)
  {
    if (!v.has_data()) return cv::Mat();

    cv::Mat m(v.nrows(), v.ncols(), opencv_typeof<V>::ret, (void*) v.address_of(vint2(0,0)), v.pitch());
    return m;
  }

};

#endif
<|endoftext|>