<commit_before>#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <unistd.h>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <gflags/gflags.h>
#include <set>
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include <boost/scoped_ptr.hpp>
#include "sort_file.h"
#include "logging.h"
#include "common/filesystem.h"
#include "common/tools_util.h"
#include "thread_pool.h"
#include "mutex.h"

DEFINE_int32(total, 0, "total numbers of map tasks");
DEFINE_int32(reduce_no, 0, "the reduce number of this reduce task");
DEFINE_string(work_dir, "/tmp", "the shuffle work dir");
DEFINE_int32(batch, 500, "merge how many maps output at the same time");
DEFINE_int32(attempt_id, 0, "the attempt_id of this reduce task");
DEFINE_string(dfs_host, "", "host name of dfs master");
DEFINE_string(dfs_port, "", "port of dfs master");
DEFINE_string(dfs_user, "", "user name of dfs master");
DEFINE_string(dfs_password, "", "password of dfs master");
DEFINE_string(pipe, "streaming", "pipe style: streaming/bistreaming");
DEFINE_bool(skip_merge, false, "whether skip merge phase");

using baidu::common::Log;
using baidu::common::FATAL;
using baidu::common::INFO;
using baidu::common::WARNING;
using namespace baidu;
using namespace baidu::shuttle;

std::set<std::string> g_merged;
int32_t g_file_no(0);
FileSystem* g_fs(NULL);
Mutex g_mu;

void FillParam(FileSystem::Param& param) {
    if (!FLAGS_dfs_user.empty()) {
        param["user"] = FLAGS_dfs_user;
    }
    if (!FLAGS_dfs_password.empty()) {
        param["password"] = FLAGS_dfs_password;
    }
    if (!FLAGS_dfs_host.empty()) {
        param["host"] = FLAGS_dfs_host;
    }
    if (!FLAGS_dfs_port.empty()) {
        param["port"] = FLAGS_dfs_port;
    }
}

void CollectFilesToMerge(std::vector<std::string>* maps_to_merge) {
    assert(maps_to_merge);
    for (int i = 0; i < FLAGS_total; i++) {
        std::stringstream ss;
        ss << FLAGS_work_dir << "/map_" << i;
        std::string map_dir = ss.str();
        if (g_merged.find(map_dir) != g_merged.end()) {
            continue;
        }
        if (g_fs->Exist(map_dir)) {
            LOG(INFO, "maps_to_merge: %s", map_dir.c_str());
            maps_to_merge->push_back(map_dir);
        }
        if (maps_to_merge->size() >= (size_t)FLAGS_batch) {
            break;
        }
    }
}

void AddSortFiles(const std::string map_dir, std::vector<std::string>* file_names) {
    assert(file_names);
    std::vector<FileInfo> sort_files;
    if (g_fs->List(map_dir, &sort_files)) {
        std::vector<FileInfo>::iterator jt;
        for (jt = sort_files.begin(); jt != sort_files.end(); jt++) {
            const std::string& file_name = jt->name;
            if (boost::ends_with(file_name, ".sort")) {
                MutexLock lock(&g_mu);
                file_names->push_back(file_name);
            }
        }
    } else {
        LOG(FATAL, "fail to list %s", map_dir.c_str());
    }
}

void MergeMapOutput(const std::vector<std::string>& maps_to_merge) {
    std::vector<std::string> * file_names = new std::vector<std::string>();
    boost::scoped_ptr<std::vector<std::string> > file_names_guard(file_names);
    std::vector<std::string>::const_iterator it;
    std::vector<std::string> real_merged_maps;
    ThreadPool pool;
    int map_ct = 0;
    for (it = maps_to_merge.begin(); it != maps_to_merge.end(); it++) {
        const std::string& map_dir = *it;
        pool.AddTask(boost::bind(&AddSortFiles, map_dir, file_names));
        map_ct++;
        real_merged_maps.push_back(map_dir);
        if (map_ct >= FLAGS_batch){
            break;
        }
    }
    LOG(INFO, "wait for list done");
    pool.Stop(true);
    if (file_names->empty()) {
        LOG(WARNING, "not map output found");
        return;
    }
    LOG(INFO, "list #%d *.sort files", file_names->size());
    MergeFileReader reader;
    FileSystem::Param param;
    FillParam(param);
    Status status = reader.Open(*file_names, param, kHdfsFile);
    if (status != kOk) {
        LOG(FATAL, "fail to open: %s", reader.GetErrorFile().c_str());
    }
    char s_reduce_no[256];
    snprintf(s_reduce_no, sizeof(s_reduce_no), "%05d", FLAGS_reduce_no);
    std::string s_reduce_key(s_reduce_no);

    SortFileReader::Iterator* scan_it = reader.Scan(s_reduce_key,
                                                    s_reduce_key + "\xff");
    if (scan_it->Error() != kOk && scan_it->Error() != kNoMore) {
        LOG(FATAL, "fail to scan: %s", reader.GetErrorFile().c_str());
    }

    char output_file[4096];
    snprintf(output_file, sizeof(output_file), "%s/reduce_%d_%d/%d.sort",
             FLAGS_work_dir.c_str(), FLAGS_reduce_no, FLAGS_attempt_id,
             g_file_no++);
    SortFileWriter * writer = SortFileWriter::Create(kHdfsFile, &status);
    if (status != kOk) {
        LOG(FATAL, "fail to create writer");
    }
    FileSystem::Param param_write;
    FillParam(param_write);
    param_write["replica"] = "2";
    status = writer->Open(output_file, param_write);
    if (status != kOk) {
        LOG(FATAL, "fail to open %s for write", output_file);
    }
    while (!scan_it->Done()) {
        status = writer->Put(scan_it->Key(), scan_it->Value());
        if (status != kOk) {
            LOG(FATAL, "fail to put: %s", output_file);
        }
        scan_it->Next();
    }
    if (scan_it->Error() != kOk && scan_it->Error() != kNoMore) {
        LOG(FATAL, "fail to scan: %s", reader.GetErrorFile().c_str());
    }
    status = writer->Close();
    if (status != kOk) {
        LOG(FATAL, "fail to close writer: %s", output_file);
    }
    delete scan_it;
    status = reader.Close();
    if (status != kOk) {
        LOG(FATAL, "fail to close reader: %s", reader.GetErrorFile().c_str());
    }
    delete writer;
    for (it = real_merged_maps.begin(); it != real_merged_maps.end(); it++) {
        LOG(INFO, "g_merged insert: %s", it->c_str());
        g_merged.insert(*it);
    }
}

void MergeAndPrint() {
    char reduce_merge_dir[4096];
    snprintf(reduce_merge_dir, sizeof(reduce_merge_dir),
             "%s/reduce_%d_%d",
             FLAGS_work_dir.c_str(), FLAGS_reduce_no, FLAGS_attempt_id);
    std::vector<FileInfo> children;
    if (!g_fs->List(reduce_merge_dir, &children)) {
        LOG(FATAL, "fail to list: %s", reduce_merge_dir);
    }
    std::vector<std::string> file_names;
    std::vector<FileInfo>::iterator it;
    for (it = children.begin(); it != children.end(); it++) {
        const std::string& file_name = it->name;
        if (boost::ends_with(file_name, ".sort")) {
            file_names.push_back(file_name);
        }
    }
    if (file_names.empty()) {
        LOG(WARNING, "no data for this reduce task");
        return;
    }
    MergeFileReader reader;
    FileSystem::Param param;
    FillParam(param);
    Status status = reader.Open(file_names, param, kHdfsFile);
    if (status != kOk) {
        LOG(FATAL, "fail to open: %s", reader.GetErrorFile().c_str());
    }
    SortFileReader::Iterator* scan_it = reader.Scan("", "");
    if (scan_it->Error() != kOk && scan_it->Error() != kNoMore) {
        LOG(FATAL, "fail to scan: %s", reader.GetErrorFile().c_str());
    }
    while (!scan_it->Done()) {
        if (FLAGS_pipe == "streaming") {
            std::cout << scan_it->Value() << std::endl;
        } else {
            std::cout << scan_it->Value();
        }
        scan_it->Next();
    }
    if (scan_it->Error() != kOk && scan_it->Error() != kNoMore) {
        LOG(FATAL, "fail to scan: %s", reader.GetErrorFile().c_str());
    }
    reader.Close();
}

int main(int argc, char* argv[]) {
    baidu::common::SetLogFile(GetLogName("./shuffle_tool.log").c_str());
    baidu::common::SetWarningFile(GetLogName("./shuffle_tool.log.wf").c_str());
    google::ParseCommandLineFlags(&argc, &argv, true);
    FileSystem::Param param;
    FillParam(param);
    g_fs = FileSystem::CreateInfHdfs(param);
    if (FLAGS_total == 0 ) {
        LOG(FATAL, "invalid map task total");
    }
    while (!FLAGS_skip_merge && (int32_t)g_merged.size() < FLAGS_total) {
        std::vector<std::string> maps_to_merge;
        CollectFilesToMerge(&maps_to_merge);
        if (maps_to_merge.empty()) {
            LOG(INFO, "map output is empty, wait 10 seconds and try...");
            sleep(10);
            continue;
        }
        if (maps_to_merge.size() >= (size_t)FLAGS_batch ||
            maps_to_merge.size() + g_merged.size() >= (size_t)FLAGS_total) {
            LOG(INFO, "try merge %d maps", maps_to_merge.size());
            std::random_shuffle(maps_to_merge.begin(), maps_to_merge.end());
            MergeMapOutput(maps_to_merge);
        } else {
            LOG(INFO, "merged: %d, wait-for merge: %d", g_merged.size(), maps_to_merge.size());
            LOG(INFO, "wait for enough map-output to merge, sleep 5 second");
            sleep(5);
        }
        LOG(INFO, "merge progress: < %d/%d > ", g_merged.size(), FLAGS_total);
    }
    LOG(INFO, "merge and print out");
    MergeAndPrint();
    return 0;
}
<commit_msg>bigger batch merge size<commit_after>#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <unistd.h>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <gflags/gflags.h>
#include <set>
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include <boost/scoped_ptr.hpp>
#include "sort_file.h"
#include "logging.h"
#include "common/filesystem.h"
#include "common/tools_util.h"
#include "thread_pool.h"
#include "mutex.h"

DEFINE_int32(total, 0, "total numbers of map tasks");
DEFINE_int32(reduce_no, 0, "the reduce number of this reduce task");
DEFINE_string(work_dir, "/tmp", "the shuffle work dir");
DEFINE_int32(batch, 800, "merge how many maps output at the same time");
DEFINE_int32(attempt_id, 0, "the attempt_id of this reduce task");
DEFINE_string(dfs_host, "", "host name of dfs master");
DEFINE_string(dfs_port, "", "port of dfs master");
DEFINE_string(dfs_user, "", "user name of dfs master");
DEFINE_string(dfs_password, "", "password of dfs master");
DEFINE_string(pipe, "streaming", "pipe style: streaming/bistreaming");
DEFINE_bool(skip_merge, false, "whether skip merge phase");

using baidu::common::Log;
using baidu::common::FATAL;
using baidu::common::INFO;
using baidu::common::WARNING;
using namespace baidu;
using namespace baidu::shuttle;

std::set<std::string> g_merged;
int32_t g_file_no(0);
FileSystem* g_fs(NULL);
Mutex g_mu;

void FillParam(FileSystem::Param& param) {
    if (!FLAGS_dfs_user.empty()) {
        param["user"] = FLAGS_dfs_user;
    }
    if (!FLAGS_dfs_password.empty()) {
        param["password"] = FLAGS_dfs_password;
    }
    if (!FLAGS_dfs_host.empty()) {
        param["host"] = FLAGS_dfs_host;
    }
    if (!FLAGS_dfs_port.empty()) {
        param["port"] = FLAGS_dfs_port;
    }
}

void CollectFilesToMerge(std::vector<std::string>* maps_to_merge) {
    assert(maps_to_merge);
    for (int i = 0; i < FLAGS_total; i++) {
        std::stringstream ss;
        ss << FLAGS_work_dir << "/map_" << i;
        std::string map_dir = ss.str();
        if (g_merged.find(map_dir) != g_merged.end()) {
            continue;
        }
        if (g_fs->Exist(map_dir)) {
            LOG(INFO, "maps_to_merge: %s", map_dir.c_str());
            maps_to_merge->push_back(map_dir);
        }
        if (maps_to_merge->size() >= (size_t)FLAGS_batch) {
            break;
        }
    }
}

void AddSortFiles(const std::string map_dir, std::vector<std::string>* file_names) {
    assert(file_names);
    std::vector<FileInfo> sort_files;
    if (g_fs->List(map_dir, &sort_files)) {
        std::vector<FileInfo>::iterator jt;
        for (jt = sort_files.begin(); jt != sort_files.end(); jt++) {
            const std::string& file_name = jt->name;
            if (boost::ends_with(file_name, ".sort")) {
                MutexLock lock(&g_mu);
                file_names->push_back(file_name);
            }
        }
    } else {
        LOG(FATAL, "fail to list %s", map_dir.c_str());
    }
}

void MergeMapOutput(const std::vector<std::string>& maps_to_merge) {
    std::vector<std::string> * file_names = new std::vector<std::string>();
    boost::scoped_ptr<std::vector<std::string> > file_names_guard(file_names);
    std::vector<std::string>::const_iterator it;
    std::vector<std::string> real_merged_maps;
    ThreadPool pool;
    int map_ct = 0;
    for (it = maps_to_merge.begin(); it != maps_to_merge.end(); it++) {
        const std::string& map_dir = *it;
        pool.AddTask(boost::bind(&AddSortFiles, map_dir, file_names));
        map_ct++;
        real_merged_maps.push_back(map_dir);
        if (map_ct >= FLAGS_batch){
            break;
        }
    }
    LOG(INFO, "wait for list done");
    pool.Stop(true);
    if (file_names->empty()) {
        LOG(WARNING, "not map output found");
        return;
    }
    LOG(INFO, "list #%d *.sort files", file_names->size());
    MergeFileReader reader;
    FileSystem::Param param;
    FillParam(param);
    Status status = reader.Open(*file_names, param, kHdfsFile);
    if (status != kOk) {
        LOG(FATAL, "fail to open: %s", reader.GetErrorFile().c_str());
    }
    char s_reduce_no[256];
    snprintf(s_reduce_no, sizeof(s_reduce_no), "%05d", FLAGS_reduce_no);
    std::string s_reduce_key(s_reduce_no);

    SortFileReader::Iterator* scan_it = reader.Scan(s_reduce_key,
                                                    s_reduce_key + "\xff");
    if (scan_it->Error() != kOk && scan_it->Error() != kNoMore) {
        LOG(FATAL, "fail to scan: %s", reader.GetErrorFile().c_str());
    }

    char output_file[4096];
    snprintf(output_file, sizeof(output_file), "%s/reduce_%d_%d/%d.sort",
             FLAGS_work_dir.c_str(), FLAGS_reduce_no, FLAGS_attempt_id,
             g_file_no++);
    SortFileWriter * writer = SortFileWriter::Create(kHdfsFile, &status);
    if (status != kOk) {
        LOG(FATAL, "fail to create writer");
    }
    FileSystem::Param param_write;
    FillParam(param_write);
    param_write["replica"] = "2";
    status = writer->Open(output_file, param_write);
    if (status != kOk) {
        LOG(FATAL, "fail to open %s for write", output_file);
    }
    while (!scan_it->Done()) {
        status = writer->Put(scan_it->Key(), scan_it->Value());
        if (status != kOk) {
            LOG(FATAL, "fail to put: %s", output_file);
        }
        scan_it->Next();
    }
    if (scan_it->Error() != kOk && scan_it->Error() != kNoMore) {
        LOG(FATAL, "fail to scan: %s", reader.GetErrorFile().c_str());
    }
    status = writer->Close();
    if (status != kOk) {
        LOG(FATAL, "fail to close writer: %s", output_file);
    }
    delete scan_it;
    status = reader.Close();
    if (status != kOk) {
        LOG(FATAL, "fail to close reader: %s", reader.GetErrorFile().c_str());
    }
    delete writer;
    for (it = real_merged_maps.begin(); it != real_merged_maps.end(); it++) {
        LOG(INFO, "g_merged insert: %s", it->c_str());
        g_merged.insert(*it);
    }
}

void MergeAndPrint() {
    char reduce_merge_dir[4096];
    snprintf(reduce_merge_dir, sizeof(reduce_merge_dir),
             "%s/reduce_%d_%d",
             FLAGS_work_dir.c_str(), FLAGS_reduce_no, FLAGS_attempt_id);
    std::vector<FileInfo> children;
    if (!g_fs->List(reduce_merge_dir, &children)) {
        LOG(FATAL, "fail to list: %s", reduce_merge_dir);
    }
    std::vector<std::string> file_names;
    std::vector<FileInfo>::iterator it;
    for (it = children.begin(); it != children.end(); it++) {
        const std::string& file_name = it->name;
        if (boost::ends_with(file_name, ".sort")) {
            file_names.push_back(file_name);
        }
    }
    if (file_names.empty()) {
        LOG(WARNING, "no data for this reduce task");
        return;
    }
    MergeFileReader reader;
    FileSystem::Param param;
    FillParam(param);
    Status status = reader.Open(file_names, param, kHdfsFile);
    if (status != kOk) {
        LOG(FATAL, "fail to open: %s", reader.GetErrorFile().c_str());
    }
    SortFileReader::Iterator* scan_it = reader.Scan("", "");
    if (scan_it->Error() != kOk && scan_it->Error() != kNoMore) {
        LOG(FATAL, "fail to scan: %s", reader.GetErrorFile().c_str());
    }
    while (!scan_it->Done()) {
        if (FLAGS_pipe == "streaming") {
            std::cout << scan_it->Value() << std::endl;
        } else {
            std::cout << scan_it->Value();
        }
        scan_it->Next();
    }
    if (scan_it->Error() != kOk && scan_it->Error() != kNoMore) {
        LOG(FATAL, "fail to scan: %s", reader.GetErrorFile().c_str());
    }
    reader.Close();
}

int main(int argc, char* argv[]) {
    baidu::common::SetLogFile(GetLogName("./shuffle_tool.log").c_str());
    baidu::common::SetWarningFile(GetLogName("./shuffle_tool.log.wf").c_str());
    google::ParseCommandLineFlags(&argc, &argv, true);
    FileSystem::Param param;
    FillParam(param);
    g_fs = FileSystem::CreateInfHdfs(param);
    if (FLAGS_total == 0 ) {
        LOG(FATAL, "invalid map task total");
    }
    while (!FLAGS_skip_merge && (int32_t)g_merged.size() < FLAGS_total) {
        std::vector<std::string> maps_to_merge;
        CollectFilesToMerge(&maps_to_merge);
        if (maps_to_merge.empty()) {
            LOG(INFO, "map output is empty, wait 10 seconds and try...");
            sleep(10);
            continue;
        }
        if (maps_to_merge.size() >= (size_t)FLAGS_batch ||
            maps_to_merge.size() + g_merged.size() >= (size_t)FLAGS_total) {
            LOG(INFO, "try merge %d maps", maps_to_merge.size());
            std::random_shuffle(maps_to_merge.begin(), maps_to_merge.end());
            MergeMapOutput(maps_to_merge);
        } else {
            LOG(INFO, "merged: %d, wait-for merge: %d", g_merged.size(), maps_to_merge.size());
            LOG(INFO, "wait for enough map-output to merge, sleep 5 second");
            sleep(5);
        }
        LOG(INFO, "merge progress: < %d/%d > ", g_merged.size(), FLAGS_total);
    }
    LOG(INFO, "merge and print out");
    MergeAndPrint();
    return 0;
}
<|endoftext|>


<commit_before>#include "game_state.hpp"

#include "start_game_state.hpp"
#include "imove.hpp"
#include "walk_move.hpp"
#include "wall_move.hpp"
#include "logger.hpp"
#include "exception.hpp"

static boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;

namespace Quoridor {

static std::vector<std::string> colors = {"red", "green", "blue", "yellow"};
std::string GameState::name_("Start Game");

GameState::GameState(std::shared_ptr<StateManager> stm,
        const std::vector<std::string> &player_types) : stm_(stm),
    board_(new Board(9)), pf_(), players_(), pawn_list_(), cur_pawn_(),
    repr_(), is_running_(true)
{
    CEGUI::ImageManager::getSingleton().loadImageset("pawn.imageset");
    win_ = std::shared_ptr<CEGUI::Window>(
            CEGUI::WindowManager::getSingleton().
                    loadLayoutFromFile("game.layout"),
            [=](CEGUI::Window *w) {
                BOOST_LOG_SEV(lg, boost::log::trivial::debug) << "removing window " << w;
                CEGUI::WindowManager::getSingleton().destroyWindow(w);
            }
    );

    subscribe_for_events_();

    if ((player_types.size() != 2) && (player_types.size() != 4)) {
        throw Exception("Invalid number of players");
    }

    set_pawns_(player_types);

    int i = 0;
    for (auto player_type : player_types) {
        BOOST_LOG_SEV(lg, boost::log::trivial::info) << "adding player "
            << player_type;
        std::shared_ptr<Pawn> pawn(new Pawn(colors[i]));
        board_->add_pawn(pawn);
        players_[pawn] = pf_.make_player(player_type, board_, pawn);
        pawn_list_.push_back(pawn);
        ++i;
    }

    cur_pawn_ = pawn_list_[0];

    init_board_repr();
}

GameState::~GameState()
{
}

void GameState::update()
{
    IMove *move;

    if (!is_running_) {
        return;
    }

    // if (!players_[cur_pawn_]->is_interactive()) {
        move = players_[cur_pawn_]->get_move();
    // }
    if (move != NULL) {
        Pos cur_node = board_->pawn_node(cur_pawn_);
        int rc;

        if (WalkMove *walk_move = dynamic_cast<WalkMove*>(move)) {
            BOOST_LOG_SEV(lg, boost::log::trivial::info) << cur_pawn_->color()
                << " move: " << walk_move->node().row() << ":"
                << walk_move->node().col();
            rc = board_->make_walking_move(cur_pawn_, walk_move->node());
            if (rc == 0) {
                Pos goal_node = board_->pawn_node(cur_pawn_);
                redraw_pawn(cur_pawn_->color()[0], cur_node, goal_node);
            }
        }
        else if (WallMove *wall_move = dynamic_cast<WallMove*>(move)) {
            const Wall &wall = wall_move->wall();
            rc = board_->add_wall(wall);
            if (rc == 0) {
                draw_wall(wall);
            }
        }

        if (board_->is_at_goal_node(cur_pawn_)) {
            BOOST_LOG_SEV(lg, boost::log::trivial::info) << cur_pawn_->color()
                << " win";
            is_running_ = false;
        }
        else if (rc == 0) {
            cur_pawn_ = next_pawn();
        }
    }
}

std::shared_ptr<CEGUI::Window> GameState::window() const
{
    return win_;
}

const std::string &GameState::name() const
{
    return name_;
}

void GameState::set_pawns_(const std::vector<std::string> &player_types)
{
    auto w1 = CEGUI::WindowManager::getSingleton().loadLayoutFromFile("pawn_anim.layout");
    win_->getChild("boardWindow/field_0_4")->addChild(w1);
    auto w2 = CEGUI::WindowManager::getSingleton().loadLayoutFromFile("pawn_anim.layout");
    win_->getChild("boardWindow/field_8_4")->addChild(w2);

    if (player_types.size() == 4) {
        auto w1 = CEGUI::WindowManager::getSingleton().loadLayoutFromFile("pawn_anim.layout");
        win_->getChild("boardWindow/field_4_0")->addChild(w1);
        auto w2 = CEGUI::WindowManager::getSingleton().loadLayoutFromFile("pawn_anim.layout");
        win_->getChild("boardWindow/field_4_8")->addChild(w2);
    }
}

void GameState::subscribe_for_events_()
{
    win_->getChild("back")->subscribeEvent(
            CEGUI::Window::EventMouseClick,
            CEGUI::Event::Subscriber(
                    &GameState::handle_back_, this
            )
    );
    for (int i = 0; i < 9; ++i) {
        for (int j = 0; j < 9; ++j) {
            std::string field_name = "boardWindow/field_" + std::to_string(i) + "_"
                + std::to_string(j);
            win_->getChild(field_name)->subscribeEvent(
                    CEGUI::Window::EventDragDropItemDropped,
                    CEGUI::Event::Subscriber(
                            &GameState::handle_fields_, this
                    )
            );
        }
    }
}

bool GameState::handle_back_(const CEGUI::EventArgs &/* e */)
{
    BOOST_LOG_SEV(lg, boost::log::trivial::info) << "returning to start game menu";
    stm_->change_state(std::shared_ptr<IState>(new StartGameState(stm_)));
    return true;
}

bool GameState::handle_fields_(const CEGUI::EventArgs &e)
{
    const CEGUI::DragDropEventArgs &dde = static_cast<const CEGUI::DragDropEventArgs&>(e);
    if (!dde.window->getChildCount()) {
        dde.window->addChild(dde.dragDropItem);
        // dde.dragDropItem->setPosition(CEGUI::UVector2(CEGUI::UDim(0.05, 0), CEGUI::UDim(0.05, 0)));
    }
    return true;
}

void GameState::init_board_repr() const
{
    repr_.resize(19);
    for (int i = 0; i < 19; ++i) {
        repr_[i].resize(19);
        for (int j = 0; j < 19; ++j) {
            if (i % 2 == 1) {
                repr_[i][j] = (j % 2 == 0 ? '|' : ' ');
            }
            else {
                repr_[i][j] = (j % 2 == 0 ? ' ' : '_');
            }
        }
    }

    for (auto pawn : pawn_list_) {
        Pos pos = board_->pawn_node(pawn);
        repr_[pos.row() * 2 + 1][pos.col() * 2 + 1] = pawn->color()[0];
    }
}

void GameState::redraw_pawn(char p, const Pos &old_pos, const Pos &new_pos) const
{
    repr_[old_pos.row() * 2 + 1][old_pos.col() * 2 + 1] = ' ';
    repr_[new_pos.row() * 2 + 1][new_pos.col() * 2 + 1] = p;
}

void GameState::draw_wall(const Wall &wall) const
{
    if (wall.orientation() == 0) {
        for (int i = 0; i < wall.cnt(); ++i) {
            repr_[wall.line() * 2 + 2][(wall.start_pos() + i) * 2 + 1] = '=';
        }
    }
    else {
        for (int i = 0; i < wall.cnt(); ++i) {
            repr_[(wall.start_pos() + i) * 2 + 1][wall.line() * 2 + 2] = '$';
        }
    }
}

std::shared_ptr<Pawn> GameState::next_pawn() const
{
    auto it = pawn_list_.begin();
    for (;it != pawn_list_.end(); ++it) {
        if (*it == cur_pawn_) {
            break;
        }
    }
    if (++it == pawn_list_.end()) {
        return pawn_list_[0];
    }
    else {
        return *it;
    }
}

}  /* namespace Quoridor */
<commit_msg>Change pawn position on player moves<commit_after>#include "game_state.hpp"

#include "start_game_state.hpp"
#include "imove.hpp"
#include "walk_move.hpp"
#include "wall_move.hpp"
#include "logger.hpp"
#include "exception.hpp"

static boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;

namespace Quoridor {

static std::vector<std::string> colors = {"red", "green", "blue", "yellow"};
std::string GameState::name_("Start Game");

GameState::GameState(std::shared_ptr<StateManager> stm,
        const std::vector<std::string> &player_types) : stm_(stm),
    board_(new Board(9)), pf_(), players_(), pawn_list_(), cur_pawn_(),
    repr_(), is_running_(true)
{
    CEGUI::ImageManager::getSingleton().loadImageset("pawn.imageset");
    win_ = std::shared_ptr<CEGUI::Window>(
            CEGUI::WindowManager::getSingleton().
                    loadLayoutFromFile("game.layout"),
            [=](CEGUI::Window *w) {
                BOOST_LOG_SEV(lg, boost::log::trivial::debug) << "removing window " << w;
                CEGUI::WindowManager::getSingleton().destroyWindow(w);
            }
    );

    subscribe_for_events_();

    if ((player_types.size() != 2) && (player_types.size() != 4)) {
        throw Exception("Invalid number of players");
    }

    set_pawns_(player_types);

    int i = 0;
    for (auto player_type : player_types) {
        BOOST_LOG_SEV(lg, boost::log::trivial::info) << "adding player "
            << player_type;
        std::shared_ptr<Pawn> pawn(new Pawn(colors[i]));
        board_->add_pawn(pawn);
        players_[pawn] = pf_.make_player(player_type, board_, pawn);
        pawn_list_.push_back(pawn);
        ++i;
    }

    cur_pawn_ = pawn_list_[0];

    init_board_repr();
}

GameState::~GameState()
{
}

void GameState::update()
{
    IMove *move;

    if (!is_running_) {
        return;
    }

    // if (!players_[cur_pawn_]->is_interactive()) {
        move = players_[cur_pawn_]->get_move();
    // }
    if (move != NULL) {
        Pos cur_node = board_->pawn_node(cur_pawn_);
        int rc;

        if (WalkMove *walk_move = dynamic_cast<WalkMove*>(move)) {
            BOOST_LOG_SEV(lg, boost::log::trivial::info) << cur_pawn_->color()
                << " move: " << walk_move->node().row() << ":"
                << walk_move->node().col() << " -> " << cur_node.row() << ":"
                << cur_node.col();
            rc = board_->make_walking_move(cur_pawn_, walk_move->node());
            if (rc == 0) {
                Pos goal_node = board_->pawn_node(cur_pawn_);
                redraw_pawn(cur_pawn_->color()[0], cur_node, goal_node);
            }
        }
        else if (WallMove *wall_move = dynamic_cast<WallMove*>(move)) {
            const Wall &wall = wall_move->wall();
            rc = board_->add_wall(wall);
            if (rc == 0) {
                draw_wall(wall);
            }
        }

        if (board_->is_at_goal_node(cur_pawn_)) {
            BOOST_LOG_SEV(lg, boost::log::trivial::info) << cur_pawn_->color()
                << " win";
            is_running_ = false;
        }
        else if (rc == 0) {
            cur_pawn_ = next_pawn();
        }
    }
}

std::shared_ptr<CEGUI::Window> GameState::window() const
{
    return win_;
}

const std::string &GameState::name() const
{
    return name_;
}

void GameState::set_pawns_(const std::vector<std::string> &player_types)
{
    auto w1 = CEGUI::WindowManager::getSingleton().loadLayoutFromFile("pawn_anim.layout");
    win_->getChild("boardWindow/field_0_4")->addChild(w1);
    auto w2 = CEGUI::WindowManager::getSingleton().loadLayoutFromFile("pawn_anim.layout");
    win_->getChild("boardWindow/field_8_4")->addChild(w2);

    if (player_types.size() == 4) {
        auto w1 = CEGUI::WindowManager::getSingleton().loadLayoutFromFile("pawn_anim.layout");
        win_->getChild("boardWindow/field_4_0")->addChild(w1);
        auto w2 = CEGUI::WindowManager::getSingleton().loadLayoutFromFile("pawn_anim.layout");
        win_->getChild("boardWindow/field_4_8")->addChild(w2);
    }
}

void GameState::subscribe_for_events_()
{
    win_->getChild("back")->subscribeEvent(
            CEGUI::Window::EventMouseClick,
            CEGUI::Event::Subscriber(
                    &GameState::handle_back_, this
            )
    );
    for (int i = 0; i < 9; ++i) {
        for (int j = 0; j < 9; ++j) {
            std::string field_name = "boardWindow/field_" + std::to_string(i) + "_"
                + std::to_string(j);
            win_->getChild(field_name)->subscribeEvent(
                    CEGUI::Window::EventDragDropItemDropped,
                    CEGUI::Event::Subscriber(
                            &GameState::handle_fields_, this
                    )
            );
        }
    }
}

bool GameState::handle_back_(const CEGUI::EventArgs &/* e */)
{
    BOOST_LOG_SEV(lg, boost::log::trivial::info) << "returning to start game menu";
    stm_->change_state(std::shared_ptr<IState>(new StartGameState(stm_)));
    return true;
}

bool GameState::handle_fields_(const CEGUI::EventArgs &e)
{
    const CEGUI::DragDropEventArgs &dde = static_cast<const CEGUI::DragDropEventArgs&>(e);
    if (!dde.window->getChildCount()) {
        dde.window->addChild(dde.dragDropItem);
        // dde.dragDropItem->setPosition(CEGUI::UVector2(CEGUI::UDim(0.05, 0), CEGUI::UDim(0.05, 0)));
    }
    return true;
}

void GameState::init_board_repr() const
{
    repr_.resize(19);
    for (int i = 0; i < 19; ++i) {
        repr_[i].resize(19);
        for (int j = 0; j < 19; ++j) {
            if (i % 2 == 1) {
                repr_[i][j] = (j % 2 == 0 ? '|' : ' ');
            }
            else {
                repr_[i][j] = (j % 2 == 0 ? ' ' : '_');
            }
        }
    }

    for (auto pawn : pawn_list_) {
        Pos pos = board_->pawn_node(pawn);
        repr_[pos.row() * 2 + 1][pos.col() * 2 + 1] = pawn->color()[0];
    }
}

void GameState::redraw_pawn(char p, const Pos &old_pos, const Pos &new_pos) const
{
    std::string old_pos_field = "boardWindow/field_"
        + std::to_string(old_pos.row()) + "_"
        + std::to_string(old_pos.col());
    std::string new_pos_field = "boardWindow/field_"
        + std::to_string(new_pos.row()) + "_"
        + std::to_string(new_pos.col());

    auto pawn_win = win_->getChild(old_pos_field)->getChild("pawn");
    win_->getChild(old_pos_field)->removeChild(pawn_win);
    win_->getChild(new_pos_field)->addChild(pawn_win);

    repr_[old_pos.row() * 2 + 1][old_pos.col() * 2 + 1] = ' ';
    repr_[new_pos.row() * 2 + 1][new_pos.col() * 2 + 1] = p;
}

void GameState::draw_wall(const Wall &wall) const
{
    if (wall.orientation() == 0) {
        for (int i = 0; i < wall.cnt(); ++i) {
            repr_[wall.line() * 2 + 2][(wall.start_pos() + i) * 2 + 1] = '=';
        }
    }
    else {
        for (int i = 0; i < wall.cnt(); ++i) {
            repr_[(wall.start_pos() + i) * 2 + 1][wall.line() * 2 + 2] = '$';
        }
    }
}

std::shared_ptr<Pawn> GameState::next_pawn() const
{
    auto it = pawn_list_.begin();
    for (;it != pawn_list_.end(); ++it) {
        if (*it == cur_pawn_) {
            break;
        }
    }
    if (++it == pawn_list_.end()) {
        return pawn_list_[0];
    }
    else {
        return *it;
    }
}

}  /* namespace Quoridor */
<|endoftext|>


<commit_before>#include "resource.h"

int main(int argc, char **argv)
{
	//initializing allegro
    al_init();
    al_init_image_addon();
    al_init_primitives_addon();
    al_init_font_addon();
    al_init_ttf_addon();
    al_get_display_mode(al_get_num_display_modes()-1, &disp_data);
    //al_set_new_display_flags(ALLEGRO_FULLSCREEN);
    al_set_new_display_flags(ALLEGRO_WINDOWED);
    al_set_new_display_option(ALLEGRO_VSYNC, 1, ALLEGRO_SUGGEST);
    disp_data.width*=0.8;
    disp_data.height*=0.8;
    display=al_create_display(disp_data.width, disp_data.height);
	if(!display)
    {
        return -1;
    }
	al_clear_to_color(al_map_rgb(0, 0, 0));
    al_flip_display();
    al_install_keyboard();
    al_install_mouse();
    al_install_audio();
    al_init_acodec_addon();
    al_reserve_samples(5);
    al_set_target_bitmap(al_get_backbuffer(display));
    // allegro initialization

	// initializing lua
	lua_state = luaL_newstate();
	// opening libraries for lua, otherwise functions dont work
	luaL_openlibs(lua_state);
	// lua initialization

	// initializing box2d
	world.SetGravity(b2Vec2(0, -9.8));
	ContactListener worldContactListener;
	world.SetContactListener(&worldContactListener);
	const int tlx=0, tly=0, brx=10000, bry=disp_data.height;
    Box ground(tlx, bry-10, brx, bry);
    Box ceiling(tlx, tly, brx, 10);
    Box leftWall(tlx, tly, 10, bry);
    Box rightWall(brx-10, 0, brx, bry);
    Chain chn;
    chn.getResource()->registerChainShape(&chn, b2Vec2(0, 0),
                                          0, -PX_TO_M(bry)/3,
                                          PX_TO_M(brx)*1/10, -PX_TO_M(bry)*3/9,
                                          PX_TO_M(brx)*2/10, -PX_TO_M(bry)*5/9,
                                          PX_TO_M(brx)*3/10, -PX_TO_M(bry)*9/9,
                                          PX_TO_M(brx)*4/10, -PX_TO_M(bry)*6/9,
                                          PX_TO_M(brx)*5/10, -PX_TO_M(bry)*5/9,
                                          PX_TO_M(brx)*6/10, -PX_TO_M(bry)*3/9,
                                          PX_TO_M(brx)*7/10, -PX_TO_M(bry)*5/9,
                                          PX_TO_M(brx)*8/10, -PX_TO_M(bry)*8/9,
                                          PX_TO_M(brx)*9/10, -PX_TO_M(bry)*9/9,
                                          PX_TO_M(brx)*10/10, -PX_TO_M(bry)*7/9
                                          );
	// box2d initialization

    resource.initialize();
    sysGC.initialize();

    /*
    Lexer lex;
    Parser psr;
    auto ret=lex.generateTokens("\
                                if(y>-0.2 && x<=11)\n\
                                {\n\
                                    if(x<0.2)\n\
                                    {\n\
                                        activeBullet.move(0.4, 0.4)\n\
                                    }\n\
                                    else\n\
                                    {\n\
                                        activeBullet.move(0.4, 0)\n\
                                    }\n\
                                }\n\
                                else if(x>11 && y>=-8.2)\n\
                                {\n\
                                    if(y>-0.2)\n\
                                    {\n\
                                        activeBullet.move(0.4, -0.4)\n\
                                    }\n\
                                    else\n\
                                    {\n\
                                        activeBullet.move(0, -0.4)\n\
                                    }\n\
                                }\n\
                                else if(y<-8.2 && x>=0.2)\n\
                                {\n\
                                    if(x>11)\n\
                                    {\n\
                                        activeBullet.move(-0.4, -0.4)\n\
                                    }\n\
                                    else\n\
                                    {\n\
                                        activeBullet.move(-0.4, 0)\n\
                                    }\n\
                                }\n\
                                else if(x<0.2 && y<=-0.2)\n\
                                {\n\
                                    if(y<-8.2)\n\
                                    {\n\
                                        activeBullet.move(-0.4, 0.4)\n\
                                    }\n\
                                    else\n\
                                    {\n\
                                        activeBullet.move(0, 0.4)\n\
                                    }\n\
                                }\n\
                              ");
    std::cout<<"Errors: "<<ret<<std::endl;
    psr.parse(lex, "updatebullet", "x, y", "luascripts/");
    */

    activeBatbot=new Batbot*;
    activeBullet=new Projectile*;

    Frame game(Rect(0, 0, disp_data.width, disp_data.height), 0);
    Robot rob(ENTITYTYPE::CROWBOT, 0, b2Vec2(PX_TO_M(20), -PX_TO_M(20)), 0, &game);
    //Batbot *bat=make_batbot(0, b2Vec2(PX_TO_M(2000), -PX_TO_M(200)), 0, &game);

    lua_regmfunctions(lua_state, "FrameMT");
    lua_makemfunction(lua_state, "spawn_batbot", "FrameMT", Frame,
    {
        make_batbot(luaL_checkinteger(l, 1), b2Vec2(luaL_checknumber(l, 2), luaL_checknumber(l, 3)), luaL_checkinteger(l, 4), obj)->push(obj->getCamera()->midground);
        return 0;
    });
    lua_prepmfunctions(lua_state, "__game", "FrameMT", Frame, &game);

    lua_regmfunctions(lua_state, "RobotMT");
    lua_makemfunction(lua_state, "shoot", "RobotMT", Robot,
    {
        obj->shootProjectile(b2Vec2(0, 0), luaL_checknumber(l, 1), luaL_checknumber(l, 2));
        return 0;
    });
    lua_prepmfunctions(lua_state, "the_robot", "RobotMT", Robot, &rob);

    lua_regmfunctions(lua_state, "BulletMT");
    lua_makemfunction(lua_state, "move", "BulletMT", Projectile*,
    {
        (*obj)->move(b2Vec2(luaL_checknumber(l, 1), luaL_checknumber(l, 2)));
        return 0;
    });
    lua_prepmfunctions(lua_state, "activeBullet", "BulletMT", Projectile*, activeBullet);

    lua_regmfunctions(lua_state, "BatbotMT");
    lua_makemfunction(lua_state, "x", "BatbotMT", Batbot*,
    {
        lua_pushnumber(l, (*obj)->getX());
        return 1;
    });
    lua_makemfunction(lua_state, "y", "BatbotMT", Batbot*,
    {
        lua_pushnumber(l, (*obj)->getY());
        return 1;
    });
    lua_makemfunction(lua_state, "mass", "BatbotMT", Batbot*,
    {
        lua_pushnumber(l, (*obj)->getMass());
        return 1;
    });
    lua_makemfunction(lua_state, "move", "BatbotMT", Batbot*,
    {
        (*obj)->move(luaL_checknumber(l, 1), luaL_checknumber(l, 2));
        return 0;
    });
    lua_prepmfunctions(lua_state, "batbot", "BatbotMT", Batbot*, activeBatbot);

    lua_makelfunction(lua_state, "luascripts/updatelua.lua", "updatelua");
    lua_reglfunction(lua_state, "luascripts/userscript.lua");
    lua_reglfunction(lua_state, "luascripts/updatebullet.lua");
    lua_reglfunction(lua_state, "luascripts/updatebatbot.lua");
    /*
    luaE_beginmfunctions(lua_state, "RobotMT");
    luaE_regmfunctions();
    luaE_makemfunction("press", Robot,
                                     {
                                         obj->onKeyPress(luaL_checkint(l, 1), ALLEGRO_KEY_RIGHT, luaL_checkint(l, 2));
                                         return 0;
                                     });
    luaE_prepmfunctions("the_robot", Robot, &rob);
    luaE_endmfunctions();
    */
    rob.push(game.getCamera()->midground);
    //bat->push(game.getCamera()->midground);
    chn.push(game.getCamera()->background);
    ground.push(game.getCamera()->background);
    ceiling.push(game.getCamera()->background);
    leftWall.push(game.getCamera()->background);
    rightWall.push(game.getCamera()->background);
    game.addOnRestart([](FRAMETYPE){return true;}, [&rob, &game](){rob.push(game.getCamera()->midground);});
    //game.addOnRestart([](FRAMETYPE){return true;}, [&bat, &game](){bat->push(game.getCamera()->midground);});
    game.addOnRestart([](FRAMETYPE){return true;}, [&chn, &game](){chn.push(game.getCamera()->background);});
    game.addOnRestart([](FRAMETYPE){return true;}, [&ground, &game](){ground.push(game.getCamera()->background);});
    game.addOnRestart([](FRAMETYPE){return true;}, [&ceiling, &game](){ceiling.push(game.getCamera()->background);});
    game.addOnRestart([](FRAMETYPE){return true;}, [&leftWall, &game](){leftWall.push(game.getCamera()->background);});
    game.addOnRestart([](FRAMETYPE){return true;}, [&rightWall, &game](){rightWall.push(game.getCamera()->background);});
    game.addOnRestart([](FRAMETYPE){return true;}, [&rob, &game](){game.addObserver(&rob);});
    game.getCamera()->setCustomTranslate([&rob](Camera *camera_arg)
                                         {
                                             camera_arg->postset().postTranslate(b2Vec2(-rob.getPosition().x+PX_TO_M(disp_data.width)/2, 0/*-rob.getPosition().y-PX_TO_M(disp_data.height)*2/3*/));
                                         }
                                         );
    game.addObserver(&rob);
    game.start(FRAMETYPE::STARTSCREEN);
    std::chrono::steady_clock::time_point current_time;
    current_time=std::chrono::steady_clock::now();
    while(game)
    {
        //menu flickering caused by unlimited framerate?
        sysEvents[EVENTTYPE::COLLECTGARBAGE].fire();
        //lua_runlfunction(lua_state, "updatelua");
        game.delayTime(std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::steady_clock::now()-current_time).count());
        current_time=std::chrono::steady_clock::now();
        game.update();
        game.render();
        lua_runlfunction(lua_state, "userscript");
        al_flip_display();
    }
    rob.pull();
    delete activeBatbot;
    delete activeBullet;
    /*
    // Events example
    EventHandler *evHandler=new EventHandler([]()
                                             {
                                                 std::cout<<"Goodbye, World!\n";
                                             });
    sysEvents.addEventHandler(evHandler);
    evHandler->push(sysEvents[EVENTTYPE::INVALID]);
    evHandler->add(EVENTTYPE::INVALID);
    sysEvents[EVENTTYPE::INVALID].fire();
    */
    lua_close(lua_state);
    resource.cleanup();
    sysGC.cleanup();
    game.end();
    game.destroy();
    al_destroy_display(display);
    printf("End\n");

    return 0;
}
<commit_msg>more spacing fixes<commit_after>#include "resource.h"

int main(int argc, char **argv)
{
	//initializing allegro
    al_init();
    al_init_image_addon();
    al_init_primitives_addon();
    al_init_font_addon();
    al_init_ttf_addon();
    al_get_display_mode(al_get_num_display_modes()-1, &disp_data);
    //al_set_new_display_flags(ALLEGRO_FULLSCREEN);
    al_set_new_display_flags(ALLEGRO_WINDOWED);
    al_set_new_display_option(ALLEGRO_VSYNC, 1, ALLEGRO_SUGGEST);
    disp_data.width*=0.8;
    disp_data.height*=0.8;
    display=al_create_display(disp_data.width, disp_data.height);
	if(!display)
    {
        return -1;
    }
	al_clear_to_color(al_map_rgb(0, 0, 0));
    al_flip_display();
    al_install_keyboard();
    al_install_mouse();
    al_install_audio();
    al_init_acodec_addon();
    al_reserve_samples(5);
    al_set_target_bitmap(al_get_backbuffer(display));
    // allegro initialization

	// initializing lua
	lua_state = luaL_newstate();
	// opening libraries for lua, otherwise functions dont work
	luaL_openlibs(lua_state);
	// lua initialization

	// initializing box2d
	world.SetGravity(b2Vec2(0, -9.8));
	ContactListener worldContactListener;
	world.SetContactListener(&worldContactListener);
	const int tlx=0, tly=0, brx=10000, bry=disp_data.height;
    Box ground(tlx, bry-10, brx, bry);
    Box ceiling(tlx, tly, brx, 10);
    Box leftWall(tlx, tly, 10, bry);
    Box rightWall(brx-10, 0, brx, bry);
    Chain chn;
    chn.getResource()->registerChainShape(&chn, b2Vec2(0, 0),
        0, -PX_TO_M(bry)/3,
        PX_TO_M(brx)*1/10, -PX_TO_M(bry)*3/9,
        PX_TO_M(brx)*2/10, -PX_TO_M(bry)*5/9,
        PX_TO_M(brx)*3/10, -PX_TO_M(bry)*9/9,
        PX_TO_M(brx)*4/10, -PX_TO_M(bry)*6/9,
        PX_TO_M(brx)*5/10, -PX_TO_M(bry)*5/9,
        PX_TO_M(brx)*6/10, -PX_TO_M(bry)*3/9,
        PX_TO_M(brx)*7/10, -PX_TO_M(bry)*5/9,
        PX_TO_M(brx)*8/10, -PX_TO_M(bry)*8/9,
        PX_TO_M(brx)*9/10, -PX_TO_M(bry)*9/9,
        PX_TO_M(brx)*10/10, -PX_TO_M(bry)*7/9
                                          );
	// box2d initialization

    resource.initialize();
    sysGC.initialize();

    /*
    Lexer lex;
    Parser psr;
    auto ret=lex.generateTokens("\
    if(y>-0.2 && x<=11)\n\
    {\n\
        if(x<0.2)\n\
        {\n\
            activeBullet.move(0.4, 0.4)\n\
        }\n\
        else\n\
        {\n\
            activeBullet.move(0.4, 0)\n\
        }\n\
    }\n\
    else if(x>11 && y>=-8.2)\n\
    {\n\
        if(y>-0.2)\n\
        {\n\
            activeBullet.move(0.4, -0.4)\n\
        }\n\
        else\n\
        {\n\
            activeBullet.move(0, -0.4)\n\
        }\n\
    }\n\
    else if(y<-8.2 && x>=0.2)\n\
    {\n\
        if(x>11)\n\
        {\n\
            activeBullet.move(-0.4, -0.4)\n\
        }\n\
        else\n\
        {\n\
            activeBullet.move(-0.4, 0)\n\
        }\n\
    }\n\
    else if(x<0.2 && y<=-0.2)\n\
    {\n\
        if(y<-8.2)\n\
        {\n\
            activeBullet.move(-0.4, 0.4)\n\
        }\n\
        else\n\
        {\n\
            activeBullet.move(0, 0.4)\n\
        }\n\
    }\n\
                              ");
    std::cout<<"Errors: "<<ret<<std::endl;
    psr.parse(lex, "updatebullet", "x, y", "luascripts/");
    */

    activeBatbot=new Batbot*;
    activeBullet=new Projectile*;

    Frame game(Rect(0, 0, disp_data.width, disp_data.height), 0);
    Robot rob(ENTITYTYPE::CROWBOT, 0, b2Vec2(PX_TO_M(20), -PX_TO_M(20)), 0, &game);

    lua_regmfunctions(lua_state, "FrameMT");
    lua_makemfunction(lua_state, "spawn_batbot", "FrameMT", Frame,
    {
        make_batbot(luaL_checkinteger(l, 1), b2Vec2(luaL_checknumber(l, 2), luaL_checknumber(l, 3)), luaL_checkinteger(l, 4), obj)->push(obj->getCamera()->midground);
        return 0;
    });
    lua_prepmfunctions(lua_state, "__game", "FrameMT", Frame, &game);

    lua_regmfunctions(lua_state, "RobotMT");
    lua_makemfunction(lua_state, "shoot", "RobotMT", Robot,
    {
        obj->shootProjectile(b2Vec2(0, 0), luaL_checknumber(l, 1), luaL_checknumber(l, 2));
        return 0;
    });
    lua_prepmfunctions(lua_state, "the_robot", "RobotMT", Robot, &rob);

    lua_regmfunctions(lua_state, "BulletMT");
    lua_makemfunction(lua_state, "move", "BulletMT", Projectile*,
    {
        (*obj)->move(b2Vec2(luaL_checknumber(l, 1), luaL_checknumber(l, 2)));
        return 0;
    });
    lua_prepmfunctions(lua_state, "activeBullet", "BulletMT", Projectile*, activeBullet);

    lua_regmfunctions(lua_state, "BatbotMT");
    lua_makemfunction(lua_state, "x", "BatbotMT", Batbot*,
    {
        lua_pushnumber(l, (*obj)->getX());
        return 1;
    });
    lua_makemfunction(lua_state, "y", "BatbotMT", Batbot*,
    {
        lua_pushnumber(l, (*obj)->getY());
        return 1;
    });
    lua_makemfunction(lua_state, "mass", "BatbotMT", Batbot*,
    {
        lua_pushnumber(l, (*obj)->getMass());
        return 1;
    });
    lua_makemfunction(lua_state, "move", "BatbotMT", Batbot*,
    {
        (*obj)->move(luaL_checknumber(l, 1), luaL_checknumber(l, 2));
        return 0;
    });
    lua_prepmfunctions(lua_state, "batbot", "BatbotMT", Batbot*, activeBatbot);

    lua_makelfunction(lua_state, "luascripts/updatelua.lua", "updatelua");
    lua_reglfunction(lua_state, "luascripts/userscript.lua");
    lua_reglfunction(lua_state, "luascripts/updatebullet.lua");
    lua_reglfunction(lua_state, "luascripts/updatebatbot.lua");
    /*
    luaE_beginmfunctions(lua_state, "RobotMT");
    luaE_regmfunctions();
    luaE_makemfunction("press", Robot,
                                     {
                                         obj->onKeyPress(luaL_checkint(l, 1), ALLEGRO_KEY_RIGHT, luaL_checkint(l, 2));
                                         return 0;
                                     });
    luaE_prepmfunctions("the_robot", Robot, &rob);
    luaE_endmfunctions();
    */
    rob.push(game.getCamera()->midground);
    chn.push(game.getCamera()->background);
    ground.push(game.getCamera()->background);
    ceiling.push(game.getCamera()->background);
    leftWall.push(game.getCamera()->background);
    rightWall.push(game.getCamera()->background);
    game.addOnRestart([](FRAMETYPE){return true;}, [&rob, &game](){rob.push(game.getCamera()->midground);});
    game.addOnRestart([](FRAMETYPE){return true;}, [&chn, &game](){chn.push(game.getCamera()->background);});
    game.addOnRestart([](FRAMETYPE){return true;}, [&ground, &game](){ground.push(game.getCamera()->background);});
    game.addOnRestart([](FRAMETYPE){return true;}, [&ceiling, &game](){ceiling.push(game.getCamera()->background);});
    game.addOnRestart([](FRAMETYPE){return true;}, [&leftWall, &game](){leftWall.push(game.getCamera()->background);});
    game.addOnRestart([](FRAMETYPE){return true;}, [&rightWall, &game](){rightWall.push(game.getCamera()->background);});
    game.addOnRestart([](FRAMETYPE){return true;}, [&rob, &game](){game.addObserver(&rob);});
    game.getCamera()->setCustomTranslate([&rob](Camera *camera_arg)
    {
        camera_arg->postset().postTranslate(b2Vec2(-rob.getPosition().x+PX_TO_M(disp_data.width)/2, 0/*-rob.getPosition().y-PX_TO_M(disp_data.height)*2/3*/));
    }
                                         );
    game.addObserver(&rob);
    game.start(FRAMETYPE::STARTSCREEN);
    std::chrono::steady_clock::time_point current_time;
    current_time=std::chrono::steady_clock::now();
    while(game)
    {
        //menu flickering caused by unlimited framerate?
        sysEvents[EVENTTYPE::COLLECTGARBAGE].fire();
        //lua_runlfunction(lua_state, "updatelua");
        game.delayTime(std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::steady_clock::now()-current_time).count());
        current_time=std::chrono::steady_clock::now();
        game.update();
        game.render();
        lua_runlfunction(lua_state, "userscript");
        al_flip_display();
    }
    rob.pull();
    delete activeBatbot;
    delete activeBullet;
    lua_close(lua_state);
    resource.cleanup();
    sysGC.cleanup();
    game.end();
    game.destroy();
    al_destroy_display(display);
    printf("End\n");

    return 0;
}
<|endoftext|>


<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2010, Rice University
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * 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.
*   * Neither the name of the Rice University nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*  POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/

/* Author: Ioan Sucan */

#include <ompl/control/SpaceInformation.h>
#include <ompl/base/goals/GoalState.h>
#include <ompl/base/spaces/SE2StateSpace.h>
#include <ompl/control/spaces/RealVectorControlSpace.h>
#include <ompl/control/planners/kpiece/KPIECE1.h>
#include <ompl/control/planners/rrt/RRT.h>
#include <ompl/control/planners/est/EST.h>
#include <ompl/control/planners/syclop/SyclopRRT.h>
#include <ompl/control/planners/syclop/SyclopEST.h>
#include <ompl/control/planners/pdst/PDST.h>
#include <ompl/control/planners/syclop/GridDecomposition.h>
#include <ompl/control/SimpleSetup.h>
#include <ompl/config.h>
#include <iostream>

namespace ob = ompl::base;
namespace oc = ompl::control;

// a decomposition is only needed for SyclopRRT and SyclopEST
class MyDecomposition : public oc::GridDecomposition
{
public:
    MyDecomposition(const int length, const ob::RealVectorBounds& bounds)
        : GridDecomposition(length, 2, bounds)
    {
    }
    void project(const ob::State* s, std::vector<double>& coord) const override
    {
        coord.resize(2);
        coord[0] = s->as<ob::SE2StateSpace::StateType>()->getX();
        coord[1] = s->as<ob::SE2StateSpace::StateType>()->getY();
    }

    void sampleFullState(const ob::StateSamplerPtr& sampler, const std::vector<double>& coord, ob::State* s) const override
    {
        sampler->sampleUniform(s);
        s->as<ob::SE2StateSpace::StateType>()->setXY(coord[0], coord[1]);
    }
};

bool isStateValid(const oc::SpaceInformation *si, const ob::State *state)
{
    //    ob::ScopedState<ob::SE2StateSpace>
    // cast the abstract state type to the type we expect
    const auto *se2state = state->as<ob::SE2StateSpace::StateType>();

    // extract the first component of the state and cast it to what we expect
    const auto *pos = se2state->as<ob::RealVectorStateSpace::StateType>(0);

    // extract the second component of the state and cast it to what we expect
    const auto *rot = se2state->as<ob::SO2StateSpace::StateType>(1);

    // check validity of state defined by pos & rot

    // return a value that is always true but uses the two variables we define, so we avoid compiler warnings
    return si->satisfiesBounds(state) && (const void*)rot != (const void*)pos;
}

void propagate(const ob::State *start, const oc::Control *control, const double duration, ob::State *result)
{
    const auto *se2state = start->as<ob::SE2StateSpace::StateType>();
    const double* pos = se2state->as<ob::RealVectorStateSpace::StateType>(0)->values;
    const double rot = se2state->as<ob::SO2StateSpace::StateType>(1)->value;
    const double* ctrl = control->as<oc::RealVectorControlSpace::ControlType>()->values;

    result->as<ob::SE2StateSpace::StateType>()->setXY(
        pos[0] + ctrl[0] * duration * cos(rot),
        pos[1] + ctrl[0] * duration * sin(rot));
    result->as<ob::SE2StateSpace::StateType>()->setYaw(
        rot    + ctrl[1] * duration);
}

void plan()
{

    // construct the state space we are planning in
    auto space(std::make_shared<ob::SE2StateSpace>());

    // set the bounds for the R^2 part of SE(2)
    ob::RealVectorBounds bounds(2);
    bounds.setLow(-1);
    bounds.setHigh(1);

    space->setBounds(bounds);

    // create a control space
    auto cspace(std::make_shared<oc::RealVectorControlSpace>(space, 2));

    // set the bounds for the control space
    ob::RealVectorBounds cbounds(2);
    cbounds.setLow(-0.3);
    cbounds.setHigh(0.3);

    cspace->setBounds(cbounds);

    // construct an instance of  space information from this control space
    auto si(std::make_shared<oc::SpaceInformation>(space, cspace));

    // set state validity checking for this space
    si->setStateValidityChecker(
        [&si](const ob::State *state) { return isStateValid(si.get(), state); });

    // set the state propagation routine
    si->setStatePropagator(propagate);

    // create a start state
    ob::ScopedState<ob::SE2StateSpace> start(space);
    start->setX(-0.5);
    start->setY(0.0);
    start->setYaw(0.0);

    // create a goal state
    ob::ScopedState<ob::SE2StateSpace> goal(start);
    goal->setX(0.5);

    // create a problem instance
    auto pdef(std::make_shared<ob::ProblemDefinition>(si));

    // set the start and goal states
    pdef->setStartAndGoalStates(start, goal, 0.1);

    // create a planner for the defined space
    //auto planner(std::make_shared<oc::RRT>(si));
    //auto planner(std::make_shared<oc::EST>(si));
    //auto planner(std::make_shared<oc::KPIECE1>(si));
    auto decomp(std::make_shared<MyDecomposition>(32, bounds));
    auto planner(std::make_shared<oc::SyclopEST>(si, decomp));
    //auto planner(std::make_shared<oc::SyclopRRT>(si, decomp));

    // set the problem we are trying to solve for the planner
    planner->setProblemDefinition(pdef);

    // perform setup steps for the planner
    planner->setup();

    // print the settings for this space
    si->printSettings(std::cout);

    // print the problem settings
    pdef->print(std::cout);

    // attempt to solve the problem within one second of planning time
    ob::PlannerStatus solved = planner->ob::Planner::solve(10.0);

    if (solved)
    {
        // get the goal representation from the problem definition (not the same as the goal state)
        // and inquire about the found path
        ob::PathPtr path = pdef->getSolutionPath();
        std::cout << "Found solution:" << std::endl;

        // print the path to screen
        path->print(std::cout);
    }
    else
        std::cout << "No solution found" << std::endl;
}

void planWithSimpleSetup()
{
    // construct the state space we are planning in
    auto space(std::make_shared<ob::SE2StateSpace>());

    // set the bounds for the R^2 part of SE(2)
    ob::RealVectorBounds bounds(2);
    bounds.setLow(-1);
    bounds.setHigh(1);

    space->setBounds(bounds);

    // create a control space
    auto cspace(std::make_shared<oc::RealVectorControlSpace>(space, 2));

    // set the bounds for the control space
    ob::RealVectorBounds cbounds(2);
    cbounds.setLow(-0.3);
    cbounds.setHigh(0.3);

    cspace->setBounds(cbounds);

    // define a simple setup class
    oc::SimpleSetup ss(cspace);

    // set the state propagation routine
    ss.setStatePropagator(propagate);

    // set state validity checking for this space
    ss.setStateValidityChecker(
        [&ss](const ob::State *state) { return isStateValid(ss.getSpaceInformation().get(), state); });

    // create a start state
    ob::ScopedState<ob::SE2StateSpace> start(space);
    start->setX(-0.5);
    start->setY(0.0);
    start->setYaw(0.0);

    // create a  goal state; use the hard way to set the elements
    ob::ScopedState<ob::SE2StateSpace> goal(space);
    (*goal)[0]->as<ob::RealVectorStateSpace::StateType>()->values[0] = 0.0;
    (*goal)[0]->as<ob::RealVectorStateSpace::StateType>()->values[1] = 0.5;
    (*goal)[1]->as<ob::SO2StateSpace::StateType>()->value = 0.0;

    // set the start and goal states
    ss.setStartAndGoalStates(start, goal, 0.05);

    // ss.setPlanner(std::make_shared<oc::PDST>(ss.getSpaceInformation()));
    // ss.getSpaceInformation()->setMinMaxControlDuration(1,100);
    // attempt to solve the problem within one second of planning time
    ob::PlannerStatus solved = ss.solve(10.0);

    if (solved)
    {
        std::cout << "Found solution:" << std::endl;
        // print the path to screen

        ss.getSolutionPath().printAsMatrix(std::cout);
    }
    else
        std::cout << "No solution found" << std::endl;
}

int main(int /*argc*/, char ** /*argv*/)
{
    std::cout << "OMPL version: " << OMPL_VERSION << std::endl;

    // plan();
    //
    // std::cout << std::endl << std::endl;
    //
    planWithSimpleSetup();

    return 0;
}
<commit_msg>fixed comment about seconds.<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2010, Rice University
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * 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.
*   * Neither the name of the Rice University nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*  POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/

/* Author: Ioan Sucan */

#include <ompl/control/SpaceInformation.h>
#include <ompl/base/goals/GoalState.h>
#include <ompl/base/spaces/SE2StateSpace.h>
#include <ompl/control/spaces/RealVectorControlSpace.h>
#include <ompl/control/planners/kpiece/KPIECE1.h>
#include <ompl/control/planners/rrt/RRT.h>
#include <ompl/control/planners/est/EST.h>
#include <ompl/control/planners/syclop/SyclopRRT.h>
#include <ompl/control/planners/syclop/SyclopEST.h>
#include <ompl/control/planners/pdst/PDST.h>
#include <ompl/control/planners/syclop/GridDecomposition.h>
#include <ompl/control/SimpleSetup.h>
#include <ompl/config.h>
#include <iostream>

namespace ob = ompl::base;
namespace oc = ompl::control;

// a decomposition is only needed for SyclopRRT and SyclopEST
class MyDecomposition : public oc::GridDecomposition
{
public:
    MyDecomposition(const int length, const ob::RealVectorBounds& bounds)
        : GridDecomposition(length, 2, bounds)
    {
    }
    void project(const ob::State* s, std::vector<double>& coord) const override
    {
        coord.resize(2);
        coord[0] = s->as<ob::SE2StateSpace::StateType>()->getX();
        coord[1] = s->as<ob::SE2StateSpace::StateType>()->getY();
    }

    void sampleFullState(const ob::StateSamplerPtr& sampler, const std::vector<double>& coord, ob::State* s) const override
    {
        sampler->sampleUniform(s);
        s->as<ob::SE2StateSpace::StateType>()->setXY(coord[0], coord[1]);
    }
};

bool isStateValid(const oc::SpaceInformation *si, const ob::State *state)
{
    //    ob::ScopedState<ob::SE2StateSpace>
    // cast the abstract state type to the type we expect
    const auto *se2state = state->as<ob::SE2StateSpace::StateType>();

    // extract the first component of the state and cast it to what we expect
    const auto *pos = se2state->as<ob::RealVectorStateSpace::StateType>(0);

    // extract the second component of the state and cast it to what we expect
    const auto *rot = se2state->as<ob::SO2StateSpace::StateType>(1);

    // check validity of state defined by pos & rot

    // return a value that is always true but uses the two variables we define, so we avoid compiler warnings
    return si->satisfiesBounds(state) && (const void*)rot != (const void*)pos;
}

void propagate(const ob::State *start, const oc::Control *control, const double duration, ob::State *result)
{
    const auto *se2state = start->as<ob::SE2StateSpace::StateType>();
    const double* pos = se2state->as<ob::RealVectorStateSpace::StateType>(0)->values;
    const double rot = se2state->as<ob::SO2StateSpace::StateType>(1)->value;
    const double* ctrl = control->as<oc::RealVectorControlSpace::ControlType>()->values;

    result->as<ob::SE2StateSpace::StateType>()->setXY(
        pos[0] + ctrl[0] * duration * cos(rot),
        pos[1] + ctrl[0] * duration * sin(rot));
    result->as<ob::SE2StateSpace::StateType>()->setYaw(
        rot    + ctrl[1] * duration);
}

void plan()
{

    // construct the state space we are planning in
    auto space(std::make_shared<ob::SE2StateSpace>());

    // set the bounds for the R^2 part of SE(2)
    ob::RealVectorBounds bounds(2);
    bounds.setLow(-1);
    bounds.setHigh(1);

    space->setBounds(bounds);

    // create a control space
    auto cspace(std::make_shared<oc::RealVectorControlSpace>(space, 2));

    // set the bounds for the control space
    ob::RealVectorBounds cbounds(2);
    cbounds.setLow(-0.3);
    cbounds.setHigh(0.3);

    cspace->setBounds(cbounds);

    // construct an instance of  space information from this control space
    auto si(std::make_shared<oc::SpaceInformation>(space, cspace));

    // set state validity checking for this space
    si->setStateValidityChecker(
        [&si](const ob::State *state) { return isStateValid(si.get(), state); });

    // set the state propagation routine
    si->setStatePropagator(propagate);

    // create a start state
    ob::ScopedState<ob::SE2StateSpace> start(space);
    start->setX(-0.5);
    start->setY(0.0);
    start->setYaw(0.0);

    // create a goal state
    ob::ScopedState<ob::SE2StateSpace> goal(start);
    goal->setX(0.5);

    // create a problem instance
    auto pdef(std::make_shared<ob::ProblemDefinition>(si));

    // set the start and goal states
    pdef->setStartAndGoalStates(start, goal, 0.1);

    // create a planner for the defined space
    //auto planner(std::make_shared<oc::RRT>(si));
    //auto planner(std::make_shared<oc::EST>(si));
    //auto planner(std::make_shared<oc::KPIECE1>(si));
    auto decomp(std::make_shared<MyDecomposition>(32, bounds));
    auto planner(std::make_shared<oc::SyclopEST>(si, decomp));
    //auto planner(std::make_shared<oc::SyclopRRT>(si, decomp));

    // set the problem we are trying to solve for the planner
    planner->setProblemDefinition(pdef);

    // perform setup steps for the planner
    planner->setup();

    // print the settings for this space
    si->printSettings(std::cout);

    // print the problem settings
    pdef->print(std::cout);

    // attempt to solve the problem within ten seconds of planning time
    ob::PlannerStatus solved = planner->ob::Planner::solve(10.0);

    if (solved)
    {
        // get the goal representation from the problem definition (not the same as the goal state)
        // and inquire about the found path
        ob::PathPtr path = pdef->getSolutionPath();
        std::cout << "Found solution:" << std::endl;

        // print the path to screen
        path->print(std::cout);
    }
    else
        std::cout << "No solution found" << std::endl;
}

void planWithSimpleSetup()
{
    // construct the state space we are planning in
    auto space(std::make_shared<ob::SE2StateSpace>());

    // set the bounds for the R^2 part of SE(2)
    ob::RealVectorBounds bounds(2);
    bounds.setLow(-1);
    bounds.setHigh(1);

    space->setBounds(bounds);

    // create a control space
    auto cspace(std::make_shared<oc::RealVectorControlSpace>(space, 2));

    // set the bounds for the control space
    ob::RealVectorBounds cbounds(2);
    cbounds.setLow(-0.3);
    cbounds.setHigh(0.3);

    cspace->setBounds(cbounds);

    // define a simple setup class
    oc::SimpleSetup ss(cspace);

    // set the state propagation routine
    ss.setStatePropagator(propagate);

    // set state validity checking for this space
    ss.setStateValidityChecker(
        [&ss](const ob::State *state) { return isStateValid(ss.getSpaceInformation().get(), state); });

    // create a start state
    ob::ScopedState<ob::SE2StateSpace> start(space);
    start->setX(-0.5);
    start->setY(0.0);
    start->setYaw(0.0);

    // create a  goal state; use the hard way to set the elements
    ob::ScopedState<ob::SE2StateSpace> goal(space);
    (*goal)[0]->as<ob::RealVectorStateSpace::StateType>()->values[0] = 0.0;
    (*goal)[0]->as<ob::RealVectorStateSpace::StateType>()->values[1] = 0.5;
    (*goal)[1]->as<ob::SO2StateSpace::StateType>()->value = 0.0;

    // set the start and goal states
    ss.setStartAndGoalStates(start, goal, 0.05);

    // ss.setPlanner(std::make_shared<oc::PDST>(ss.getSpaceInformation()));
    // ss.getSpaceInformation()->setMinMaxControlDuration(1,100);
    // attempt to solve the problem within one second of planning time
    ob::PlannerStatus solved = ss.solve(10.0);

    if (solved)
    {
        std::cout << "Found solution:" << std::endl;
        // print the path to screen

        ss.getSolutionPath().printAsMatrix(std::cout);
    }
    else
        std::cout << "No solution found" << std::endl;
}

int main(int /*argc*/, char ** /*argv*/)
{
    std::cout << "OMPL version: " << OMPL_VERSION << std::endl;

    // plan();
    //
    // std::cout << std::endl << std::endl;
    //
    planWithSimpleSetup();

    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: segmentedname.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 14:42:58 $
 *
 *  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 ARY_SEGMENTEDNAME_HXX
#define ARY_SEGMENTEDNAME_HXX

// USED SERVICES
    // BASE CLASSES
    // OTHER

namespace ary
{
namespace sn    // segmented name
{

/** One segment in a name like "::global::abc<hello,xy>::def".
    A segment being the part between "::"s.

    @collab implements ->SegmentedName
*/
class NameSegment
{
  public:
    explicit            NameSegment(
                            const char *        i_name );
    explicit            NameSegment(
                            const String &      i_name );
    explicit            NameSegment(
                            const NameSegment & i_segment );
                        ~NameSegment();
    // OPERATORS
    NameSegment &       operator=(
                            const NameSegment & i_other );
    bool                operator<(
                            const NameSegment & i_other ) const;
    // OPERATIONS
    String &            Make_Template();

    // INQUIRY
    const String  &     Name() const;
    const String *      TemplateArguments() const;

    void                Get_Text(
                            StreamStr &         o_out ) const;
  private:
    // DATA
    String              sName;
    Dyn<String>         pTemplateArguments;
};

typedef std::vector<NameSegment>        NameChain;

}   // namespace sn

/** A name of the form "::global::abc<hello,xy>::def".
*/
class SegmentedName
{
  public:
    explicit            SegmentedName(
                            const char *        i_text );
    explicit            SegmentedName(
                            const String &      i_text );
                        ~SegmentedName();
    // OPERATIONS
    bool                operator<(
                            const SegmentedName &
                                                i_other ) const;

    // INQUIRY
    bool                IsAbsolute() const;
    const sn::NameChain &
                        Sequence() const;

    void                Get_Text(
                            StreamStr &         o_out ) const;
  private:
    void                Interpret_Text(
                            const char *        i_text ); /// [valid C++ or IDL name].

    // DATA
    sn::NameChain       aSegments;
    bool                bIsAbsolute;
};

// IMPLEMENTATION
namespace sn
{

inline const String  &
NameSegment::Name() const
{
    return sName;
}

inline const String *
NameSegment::TemplateArguments() const
{
    return pTemplateArguments.Ptr();
}

}   // namespace sn

inline bool
SegmentedName::IsAbsolute() const
{
    return bIsAbsolute;
}

inline const sn::NameChain &
SegmentedName::Sequence() const
{
    return aSegments;
}

}   // namespace ary
#endif
<commit_msg>INTEGRATION: CWS cmcfixes39 (1.2.4); FILE MERGED 2007/11/20 09:48:25 cmc 1.2.4.1: #i83486# stlportism -> stl<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: segmentedname.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2007-12-12 14:56:07 $
 *
 *  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 ARY_SEGMENTEDNAME_HXX
#define ARY_SEGMENTEDNAME_HXX

// USED SERVICES
    // BASE CLASSES
    // OTHER

namespace ary
{
namespace sn    // segmented name
{

/** One segment in a name like "::global::abc<hello,xy>::def".
    A segment being the part between "::"s.

    @collab implements ->SegmentedName
*/
class NameSegment
{
  public:
    explicit            NameSegment(
                            const char *        i_name );
    explicit            NameSegment(
                            const String &      i_name );
                        NameSegment(
                            const NameSegment & i_segment );
                        ~NameSegment();
    // OPERATORS
    NameSegment &       operator=(
                            const NameSegment & i_other );
    bool                operator<(
                            const NameSegment & i_other ) const;
    // OPERATIONS
    String &            Make_Template();

    // INQUIRY
    const String  &     Name() const;
    const String *      TemplateArguments() const;

    void                Get_Text(
                            StreamStr &         o_out ) const;
  private:
    // DATA
    String              sName;
    Dyn<String>         pTemplateArguments;
};

typedef std::vector<NameSegment>        NameChain;

}   // namespace sn

/** A name of the form "::global::abc<hello,xy>::def".
*/
class SegmentedName
{
  public:
    explicit            SegmentedName(
                            const char *        i_text );
    explicit            SegmentedName(
                            const String &      i_text );
                        ~SegmentedName();
    // OPERATIONS
    bool                operator<(
                            const SegmentedName &
                                                i_other ) const;

    // INQUIRY
    bool                IsAbsolute() const;
    const sn::NameChain &
                        Sequence() const;

    void                Get_Text(
                            StreamStr &         o_out ) const;
  private:
    void                Interpret_Text(
                            const char *        i_text ); /// [valid C++ or IDL name].

    // DATA
    sn::NameChain       aSegments;
    bool                bIsAbsolute;
};

// IMPLEMENTATION
namespace sn
{

inline const String  &
NameSegment::Name() const
{
    return sName;
}

inline const String *
NameSegment::TemplateArguments() const
{
    return pTemplateArguments.Ptr();
}

}   // namespace sn

inline bool
SegmentedName::IsAbsolute() const
{
    return bIsAbsolute;
}

inline const sn::NameChain &
SegmentedName::Sequence() const
{
    return aSegments;
}

}   // namespace ary
#endif
<|endoftext|>