<commit_before>#include <limits.h>
#include <manyclaw/manyclaw.h>
#include "gtest/gtest.h"

::testing::AssertionResult ArraysMatch(const real *expected,
                                       const real *actual, int size){
  for (int i=0; i < size; ++i){
    if (fabs(expected[i] - actual[i]) > 1e-8){
      return ::testing::AssertionFailure() << "array[" << i
                                           << "] (" << actual[i] << ") != expected[" << i
                                           << "] (" << expected[i] << ")";
    }
  }

  return ::testing::AssertionSuccess();
}

// Test the indexer methods
TEST(AdvectionStepper, base) {
  int nx = 5, ny = 5;
  int num_ghost = advection_rp_grid_params.num_ghost;
  int num_eqns = advection_rp_grid_params.num_eqn;
  int num_waves = advection_rp_grid_params.num_waves;
  FieldIndexer fi(nx, ny, num_ghost, num_eqns);
  EdgeFieldIndexer efi(nx, ny, num_ghost, num_eqns, num_waves);
  real q[fi.size()];
  real amdq[efi.size()], amdq_gold[efi.size()];
  real apdq[efi.size()], apdq_gold[efi.size()];
  real wave[efi.size()], wave_gold[efi.size()];
  real speed[efi.size()], speed_gold[efi.size()];

  for(int idx=0; idx < fi.row_size() * fi.col_size(); ++idx)
      q[idx] = 0.0;
  q[fi.idx(5, 5)] = 1.0;

  for(int idx=0; idx < fi.row_size() * fi.col_size(); ++idx) {
    wave_gold[idx] = 0.0;
    speed_gold[idx] = 1.0;
    amdq_gold[idx] = 0.0;
    apdq_gold[idx] = 0.0;
  }

  wave_gold[efi.left_edge(5,5)] = 1.0;
  speed_gold[efi.left_edge(5,5)] = 1.0;
  amdq_gold[efi.left_edge(5,5)] = 0.0;
  apdq_gold[efi.left_edge(5,5)] = 1.0;

  wave_gold[efi.right_edge(5,5)] = -1.0;
  speed_gold[efi.right_edge(5,5)] = 1.0;
  amdq_gold[efi.right_edge(5,5)] = 0.0;
  apdq_gold[efi.right_edge(5,5)] = -1.0;

  wave_gold[efi.down_edge(5,5)] = 1.0;
  speed_gold[efi.down_edge(5,5)] = 1.0;
  amdq_gold[efi.down_edge(5,5)] = 0.0;
  apdq_gold[efi.down_edge(5,5)] = 1.0;

  wave_gold[efi.up_edge(5,5)] = -1.0;
  speed_gold[efi.up_edge(5,5)] = 1.0;
  amdq_gold[efi.up_edge(5,5)] = 0.0;
  apdq_gold[efi.up_edge(5,5)] = -1.0;

  advection_rp_step_serial_cellwise(q, NULL, nx, ny, amdq, apdq, wave, speed);

  EXPECT_TRUE(ArraysMatch(wave_gold, wave, efi.size()));
  EXPECT_TRUE(ArraysMatch(speed_gold, speed, efi.size()));
  EXPECT_TRUE(ArraysMatch(amdq_gold, amdq, efi.size()));
  EXPECT_TRUE(ArraysMatch(apdq_gold, apdq, efi.size()));
}
<commit_msg>Making prettier test<commit_after>#include <limits.h>
#include <manyclaw/manyclaw.h>
#include "gtest/gtest.h"

::testing::AssertionResult ArraysMatch(const real *expected,
                                       const real *actual, int size){
  std::vector<int> bad_loc;
  for (int i=0; i < size; ++i){
    if (std::fabs(expected[i] - actual[i]) > 1e-8){
      bad_loc.push_back(i);
    }
  }

  if (bad_loc.size() > 0) {
    std::ostringstream fail;
    fail << std::endl;
    for(size_t i=0; i < bad_loc.size(); ++i){
      int idx = bad_loc[i];
      fail << std::scientific
           << "  array[" << idx
           << "] (" << actual[idx] << ") != expected[" << idx
           << "] (" << expected[idx] << ")\n";
    }
    fail << "  Num_wrong:" << bad_loc.size();
    return ::testing::AssertionFailure() << fail.str();
  }

  return ::testing::AssertionSuccess();
}

// Test the indexer methods
TEST(AdvectionStepper, base) {
  int nx = 5, ny = 5;
  int num_ghost = advection_rp_grid_params.num_ghost;
  int num_eqns = advection_rp_grid_params.num_eqn;
  int num_waves = advection_rp_grid_params.num_waves;
  FieldIndexer fi(nx, ny, num_ghost, num_eqns);
  EdgeFieldIndexer efi(nx, ny, num_ghost, num_eqns, num_waves);
  real q[fi.size()];
  real amdq[efi.size()], amdq_gold[efi.size()];
  real apdq[efi.size()], apdq_gold[efi.size()];
  real wave[efi.size()], wave_gold[efi.size()];
  real speed[efi.size()], speed_gold[efi.size()];

  for(int idx=0; idx < fi.row_size() * fi.col_size(); ++idx)
      q[idx] = 0.0;
  q[fi.idx(5, 5)] = 1.0;

  for(int idx=0; idx < fi.row_size() * fi.col_size(); ++idx) {
    wave_gold[idx] = 0.0;
    speed_gold[idx] = 1.0;
    amdq_gold[idx] = 0.0;
    apdq_gold[idx] = 0.0;
  }

  wave_gold[efi.left_edge(5,5)] = 1.0;
  speed_gold[efi.left_edge(5,5)] = 1.0;
  amdq_gold[efi.left_edge(5,5)] = 0.0;
  apdq_gold[efi.left_edge(5,5)] = 1.0;

  wave_gold[efi.right_edge(5,5)] = -1.0;
  speed_gold[efi.right_edge(5,5)] = 1.0;
  amdq_gold[efi.right_edge(5,5)] = 0.0;
  apdq_gold[efi.right_edge(5,5)] = -1.0;

  wave_gold[efi.down_edge(5,5)] = 1.0;
  speed_gold[efi.down_edge(5,5)] = 1.0;
  amdq_gold[efi.down_edge(5,5)] = 0.0;
  apdq_gold[efi.down_edge(5,5)] = 1.0;

  wave_gold[efi.up_edge(5,5)] = -1.0;
  speed_gold[efi.up_edge(5,5)] = 1.0;
  amdq_gold[efi.up_edge(5,5)] = 0.0;
  apdq_gold[efi.up_edge(5,5)] = -1.0;

  advection_rp_step_serial_cellwise(q, NULL, nx, ny, amdq, apdq, wave, speed);

  EXPECT_TRUE(ArraysMatch(wave, wave_gold, efi.size()));
  EXPECT_TRUE(ArraysMatch(speed, speed_gold, efi.size()));
  EXPECT_TRUE(ArraysMatch(amdq, amdq_gold, efi.size()));
  EXPECT_TRUE(ArraysMatch(apdq, apdq_gold, efi.size()));
}
<|endoftext|>


<commit_before>#include "game.hpp"

#include <iostream>
#include "exception.hpp"

namespace Quoridor {

Game::Game(Board *board) : board_(board), player_list_()
{
}

Game::~Game()
{
}

void Game::main_loop()
{
    while (true) {
        for (auto *player: player_list_) {
            make_move(player);
        }
    }
}

void Game::add_player(Player *player)
{
    int board_side = board_->next_side();
    player->set_board_side(board_side);
    pos_t pos;

    switch (board_side) {
    case 0:
        pos.first = 0;
        pos.second = 4;
        break;
    case 1:
        pos.first = 4;
        pos.second = 0;
        break;
    case 2:
        pos.first = 8;
        pos.second = 4;
        break;
    case 3:
        pos.first = 4;
        pos.second = 8;
        break;
    default:
        throw Exception();
    }
    player->set_pos(pos);
    board_->add_occupied(pos);
    player_list_.push_back(player);
}

void Game::make_move(Player *player)
{
    int move;
    while (true) {
        std::cout << "make move ";
        std::cin >> move;
        if ((move >= 0) && (move <= 4)) {
            break;
        }
    }

    pos_t fin_pos;
    move = (move + player->board_side()) % 4;
    if (board_->make_move(move, player->pos(), &fin_pos) == 0) {
        std::cout << player->name() << ": ("
            << player->pos().first << "," << player->pos().second << " => ("
            << fin_pos.first << "," << fin_pos.second << ")" << std::endl;

        board_->rm_occupied(player->pos());
        player->set_pos(fin_pos);
        board_->add_occupied(fin_pos);
    }
}

bool Game::is_win(const Player *player) const
{
    return board_->is_at_opposite_side(player->board_side(), player->pos());
}

}  /* namespace Quoridor */
<commit_msg>Check if player wins after each move.<commit_after>#include "game.hpp"

#include <iostream>
#include "exception.hpp"

namespace Quoridor {

Game::Game(Board *board) : board_(board), player_list_()
{
}

Game::~Game()
{
}

void Game::main_loop()
{
    while (true) {
        for (auto *player: player_list_) {
            make_move(player);
            if (is_win(player)) {
                std::cout << player->name() << " win" << std::endl;
            }
        }
    }
}

void Game::add_player(Player *player)
{
    int board_side = board_->next_side();
    player->set_board_side(board_side);
    pos_t pos;

    switch (board_side) {
    case 0:
        pos.first = 0;
        pos.second = 4;
        break;
    case 1:
        pos.first = 4;
        pos.second = 0;
        break;
    case 2:
        pos.first = 8;
        pos.second = 4;
        break;
    case 3:
        pos.first = 4;
        pos.second = 8;
        break;
    default:
        throw Exception();
    }
    player->set_pos(pos);
    board_->add_occupied(pos);
    player_list_.push_back(player);
}

void Game::make_move(Player *player)
{
    int move;
    while (true) {
        std::cout << "make move ";
        std::cin >> move;
        if ((move >= 0) && (move <= 4)) {
            break;
        }
    }

    pos_t fin_pos;
    move = (move + player->board_side()) % 4;
    if (board_->make_move(move, player->pos(), &fin_pos) == 0) {
        std::cout << player->name() << ": ("
            << player->pos().first << "," << player->pos().second << " => ("
            << fin_pos.first << "," << fin_pos.second << ")" << std::endl;

        board_->rm_occupied(player->pos());
        player->set_pos(fin_pos);
        board_->add_occupied(fin_pos);
    }
}

bool Game::is_win(const Player *player) const
{
    return board_->is_at_opposite_side(player->board_side(), player->pos());
}

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


<commit_before>#include <SDL/SDL.h>
#ifdef __APPLE__
#include <SDL_mixer/SDL_mixer.h>
#else
#include <SDL/SDL_mixer.h>
#endif

#include "main.h"
#include "game.h"
#include "map.h"
#include "hud.h"
#include "sprite.h"
extern int resetTimer;
extern SDL_Surface *screen;

Game::Game()
{

}

bool Game::hitTarget(Sprite *hero,Sprite *target,Map &map,Hud &hud)
{
	float deltax,deltay;
	float dist;
	deltax=target->x-hero->x;
	deltay=target->y-hero->y;
	dist=deltax*deltax+deltay*deltay;
	if(dist<32*32) {
		hero->score++;
		hud.animateScore(map.viewx,map.viewy,hero);
		return true;
	}
	return false;
}

void Game::mapReset(Map &map)
{
//	hero.reset(64,128);
//	baddie.reset(64,128);
//	i=(rand()%(map.getTilesAcross()-3))+2;
//	j=(rand()%(map.getTilesDown()-2))+1;
//	target.reset(32*i,32*j);
    int x,j;
    for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) {
        x=(rand()%(map.getTilesAcross()-3))+2;
        j=(rand()%(map.getTilesDown()-2))+1;
        Sprite *player=*p;
        player->reset(32*x, 32*j);
    }
    for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) {
        x=(rand()%(map.getTilesAcross()-3))+2;
        j=(rand()%(map.getTilesDown()-2))+1;
        Sprite *item=*p;
        item->reset(32*x, 32*j);
    }
//	map.calculateGradient(&target);
//	resetTimer=3000;
//	Mix_PauseMusic();
//	map.updateView(&target);
}

void Game::newGame(Map &map)
{
    //for (int i = 0; i < _playerList.size(); i++) {
    for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) {
        Sprite *player=*p;
        player->score = 0;
    }
    for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) {
        Sprite *item=*p;
        item->score = 0;
    }
	mapReset(map);
	playSound(S_START);
}

void Game::update(Map &map,Hud &hud)
{
	map.updatePhysics();
    for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) {
        Sprite *player=*p;
        player->updatePhysics(&map);
    }
    for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) {
        Sprite *item=*p;
        item->updatePhysics(&map);
    }
	//baddie.x=200;
//	if(resetTimer>0) {
//		resetTimer-=16;
//		if(resetTimer<=0) {
//			resetTimer=0;
//			Mix_ResumeMusic();
//		}
//	} else {
//		map.updateView(&hero); //, &baddie);
//	}
//	hud.update(&hero, &baddie);
//	if( hitTarget(&hero,&target,map,hud) || hitTarget(&baddie,&target,map,hud)) {
//		mapReset(map);
//		playSound(S_MATCH);
//		if(hud.leftScore>8 || hud.rightScore>8) gameMode=MODE_WINNER;
//	}
}

SDL_Surface *titleImage=0;
SDL_Surface *menuImage=0;
void Game::draw(Map &map,Hud &hud)
{
#ifdef _PSP
	oslStartDrawing();		//To be able to draw on the screen
#else
	static SDL_Surface *bgImage=0;
	//if(!bgImage) bgImage=IMG_Load("data/title.png");
	//if(bgImage) SDL_BlitSurface(bgImage,0,screen,0);
	//else
    SDL_FillRect(screen,0,SDL_MapRGB(screen->format,240,240,128));
#endif

	map.draw();		//Draw the images to the screen
    for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) {
        Sprite *player=*p;
        player->draw(map.viewx,map.viewy);
    }
    for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) {
        Sprite *item=*p;
        item->draw(map.viewx,map.viewy);
    }
	hud.draw();
	if( gameMode==MODE_TITLE) {
		if(!titleImage) titleImage=IMG_Load("data/title.png");
		if(titleImage) SDL_BlitSurface( titleImage, NULL, screen, NULL);
	} else {
		if(titleImage) SDL_FreeSurface( titleImage);
		titleImage=0;
	}
	if( gameMode==MODE_MENU) {
		if(!menuImage) menuImage=IMG_Load("data/menu.png");
		if(menuImage) SDL_BlitSurface( menuImage, NULL, screen, NULL);
	} else {
		if(menuImage) SDL_FreeSurface( menuImage);
		menuImage=0;
	}

#ifdef _PSP
	oslEndDrawing();		//Ends drawing mode

	oslEndFrame();
	oslSyncFrame();		//Synchronizes the screen
#else
	SDL_Flip(screen);
	static long before;
	long now=SDL_GetTicks();
	long delay=before+32-now;
	if(delay>0 && delay<60) SDL_Delay(delay);
	before=now;
#endif
}

void Game::handleUp(int key)
{

}

void Game::handleDown(int key)
{

}

void Game::addCharSprite(Sprite* spriteToAdd){
    _playerList.push_back(spriteToAdd);
    printf("Success\n");
}

void Game::addItemSprite(Sprite *spriteToAdd){
    _itemList.push_back(spriteToAdd);
}

<commit_msg>New Background<commit_after>#include <SDL/SDL.h>
#ifdef __APPLE__
#include <SDL_mixer/SDL_mixer.h>
#else
#include <SDL/SDL_mixer.h>
#endif

#include "main.h"
#include "game.h"
#include "map.h"
#include "hud.h"
#include "sprite.h"
extern int resetTimer;
extern SDL_Surface *screen;

Game::Game()
{

}

bool Game::hitTarget(Sprite *hero,Sprite *target,Map &map,Hud &hud)
{
	float deltax,deltay;
	float dist;
	deltax=target->x-hero->x;
	deltay=target->y-hero->y;
	dist=deltax*deltax+deltay*deltay;
	if(dist<32*32) {
		hero->score++;
		hud.animateScore(map.viewx,map.viewy,hero);
		return true;
	}
	return false;
}

void Game::mapReset(Map &map)
{
//	hero.reset(64,128);
//	baddie.reset(64,128);
//	i=(rand()%(map.getTilesAcross()-3))+2;
//	j=(rand()%(map.getTilesDown()-2))+1;
//	target.reset(32*i,32*j);
    int x,j;
    for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) {
        x=(rand()%(map.getTilesAcross()-3))+2;
        j=(rand()%(map.getTilesDown()-2))+1;
        Sprite *player=*p;
        player->reset(32*x, 32*j);
    }
    for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) {
        x=(rand()%(map.getTilesAcross()-3))+2;
        j=(rand()%(map.getTilesDown()-2))+1;
        Sprite *item=*p;
        item->reset(32*x, 32*j);
    }
//	map.calculateGradient(&target);
//	resetTimer=3000;
//	Mix_PauseMusic();
//	map.updateView(&target);
}

void Game::newGame(Map &map)
{
    //for (int i = 0; i < _playerList.size(); i++) {
    for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) {
        Sprite *player=*p;
        player->score = 0;
    }
    for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) {
        Sprite *item=*p;
        item->score = 0;
    }
	mapReset(map);
	playSound(S_START);
}

void Game::update(Map &map,Hud &hud)
{
	map.updatePhysics();
    for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) {
        Sprite *player=*p;
        player->updatePhysics(&map);
    }
    for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) {
        Sprite *item=*p;
        item->updatePhysics(&map);
    }
	//baddie.x=200;
//	if(resetTimer>0) {
//		resetTimer-=16;
//		if(resetTimer<=0) {
//			resetTimer=0;
//			Mix_ResumeMusic();
//		}
//	} else {
//		map.updateView(&hero); //, &baddie);
//	}
//	hud.update(&hero, &baddie);
//	if( hitTarget(&hero,&target,map,hud) || hitTarget(&baddie,&target,map,hud)) {
//		mapReset(map);
//		playSound(S_MATCH);
//		if(hud.leftScore>8 || hud.rightScore>8) gameMode=MODE_WINNER;
//	}
}

SDL_Surface *titleImage=0;
SDL_Surface *menuImage=0;
void Game::draw(Map &map,Hud &hud)
{
#ifdef _PSP
	oslStartDrawing();		//To be able to draw on the screen
#else
	static SDL_Surface *bgImage=0;
	//if(!bgImage) bgImage=IMG_Load("data/title.png");
	//if(bgImage) SDL_BlitSurface(bgImage,0,screen,0);
	//else
    SDL_FillRect(screen,0,SDL_MapRGB(screen->format,189, 237, 255));
#endif

	map.draw();		//Draw the images to the screen
    for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) {
        Sprite *player=*p;
        player->draw(map.viewx,map.viewy);
    }
    for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) {
        Sprite *item=*p;
        item->draw(map.viewx,map.viewy);
    }
	hud.draw();
	if( gameMode==MODE_TITLE) {
		if(!titleImage) titleImage=IMG_Load("data/title.png");
		if(titleImage) SDL_BlitSurface( titleImage, NULL, screen, NULL);
	} else {
		if(titleImage) SDL_FreeSurface( titleImage);
		titleImage=0;
	}
	if( gameMode==MODE_MENU) {
		if(!menuImage) menuImage=IMG_Load("data/menu.png");
		if(menuImage) SDL_BlitSurface( menuImage, NULL, screen, NULL);
	} else {
		if(menuImage) SDL_FreeSurface( menuImage);
		menuImage=0;
	}

#ifdef _PSP
	oslEndDrawing();		//Ends drawing mode

	oslEndFrame();
	oslSyncFrame();		//Synchronizes the screen
#else
	SDL_Flip(screen);
	static long before;
	long now=SDL_GetTicks();
	long delay=before+32-now;
	if(delay>0 && delay<60) SDL_Delay(delay);
	before=now;
#endif
}

void Game::handleUp(int key)
{

}

void Game::handleDown(int key)
{

}

void Game::addCharSprite(Sprite* spriteToAdd){
    _playerList.push_back(spriteToAdd);
    printf("Success\n");
}

void Game::addItemSprite(Sprite *spriteToAdd){
    _itemList.push_back(spriteToAdd);
}

<|endoftext|>


<commit_before>#include <PlatformSpecification.h>
#include <Framebuffer.h>
#include <Perlin.h>

#include <boost/chrono.hpp>
#include <boost/thread.hpp>
#include <boost/random.hpp>
#include <fstream>
#include <string>

#define WIDTH 700
#define HEIGHT 500
#define SIZE WIDTH * HEIGHT

struct InputData
{
  float Da;
  float Db;
  float f;
  float k;
  float delta;
};

struct SimData
{
  float a_current[SIZE];
  float b_current[SIZE];
  float a_buffer[SIZE];
  float b_buffer[SIZE];
};

std::string read_file(const char _filepath[])
{
  std::string output;
  std::ifstream file(_filepath);

  if(file.is_open())
  {
    std::string line;
    while(!file.eof())
    {
      std::getline(file, line);
      output.append(line + "\n");
    }
  }
  else
  {
    std::cout << "File could not be opened." << std::endl;
    exit(EXIT_FAILURE);
  }

  file.close();
  return output;
}

void opencl_error_check(const cl_int _error)
{
  if(_error != CL_SUCCESS)
  {
    std::cout << "OpenCL error: " << _error << std::endl;
    exit(EXIT_FAILURE);
  }
}

void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
  InputData *input = static_cast<InputData*>(glfwGetWindowUserPointer(window));

  if(action == GLFW_PRESS)
  {
    switch(key)
    {
      case GLFW_KEY_ESCAPE:
        glfwSetWindowShouldClose(window, GL_TRUE);
        break;
      case GLFW_KEY_Q:
        glfwSetWindowShouldClose(window, GL_TRUE);
        break;
      case GLFW_KEY_A:
        input->Da *= 1.25f;
        std::cout << input->Da << std::endl;
        break;
      case GLFW_KEY_Z:
        input->Da *= 0.8f;
        std::cout << input->Da << std::endl;
        break;
      case GLFW_KEY_S:
        input->Db *= 1.25f;
        std::cout << input->Db << std::endl;
        break;
      case GLFW_KEY_X:
        input->Db *= 0.8f;
        std::cout << input->Db << std::endl;
        break;
      case GLFW_KEY_D:
        input->f *= 1.25f;
        std::cout << "f = " << input->f << std::endl;
        break;
      case GLFW_KEY_C:
        input->f *= 0.8f;
        std::cout << "f = " << input->f << std::endl;
        break;
      case GLFW_KEY_F:
        input->k *= 1.25f;
        std::cout << "k = " << input->k << std::endl;
        break;
      case GLFW_KEY_V:
        input->k *= 0.8f;
        std::cout << "k = " << input->k << std::endl;
        break;
    }
  }
}

int mod(const int _a, const int _b)
{
  int value = _a % _b;
  if (value < 0)
    value += _b;
  return value;
}

float laplacian(const float* _array, const int _point, const int _width, const int _height)
{
  int xpos = _point % _width;
  int ypos = _point / _width;
  int positive_x = mod(xpos + 1, _width);
  int negative_x = mod(xpos - 1, _width);
  int positive_y = mod(ypos + 1, _height) * _width;
  int negative_y = mod(ypos - 1, _height) * _width;

  int index[] = {
    negative_x + positive_y, xpos + positive_y, positive_x + positive_y,
    negative_x + ypos * _width, xpos + ypos * _width, positive_x + ypos * _width,
    negative_x + negative_y, xpos + negative_y, positive_x + negative_y
  };

  float weight[] = {
    0.05f, 0.2f, 0.05f,
    0.2f, -1.f, 0.2f,
    0.05f, 0.2f, 0.05f
  };

  float output = _array[index[0]] * weight[0] + _array[index[1]] * weight[1] + _array[index[2]] * weight[2]
  + _array[index[3]] * weight[3] + _array[index[4]] * weight[4] + _array[index[5]] * weight[5]
  + _array[index[6]] * weight[6] + _array[index[7]] * weight[7] + _array[index[8]] * weight[8];

  return output;
}

int main(int argc, char const *argv[])
{
  InputData input;
  input.Da = 1.f;
  input.Db = 0.5f;
  input.f = 0.018f;
  input.k = 0.051f;
  input.delta = 0.8f;

  Framebuffer *framebuffer = new Framebuffer();

  GLFWwindow* window = framebuffer->init(WIDTH, HEIGHT, &input);
  glfwSetKeyCallback(window, keyCallback);

  Perlin perlin;
  SimData *data = new SimData;
  for(int i = 0; i < SIZE; ++i)
  {
    float xpos = i % WIDTH;
    float ypos = i / WIDTH;
    if(perlin.noise(xpos / 100, ypos / 100, 0) > 0.4f)
    {
      data->a_current[i] = 1.f;
      data->b_current[i] = 1.f;
      data->a_buffer[i] = 0.f;
      data->b_buffer[i] = 0.f;
    }
    else
    {
      data->a_current[i] = 1.f;
      data->b_current[i] = 0.f;
      data->a_buffer[i] = 0.f;
      data->b_buffer[i] = 0.f;
    }
  }

  float *image = new float[SIZE*3];
  for(int i = 0; i < SIZE; ++i)
  {
    image[i * 3 + 0] = data->a_current[i];
    image[i * 3 + 1] = data->a_current[i];
    image[i * 3 + 2] = data->a_current[i];
  }

  framebuffer->image(image, WIDTH, HEIGHT);

  // OpenCL setup starts here

  // Setup
  cl_platform_id platform_id;
  clGetPlatformIDs(1, &platform_id, NULL);
  cl_uint device_count;
  clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 0, NULL, &device_count);
  cl_device_id *device_ids = new cl_device_id[device_count];
  clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, device_count, device_ids, NULL);

  // Error code
  cl_int error = CL_SUCCESS;

  // Context creation
  const cl_context_properties context_properties[] = {
    CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(platform_id),
    0
  };
  cl_context context = clCreateContext(context_properties, device_count, device_ids, NULL, NULL, &error);
  opencl_error_check(error);

  // GLuint m_texture;
  // glGenTextures(1, &m_texture);
  // glBindTexture(GL_TEXTURE_2D, m_texture);
  // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
  // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
  // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_FLOAT, NULL);

  // Memory allocation
  cl_mem cMem_a = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float) * SIZE, data->a_current, &error);
  opencl_error_check(error);
  cl_mem cMem_b = clCreateBuffer(context, CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float) * SIZE, data->b_current, &error);
  opencl_error_check(error);
  cl_mem bMem_a = clCreateBuffer(context, CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float) * SIZE, data->a_buffer, &error);
  opencl_error_check(error);
  cl_mem bMem_b = clCreateBuffer(context, CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float) * SIZE, data->b_buffer, &error);
  opencl_error_check(error);
  // cl_mem mem = clCreateFromGLTexture(context, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, m_texture, &error);
  // opencl_error_check(error);

  // Load source file
  std::string file = read_file("kernals/image.cl");
  const char* source[] = {file.c_str()};

  // Build program
  cl_program program = clCreateProgramWithSource(context, 1, source, NULL, &error);
  opencl_error_check(error);
  error = clBuildProgram(program, device_count, device_ids, NULL, NULL, NULL);
  if(error != CL_SUCCESS)
  {
    char buffer[2048];
    clGetProgramBuildInfo(program, device_ids[0], CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, NULL);
    std::cout << buffer << std::endl;
    exit(EXIT_FAILURE);
  }

  // Resolution for kernal
  const float width = WIDTH;
  const float height = HEIGHT;

  // Create kernel one
  cl_kernel kernel_one = clCreateKernel(program, "square", &error);
  opencl_error_check(error);

  // Set argurments for kernel one
  clSetKernelArg(kernel_one, 0, sizeof(cl_mem), &cMem_a);
  clSetKernelArg(kernel_one, 1, sizeof(cl_mem), &cMem_b);
  clSetKernelArg(kernel_one, 2, sizeof(cl_mem), &bMem_a);
  clSetKernelArg(kernel_one, 3, sizeof(cl_mem), &bMem_b);
  clSetKernelArg(kernel_one, 4, sizeof(InputData), &input);
  clSetKernelArg(kernel_one, 5, sizeof(float), &width);
  clSetKernelArg(kernel_one, 6, sizeof(float), &height);

  // Create kernel two
  cl_kernel kernel_two = clCreateKernel(program, "square", &error);
  opencl_error_check(error);

  // Set argurments for kernel two
  clSetKernelArg(kernel_two, 0, sizeof(cl_mem), &bMem_a);
  clSetKernelArg(kernel_two, 1, sizeof(cl_mem), &bMem_b);
  clSetKernelArg(kernel_two, 2, sizeof(cl_mem), &cMem_a);
  clSetKernelArg(kernel_two, 3, sizeof(cl_mem), &cMem_b);
  clSetKernelArg(kernel_two, 4, sizeof(InputData), &input);
  clSetKernelArg(kernel_two, 5, sizeof(float), &width);
  clSetKernelArg(kernel_two, 6, sizeof(float), &height);

  // Create queue
  cl_command_queue queue = clCreateCommandQueue(context, device_ids[0], 0, &error);
  opencl_error_check(error);

  // OpenCL setup ends here

  framebuffer->bind();

  unsigned int iteration = 0;
  boost::chrono::milliseconds iteration_delta(static_cast<int>((1000.f / 60.f) * input.delta));

  while( !framebuffer->close() )
  {
    boost::chrono::high_resolution_clock::time_point timer_start = boost::chrono::high_resolution_clock::now();

    // for(int i = 0; i < SIZE; ++i)
    // {
    //   data->a_buffer[i] = data->a_current[i];
    //   data->b_buffer[i] = data->b_current[i];

    //   float reaction = data->a_buffer[i] * (data->b_buffer[i] * data->b_buffer[i]);
    //   data->a_current[i] = data->a_buffer[i] + (input.Da * laplacian(data->a_buffer, i, WIDTH, HEIGHT) - reaction + input.f * (1.f - data->a_buffer[i])) * input.delta;
    //   data->b_current[i] = data->b_buffer[i] + (input.Db * laplacian(data->b_buffer, i, WIDTH, HEIGHT) + reaction - (input.k + input.f) * data->b_buffer[i]) * input.delta;
    // }

    // Run queue
    std::size_t size[] = {SIZE};
    error = clEnqueueNDRangeKernel(queue, (iteration % 2) ? kernel_one : kernel_two, 1, 0, size, NULL, 0, NULL, NULL);
    opencl_error_check(error);

    // Get data from GPU
    error = clEnqueueReadBuffer(queue, cMem_a, CL_TRUE, 0, sizeof(float) * SIZE, data->a_current, 0, NULL, NULL);
    opencl_error_check(error);

    for(int i = 0; i < SIZE; ++i)
    {
      float current = image[i * 3 + 0];
      image[i * 3 + 0] = data->a_current[i];
      image[i * 3 + 1] = data->a_current[i];
      image[i * 3 + 2] = data->a_current[i];
    }

    framebuffer->image(image, WIDTH, HEIGHT);
    framebuffer->draw();

    std::string title = "Graphics Environment Iteration: " + std::to_string(++iteration);
    framebuffer->title(title);

    boost::chrono::high_resolution_clock::time_point timer_end = boost::chrono::high_resolution_clock::now();
    boost::chrono::milliseconds iteration_time(boost::chrono::duration_cast<boost::chrono::milliseconds>(timer_end - timer_start).count());
    if(iteration_time < iteration_delta)
    {
      boost::this_thread::sleep_for(iteration_delta - iteration_time);
    }
  }

  // Cleanup
  clReleaseCommandQueue(queue);
  clReleaseMemObject(bMem_b);
  clReleaseMemObject(bMem_a);
  clReleaseMemObject(cMem_b);
  clReleaseMemObject(cMem_a);
  clReleaseKernel(kernel_two);
  clReleaseKernel(kernel_one);
  clReleaseProgram(program);
  clReleaseContext(context);
  delete[] device_ids;

  delete data;
  delete framebuffer;
  delete[] image;

  exit(EXIT_SUCCESS);
}<commit_msg>Removed code for CPU simulation<commit_after>#include <PlatformSpecification.h>
#include <Framebuffer.h>
#include <Perlin.h>

#include <boost/chrono.hpp>
#include <boost/thread.hpp>
#include <boost/random.hpp>
#include <fstream>
#include <string>

#define WIDTH 700
#define HEIGHT 500
#define SIZE WIDTH * HEIGHT

struct InputData
{
  float Da;
  float Db;
  float f;
  float k;
  float delta;
};

struct SimData
{
  float a_current[SIZE];
  float b_current[SIZE];
  float a_buffer[SIZE];
  float b_buffer[SIZE];
};

std::string read_file(const char _filepath[])
{
  std::string output;
  std::ifstream file(_filepath);

  if(file.is_open())
  {
    std::string line;
    while(!file.eof())
    {
      std::getline(file, line);
      output.append(line + "\n");
    }
  }
  else
  {
    std::cout << "File could not be opened." << std::endl;
    exit(EXIT_FAILURE);
  }

  file.close();
  return output;
}

void opencl_error_check(const cl_int _error)
{
  if(_error != CL_SUCCESS)
  {
    std::cout << "OpenCL error: " << _error << std::endl;
    exit(EXIT_FAILURE);
  }
}

void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
  InputData *input = static_cast<InputData*>(glfwGetWindowUserPointer(window));

  if(action == GLFW_PRESS)
  {
    switch(key)
    {
      case GLFW_KEY_ESCAPE:
        glfwSetWindowShouldClose(window, GL_TRUE);
        break;
      case GLFW_KEY_Q:
        glfwSetWindowShouldClose(window, GL_TRUE);
        break;
      case GLFW_KEY_A:
        input->Da *= 1.25f;
        std::cout << input->Da << std::endl;
        break;
      case GLFW_KEY_Z:
        input->Da *= 0.8f;
        std::cout << input->Da << std::endl;
        break;
      case GLFW_KEY_S:
        input->Db *= 1.25f;
        std::cout << input->Db << std::endl;
        break;
      case GLFW_KEY_X:
        input->Db *= 0.8f;
        std::cout << input->Db << std::endl;
        break;
      case GLFW_KEY_D:
        input->f *= 1.25f;
        std::cout << "f = " << input->f << std::endl;
        break;
      case GLFW_KEY_C:
        input->f *= 0.8f;
        std::cout << "f = " << input->f << std::endl;
        break;
      case GLFW_KEY_F:
        input->k *= 1.25f;
        std::cout << "k = " << input->k << std::endl;
        break;
      case GLFW_KEY_V:
        input->k *= 0.8f;
        std::cout << "k = " << input->k << std::endl;
        break;
    }
  }
}

int main(int argc, char const *argv[])
{
  InputData input;
  input.Da = 1.f;
  input.Db = 0.5f;
  input.f = 0.018f;
  input.k = 0.051f;
  input.delta = 0.8f;

  Framebuffer *framebuffer = new Framebuffer();

  GLFWwindow* window = framebuffer->init(WIDTH, HEIGHT, &input);
  glfwSetKeyCallback(window, keyCallback);

  SimData *data = new SimData;
  float *image = new float[SIZE*3];

  Perlin perlin;
  for(int i = 0; i < SIZE; ++i)
  {
    float xpos = i % WIDTH;
    float ypos = i / WIDTH;

    if(perlin.noise(xpos / 100, ypos / 100, 0) > 0.4f)
    {
      data->a_current[i] = 1.f;
      data->b_current[i] = 1.f;
    }
    else
    {
      data->a_current[i] = 1.f;
      data->b_current[i] = 0.f;
    }

    data->a_buffer[i] = 0.f;
    data->b_buffer[i] = 0.f;
  }

  // OpenCL setup starts here

  // Setup
  cl_platform_id platform_id;
  clGetPlatformIDs(1, &platform_id, NULL);
  cl_uint device_count;
  clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 0, NULL, &device_count);
  cl_device_id *device_ids = new cl_device_id[device_count];
  clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, device_count, device_ids, NULL);

  // Error code
  cl_int error = CL_SUCCESS;

  // Context creation
  const cl_context_properties context_properties[] = {
    CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(platform_id),
    0
  };
  cl_context context = clCreateContext(context_properties, device_count, device_ids, NULL, NULL, &error);
  opencl_error_check(error);

  // GLuint m_texture;
  // glGenTextures(1, &m_texture);
  // glBindTexture(GL_TEXTURE_2D, m_texture);
  // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
  // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
  // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_FLOAT, NULL);

  // Memory allocation
  cl_mem cMem_a = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float) * SIZE, data->a_current, &error);
  opencl_error_check(error);
  cl_mem cMem_b = clCreateBuffer(context, CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float) * SIZE, data->b_current, &error);
  opencl_error_check(error);
  cl_mem bMem_a = clCreateBuffer(context, CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float) * SIZE, data->a_buffer, &error);
  opencl_error_check(error);
  cl_mem bMem_b = clCreateBuffer(context, CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float) * SIZE, data->b_buffer, &error);
  opencl_error_check(error);
  // cl_mem mem = clCreateFromGLTexture(context, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, m_texture, &error);
  // opencl_error_check(error);

  // Load source file
  std::string file = read_file("kernals/image.cl");
  const char* source[] = {file.c_str()};

  // Build program
  cl_program program = clCreateProgramWithSource(context, 1, source, NULL, &error);
  opencl_error_check(error);
  error = clBuildProgram(program, device_count, device_ids, NULL, NULL, NULL);
  if(error != CL_SUCCESS)
  {
    char buffer[1024];
    clGetProgramBuildInfo(program, device_ids[0], CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, NULL);
    std::cout << buffer << std::endl;
    exit(EXIT_FAILURE);
  }

  // Resolution for kernal
  const float width = WIDTH;
  const float height = HEIGHT;

  // Create kernel one
  cl_kernel kernel_one = clCreateKernel(program, "square", &error);
  opencl_error_check(error);

  // Set argurments for kernel one
  clSetKernelArg(kernel_one, 0, sizeof(cl_mem), &cMem_a);
  clSetKernelArg(kernel_one, 1, sizeof(cl_mem), &cMem_b);
  clSetKernelArg(kernel_one, 2, sizeof(cl_mem), &bMem_a);
  clSetKernelArg(kernel_one, 3, sizeof(cl_mem), &bMem_b);
  clSetKernelArg(kernel_one, 4, sizeof(InputData), &input);
  clSetKernelArg(kernel_one, 5, sizeof(float), &width);
  clSetKernelArg(kernel_one, 6, sizeof(float), &height);

  // Create kernel two
  cl_kernel kernel_two = clCreateKernel(program, "square", &error);
  opencl_error_check(error);

  // Set argurments for kernel two
  clSetKernelArg(kernel_two, 0, sizeof(cl_mem), &bMem_a);
  clSetKernelArg(kernel_two, 1, sizeof(cl_mem), &bMem_b);
  clSetKernelArg(kernel_two, 2, sizeof(cl_mem), &cMem_a);
  clSetKernelArg(kernel_two, 3, sizeof(cl_mem), &cMem_b);
  clSetKernelArg(kernel_two, 4, sizeof(InputData), &input);
  clSetKernelArg(kernel_two, 5, sizeof(float), &width);
  clSetKernelArg(kernel_two, 6, sizeof(float), &height);

  // Create queue
  cl_command_queue queue = clCreateCommandQueue(context, device_ids[0], 0, &error);
  opencl_error_check(error);

  // OpenCL setup ends here

  framebuffer->bind();
  unsigned int iteration = 0;
  boost::chrono::milliseconds iteration_delta(static_cast<int>((1000.f / 60.f) * input.delta));

  while( !framebuffer->close() )
  {
    boost::chrono::high_resolution_clock::time_point timer_start = boost::chrono::high_resolution_clock::now();

    // Run queue
    std::size_t size[] = {SIZE};
    error = clEnqueueNDRangeKernel(queue, (iteration % 2) ? kernel_one : kernel_two, 1, 0, size, NULL, 0, NULL, NULL);
    opencl_error_check(error);

    // Get data from GPU
    error = clEnqueueReadBuffer(queue, cMem_a, CL_TRUE, 0, sizeof(float) * SIZE, data->a_current, 0, NULL, NULL);
    opencl_error_check(error);

    for(int i = 0; i < SIZE; ++i)
    {
      float current = image[i * 3 + 0];
      image[i * 3 + 0] = data->a_current[i];
      image[i * 3 + 1] = data->a_current[i];
      image[i * 3 + 2] = data->a_current[i];
    }

    framebuffer->image(image, WIDTH, HEIGHT);
    framebuffer->draw();

    std::string title = "Graphics Environment Iteration: " + std::to_string(++iteration);
    framebuffer->title(title);

    boost::chrono::high_resolution_clock::time_point timer_end = boost::chrono::high_resolution_clock::now();
    boost::chrono::milliseconds iteration_time(boost::chrono::duration_cast<boost::chrono::milliseconds>(timer_end - timer_start).count());
    if(iteration_time < iteration_delta)
    {
      boost::this_thread::sleep_for(iteration_delta - iteration_time);
    }
  }

  // Cleanup
  clReleaseCommandQueue(queue);
  clReleaseMemObject(bMem_b);
  clReleaseMemObject(bMem_a);
  clReleaseMemObject(cMem_b);
  clReleaseMemObject(cMem_a);
  clReleaseKernel(kernel_two);
  clReleaseKernel(kernel_one);
  clReleaseProgram(program);
  clReleaseContext(context);
  delete[] device_ids;

  delete data;
  delete framebuffer;
  delete[] image;

  exit(EXIT_SUCCESS);
}<|endoftext|>


<commit_before>#include "math/Vector.hpp"
#include "mill_pdb.hpp"
#include "mill_dcd.hpp"
#include "mill_ninfo.hpp"
#include <iostream>

template<std::size_t MAJOR_V, std::size_t MINOR_V>
void print_logo();
void print_help();
void print_man();

int main(int argc, char **argv)
{
    print_logo<1, 0>();
    if(argc < 3)
    {
        print_help();
        return 1;
    }

    std::string mode(argv[1]);

    if(mode == "pdb")
    {
        try
        {
            return mill::mode_pdb<mill::Vector<double, 3>>(argc-1, ++argv);
        }
        catch(std::exception& excpt)
        {
            std::cerr << "exception thrown: " << excpt.what() << std::endl;
            return 1;
        }
    }
    else if(mode == "ninfo")
    {
        try
        {
            return mill::mode_ninfo<mill::Vector<double, 3>>(argc-1, ++argv);
        }
        catch(std::exception& excpt)
        {
            std::cerr << "exception thrown: " << excpt.what() << std::endl;
            return 1;
        }
    }
    else if(mode == "dcd")
    {
        try
        {
            return mill::mode_dcd<mill::Vector<double, 3>>(argc-1, ++argv);
        }
        catch(std::exception& excpt)
        {
            std::cerr << "exception thrown: " << excpt.what() << std::endl;
            return 1;
        }
    }
    else if(mode == "help")
    {
        print_help();
        return 1;
    }
    else
    {
        std::cerr << "unknown command: " << mode << std::endl;
        print_help();
        return 1;
    }
}

template<std::size_t MAJOR_V, std::size_t MINOR_V>
void print_logo()
{
// not escaped
//     std::cerr << "  ____        __  __             __    __ _  _  _  " << std::endl;
//     std::cerr << " / ___| ___  / _|/ _| ___  ___   | \  / |(_)| || | " << std::endl;
//     std::cerr << "| |    / _ \| |_| |_ / _ \/ _ \  |  \/  || || || | " << std::endl;
//     std::cerr << "| |___| (_) |  _|  _|  __|  __/  | |\/| || || || | " << std::endl;
//     std::cerr << " \____|\___/|_| |_|  \___|\___|  |_|  |_||_||_||_| " << std::endl;
    std::cerr << "  ___        __  __             __    __ _  _  _  "     << std::endl;
    std::cerr << " / __| ___  / _|/ _| ___  ___   | \\  / |(_)| || | "    << std::endl;
    std::cerr << "| |   / _ \\| |_| |_ / _ \\/ _ \\  |  \\/  || || || | " << std::endl;
    std::cerr << "| |__| (_) |  _|  _|  __|  __/  | |\\/| || || || | "    << std::endl;
    std::cerr << " \\___|\\___/|_| |_|  \\___|\\___|  |_|  |_||_||_||_| " << std::endl;
    std::cerr << "                                      version "
              << MAJOR_V << "." << MINOR_V << std::endl;
    std::cerr << "                         Copyright 2016 Toru Niina " << std::endl;
    std::cerr << std::endl;
    std::cerr << std::endl;

    return;
}

void print_help()
{
    std::cerr << "Usage: mill [mode] [job]" << std::endl;
    std::cerr << std::endl;
    std::cerr << "command-line interface" << std::endl;
    std::cerr << std::endl;
    std::cerr << "list of modes" << std::endl;
    std::cerr << "\t" << "pdb" << std::endl;
    std::cerr << "\t" << "dcd" << std::endl;
    std::cerr << "\t" << "ninfo" << std::endl;
    std::cerr << std::endl;
    std::cerr << "jobs"    << std::endl;
    std::cerr << "\t" << "seq" << std::endl;
    std::cerr << "\t" << "join" << std::endl;
    std::cerr << "\t" << "split" << std::endl;
    std::cerr << "\t" << "make-movie" << std::endl;
//     std::cerr << "\t" << JOB_SHOW         << std::endl;
//     std::cerr << "\t" << JOB_MUTATE       << std::endl;
//     std::cerr << "\t" << JOB_MAKE_CG      << std::endl;
//     std::cerr << "\t" << JOB_MAKE_NINFO   << std::endl;
    std::cerr << std::endl;
    std::cerr << "some combination of mode and job is not defined." << std::endl;
    std::cerr << "to see more information, run `mill --man`."       << std::endl;
    return;
}

void print_man()
{
    std::cerr << "\t\t\t\t Coffee Mill" << std::endl;

    std::cerr << "NAME" << std::endl;
    std::cerr << "\tcoffee mill - command line tools for using cafemol" << std::endl;

    std::cerr << std::endl;
    std::cerr << "SYNOPSIS" << std::endl;
    std::cerr << "\tmill [-h] {pdb | dcd | ninfo | dna}" << std::endl;
    std::cerr << std::endl;

    std::cerr << "DESCRIPTION" << std::endl;
    std::cerr << "\tcoffee mill is the command line tool for handling cafemol files."
              << std::endl;
    std::cerr << std::endl;

    std::cerr << "\tpdb" << std::endl;
    std::cerr << "\t\thandle pdb files. extract sequence, split for cafemol input, "
              << std::endl;
    std::cerr << "\t\tmake cg file, make ninfo file, etc..." << std::endl;
    std::cerr << std::endl;

    std::cerr << "\tdna" << std::endl;
    std::cerr << "\t\thandle dna sequence, mutate pdb file, etc..." << std::endl;
    std::cerr << std::endl;

    std::cerr << "\tdcd" << std::endl;
    std::cerr << "\t\thandle dcd files. make movie file, calculate some values, "
              << std::endl;
    std::cerr << "\t\tjoin some dcd files, etc..." << std::endl;
    std::cerr << std::endl;

    std::cerr << "\tninfo" << std::endl;
    std::cerr << "\t\thandle ninfo files. split ninfo files, show structure as XYZ file,"
              << std::endl;
    std::cerr << "\t\tetc..." << std::endl;

    return;
}
<commit_msg>change include path<commit_after>#include <mill/math/Vector.hpp>
#include "mill_pdb.hpp"
#include "mill_dcd.hpp"
#include "mill_ninfo.hpp"
#include <iostream>

template<std::size_t MAJOR_V, std::size_t MINOR_V>
void print_logo();
void print_help();
void print_man();

int main(int argc, char **argv)
{
    print_logo<1, 0>();
    if(argc < 3)
    {
        print_help();
        return 1;
    }

    std::string mode(argv[1]);

    if(mode == "pdb")
    {
        try
        {
            return mill::mode_pdb<mill::Vector<double, 3>>(argc-1, ++argv);
        }
        catch(std::exception& excpt)
        {
            std::cerr << "exception thrown: " << excpt.what() << std::endl;
            return 1;
        }
    }
    else if(mode == "ninfo")
    {
        try
        {
            return mill::mode_ninfo<mill::Vector<double, 3>>(argc-1, ++argv);
        }
        catch(std::exception& excpt)
        {
            std::cerr << "exception thrown: " << excpt.what() << std::endl;
            return 1;
        }
    }
    else if(mode == "dcd")
    {
        try
        {
            return mill::mode_dcd<mill::Vector<double, 3>>(argc-1, ++argv);
        }
        catch(std::exception& excpt)
        {
            std::cerr << "exception thrown: " << excpt.what() << std::endl;
            return 1;
        }
    }
    else if(mode == "help")
    {
        print_help();
        return 1;
    }
    else
    {
        std::cerr << "unknown command: " << mode << std::endl;
        print_help();
        return 1;
    }
}

template<std::size_t MAJOR_V, std::size_t MINOR_V>
void print_logo()
{
// not escaped
//     std::cerr << "  ____        __  __             __    __ _  _  _  " << std::endl;
//     std::cerr << " / ___| ___  / _|/ _| ___  ___   | \  / |(_)| || | " << std::endl;
//     std::cerr << "| |    / _ \| |_| |_ / _ \/ _ \  |  \/  || || || | " << std::endl;
//     std::cerr << "| |___| (_) |  _|  _|  __|  __/  | |\/| || || || | " << std::endl;
//     std::cerr << " \____|\___/|_| |_|  \___|\___|  |_|  |_||_||_||_| " << std::endl;
    std::cerr << "  ___        __  __             __    __ _  _  _  "     << std::endl;
    std::cerr << " / __| ___  / _|/ _| ___  ___   | \\  / |(_)| || | "    << std::endl;
    std::cerr << "| |   / _ \\| |_| |_ / _ \\/ _ \\  |  \\/  || || || | " << std::endl;
    std::cerr << "| |__| (_) |  _|  _|  __|  __/  | |\\/| || || || | "    << std::endl;
    std::cerr << " \\___|\\___/|_| |_|  \\___|\\___|  |_|  |_||_||_||_| " << std::endl;
    std::cerr << "                                      version "
              << MAJOR_V << "." << MINOR_V << std::endl;
    std::cerr << "                         Copyright 2016 Toru Niina " << std::endl;
    std::cerr << std::endl;
    std::cerr << std::endl;

    return;
}

void print_help()
{
    std::cerr << "Usage: mill [mode] [job]" << std::endl;
    std::cerr << std::endl;
    std::cerr << "command-line interface" << std::endl;
    std::cerr << std::endl;
    std::cerr << "list of modes" << std::endl;
    std::cerr << "\t" << "pdb" << std::endl;
    std::cerr << "\t" << "dcd" << std::endl;
    std::cerr << "\t" << "ninfo" << std::endl;
    std::cerr << std::endl;
    std::cerr << "jobs"    << std::endl;
    std::cerr << "\t" << "seq" << std::endl;
    std::cerr << "\t" << "join" << std::endl;
    std::cerr << "\t" << "split" << std::endl;
    std::cerr << "\t" << "make-movie" << std::endl;
//     std::cerr << "\t" << JOB_SHOW         << std::endl;
//     std::cerr << "\t" << JOB_MUTATE       << std::endl;
//     std::cerr << "\t" << JOB_MAKE_CG      << std::endl;
//     std::cerr << "\t" << JOB_MAKE_NINFO   << std::endl;
    std::cerr << std::endl;
    std::cerr << "some combination of mode and job is not defined." << std::endl;
    std::cerr << "to see more information, run `mill --man`."       << std::endl;
    return;
}

void print_man()
{
    std::cerr << "\t\t\t\t Coffee Mill" << std::endl;

    std::cerr << "NAME" << std::endl;
    std::cerr << "\tcoffee mill - command line tools for using cafemol" << std::endl;

    std::cerr << std::endl;
    std::cerr << "SYNOPSIS" << std::endl;
    std::cerr << "\tmill [-h] {pdb | dcd | ninfo | dna}" << std::endl;
    std::cerr << std::endl;

    std::cerr << "DESCRIPTION" << std::endl;
    std::cerr << "\tcoffee mill is the command line tool for handling cafemol files."
              << std::endl;
    std::cerr << std::endl;

    std::cerr << "\tpdb" << std::endl;
    std::cerr << "\t\thandle pdb files. extract sequence, split for cafemol input, "
              << std::endl;
    std::cerr << "\t\tmake cg file, make ninfo file, etc..." << std::endl;
    std::cerr << std::endl;

    std::cerr << "\tdna" << std::endl;
    std::cerr << "\t\thandle dna sequence, mutate pdb file, etc..." << std::endl;
    std::cerr << std::endl;

    std::cerr << "\tdcd" << std::endl;
    std::cerr << "\t\thandle dcd files. make movie file, calculate some values, "
              << std::endl;
    std::cerr << "\t\tjoin some dcd files, etc..." << std::endl;
    std::cerr << std::endl;

    std::cerr << "\tninfo" << std::endl;
    std::cerr << "\t\thandle ninfo files. split ninfo files, show structure as XYZ file,"
              << std::endl;
    std::cerr << "\t\tetc..." << std::endl;

    return;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_unotools.hxx"

#include <unotools/localisationoptions.hxx>
#include <unotools/configmgr.hxx>
#include <unotools/configitem.hxx>
#include <tools/debug.hxx>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Sequence.hxx>

#include <rtl/logfile.hxx>
#include "itemholder1.hxx"

//_________________________________________________________________________________________________________________
//  namespaces
//_________________________________________________________________________________________________________________

using namespace ::utl                   ;
using namespace ::rtl                   ;
using namespace ::osl                   ;
using namespace ::com::sun::star::uno   ;

//_________________________________________________________________________________________________________________
//  const
//_________________________________________________________________________________________________________________

#define ROOTNODE_LOCALISATION           OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/View/Localisation"))
#define DEFAULT_AUTOMNEMONIC            sal_False
#define DEFAULT_DIALOGSCALE             0

#define PROPERTYNAME_AUTOMNEMONIC       OUString(RTL_CONSTASCII_USTRINGPARAM("AutoMnemonic" ))
#define PROPERTYNAME_DIALOGSCALE        OUString(RTL_CONSTASCII_USTRINGPARAM("DialogScale"  ))

#define PROPERTYHANDLE_AUTOMNEMONIC     0
#define PROPERTYHANDLE_DIALOGSCALE      1

#define PROPERTYCOUNT                   2

//_________________________________________________________________________________________________________________
//  private declarations!
//_________________________________________________________________________________________________________________

class SvtLocalisationOptions_Impl : public ConfigItem
{
    //-------------------------------------------------------------------------------------------------------------
    //  public methods
    //-------------------------------------------------------------------------------------------------------------

    public:

        //---------------------------------------------------------------------------------------------------------
        //  constructor / destructor
        //---------------------------------------------------------------------------------------------------------

         SvtLocalisationOptions_Impl();
        ~SvtLocalisationOptions_Impl();

        //---------------------------------------------------------------------------------------------------------
        //  overloaded methods of baseclass
        //---------------------------------------------------------------------------------------------------------

        /*-****************************************************************************************************//**
            @short      called for notify of configmanager
            @descr      These method is called from the ConfigManager before application ends or from the
                         PropertyChangeListener if the sub tree broadcasts changes. You must update your
                        internal values.

            @seealso    baseclass ConfigItem

            @param      "seqPropertyNames" is the list of properties which should be updated.
            @return     -

            @onerror    -
        *//*-*****************************************************************************************************/

        virtual void Notify( const Sequence< OUString >& seqPropertyNames );

        /*-****************************************************************************************************//**
            @short      write changes to configuration
            @descr      These method writes the changed values into the sub tree
                        and should always called in our destructor to guarantee consistency of config data.

            @seealso    baseclass ConfigItem

            @param      -
            @return     -

            @onerror    -
        *//*-*****************************************************************************************************/

        virtual void Commit();

        //---------------------------------------------------------------------------------------------------------
        //  public interface
        //---------------------------------------------------------------------------------------------------------

        /*-****************************************************************************************************//**
            @short      access method to get internal values
            @descr      These method give us a chance to regulate acces to ouer internal values.
                        It's not used in the moment - but it's possible for the feature!

            @seealso    -

            @param      -
            @return     -

            @onerror    -
        *//*-*****************************************************************************************************/

        sal_Bool    IsAutoMnemonic  (                   ) const ;
        void        SetAutoMnemonic ( sal_Bool  bState  )       ;
        sal_Int32   GetDialogScale  (                   ) const ;
        void        SetDialogScale  ( sal_Int32 nScale  )       ;

    //-------------------------------------------------------------------------------------------------------------
    //  private methods
    //-------------------------------------------------------------------------------------------------------------

    private:

        /*-****************************************************************************************************//**
            @short      return list of key names of ouer configuration management which represent oue module tree
            @descr      These methods return a static const list of key names. We need it to get needed values from our
                        configuration management.

            @seealso    -

            @param      -
            @return     A list of needed configuration keys is returned.

            @onerror    -
        *//*-*****************************************************************************************************/

        static Sequence< OUString > GetPropertyNames();

    //-------------------------------------------------------------------------------------------------------------
    //  private member
    //-------------------------------------------------------------------------------------------------------------

    private:

        sal_Bool    m_bAutoMnemonic     ;
        sal_Int32   m_nDialogScale      ;
};

//_________________________________________________________________________________________________________________
//  definitions
//_________________________________________________________________________________________________________________

//*****************************************************************************************************************
//  constructor
//*****************************************************************************************************************
SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()
    // Init baseclasses first
    :   ConfigItem          ( ROOTNODE_LOCALISATION )
    // Init member then.
    ,   m_bAutoMnemonic     ( DEFAULT_AUTOMNEMONIC  )
    ,   m_nDialogScale      ( DEFAULT_DIALOGSCALE   )
{
    // Use our static list of configuration keys to get his values.
    Sequence< OUString >    seqNames    = GetPropertyNames  (           );
    Sequence< Any >         seqValues   = GetProperties     ( seqNames  );

    // Safe impossible cases.
    // We need values from ALL configuration keys.
    // Follow assignment use order of values in relation to our list of key names!
    DBG_ASSERT( !(seqNames.getLength()!=seqValues.getLength()), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nI miss some values of configuration keys!\n" );

    // Copy values from list in right order to ouer internal member.
    sal_Int32 nPropertyCount = seqValues.getLength();
    for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty )
    {
        // Safe impossible cases.
        // Check any for valid value.
        DBG_ASSERT( !(seqValues[nProperty].hasValue()==sal_False), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nInvalid property value detected!\n" );
        switch( nProperty )
        {
            case PROPERTYHANDLE_AUTOMNEMONIC    :   {
                                                        DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\AutoMnemonic\"?" );
                                                        seqValues[nProperty] >>= m_bAutoMnemonic;
                                                    }
                                                    break;

            case PROPERTYHANDLE_DIALOGSCALE     :   {
                                                        DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\DialogScale\"?" );
                                                        seqValues[nProperty] >>= m_nDialogScale;
                                                    }
                                                    break;
        }
    }

    // Enable notification mechanism of ouer baseclass.
    // We need it to get information about changes outside these class on ouer used configuration keys!
    EnableNotification( seqNames );
}

//*****************************************************************************************************************
//  destructor
//*****************************************************************************************************************
SvtLocalisationOptions_Impl::~SvtLocalisationOptions_Impl()
{
    // We must save our current values .. if user forget it!
    if( IsModified() == sal_True )
    {
        Commit();
    }
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
void SvtLocalisationOptions_Impl::Notify( const Sequence< OUString >& seqPropertyNames )
{
    // Use given list of updated properties to get his values from configuration directly!
    Sequence< Any > seqValues = GetProperties( seqPropertyNames );
    // Safe impossible cases.
    // We need values from ALL notified configuration keys.
    DBG_ASSERT( !(seqPropertyNames.getLength()!=seqValues.getLength()), "SvtLocalisationOptions_Impl::Notify()\nI miss some values of configuration keys!\n" );
    // Step over list of property names and get right value from coreesponding value list to set it on internal members!
    sal_Int32 nCount = seqPropertyNames.getLength();
    for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty )
    {
        if( seqPropertyNames[nProperty] == PROPERTYNAME_AUTOMNEMONIC )
        {
            DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\AutoMnemonic\"?" );
            seqValues[nProperty] >>= m_bAutoMnemonic;
        }
        else
        if( seqPropertyNames[nProperty] == PROPERTYNAME_DIALOGSCALE )
        {
            DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\DialogScale\"?" );
            seqValues[nProperty] >>= m_nDialogScale;
        }
        #if OSL_DEBUG_LEVEL > 1
        else DBG_ASSERT( sal_False, "SvtLocalisationOptions_Impl::Notify()\nUnkown property detected ... I can't handle these!\n" );
        #endif
    }

    NotifyListeners(0);
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
void SvtLocalisationOptions_Impl::Commit()
{
    // Get names of supported properties, create a list for values and copy current values to it.
    Sequence< OUString >    seqNames    = GetPropertyNames  ();
    sal_Int32               nCount      = seqNames.getLength();
    Sequence< Any >         seqValues   ( nCount );
    for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty )
    {
        switch( nProperty )
        {
            case PROPERTYHANDLE_AUTOMNEMONIC    :   {
                                                        seqValues[nProperty] <<= m_bAutoMnemonic;
                                                    }
                                                    break;

            case PROPERTYHANDLE_DIALOGSCALE     :   {
                                                        seqValues[nProperty] <<= m_nDialogScale;
                                                    }
                                                    break;
        }
    }
    // Set properties in configuration.
    PutProperties( seqNames, seqValues );
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
sal_Bool SvtLocalisationOptions_Impl::IsAutoMnemonic() const
{
    return m_bAutoMnemonic;
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
void SvtLocalisationOptions_Impl::SetAutoMnemonic( sal_Bool bState )
{
    m_bAutoMnemonic = bState;
    SetModified();
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
sal_Int32 SvtLocalisationOptions_Impl::GetDialogScale() const
{
    return m_nDialogScale;
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
void SvtLocalisationOptions_Impl::SetDialogScale( sal_Int32 nScale )
{
    m_nDialogScale = nScale;
    SetModified();
}

Sequence< OUString > SvtLocalisationOptions_Impl::GetPropertyNames()
{
    // Build static list of configuration key names.
    const OUString aProperties[] =
    {
        PROPERTYNAME_AUTOMNEMONIC   ,
        PROPERTYNAME_DIALOGSCALE    ,
    };
    // Initialize return sequence with these list ...
    Sequence< OUString > seqPropertyNames(aProperties, PROPERTYCOUNT);
    // ... and return it.
    return seqPropertyNames;
}

//*****************************************************************************************************************
//  initialize static member
//  DON'T DO IT IN YOUR HEADER!
//  see definition for further informations
//*****************************************************************************************************************
SvtLocalisationOptions_Impl*    SvtLocalisationOptions::m_pDataContainer    = NULL  ;
sal_Int32                       SvtLocalisationOptions::m_nRefCount         = 0     ;

//*****************************************************************************************************************
//  constructor
//*****************************************************************************************************************
SvtLocalisationOptions::SvtLocalisationOptions()
{
    // Global access, must be guarded (multithreading!).
    MutexGuard aGuard( GetOwnStaticMutex() );
    // Increase ouer refcount ...
    ++m_nRefCount;
    // ... and initialize ouer data container only if it not already exist!
    if( m_pDataContainer == NULL )
    {
        RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtLocalisationOptions_Impl::ctor()");
        m_pDataContainer = new SvtLocalisationOptions_Impl;

        ItemHolder1::holdConfigItem(E_LOCALISATIONOPTIONS);
    }
}

//*****************************************************************************************************************
//  destructor
//*****************************************************************************************************************
SvtLocalisationOptions::~SvtLocalisationOptions()
{
    // Global access, must be guarded (multithreading!)
    MutexGuard aGuard( GetOwnStaticMutex() );
    // Decrease ouer refcount.
    --m_nRefCount;
    // If last instance was deleted ...
    // we must destroy ouer static data container!
    if( m_nRefCount <= 0 )
    {
        delete m_pDataContainer;
        m_pDataContainer = NULL;
    }
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
sal_Bool SvtLocalisationOptions::IsAutoMnemonic() const
{
    MutexGuard aGuard( GetOwnStaticMutex() );
    return m_pDataContainer->IsAutoMnemonic();
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
void SvtLocalisationOptions::SetAutoMnemonic( sal_Bool bState )
{
    MutexGuard aGuard( GetOwnStaticMutex() );
    m_pDataContainer->SetAutoMnemonic( bState );
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
sal_Int32 SvtLocalisationOptions::GetDialogScale() const
{
    MutexGuard aGuard( GetOwnStaticMutex() );
    return m_pDataContainer->GetDialogScale();
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
void SvtLocalisationOptions::SetDialogScale( sal_Int32 nScale )
{
    MutexGuard aGuard( GetOwnStaticMutex() );
    m_pDataContainer->SetDialogScale( nScale );
}

namespace
{
    class theLocalisationOptionsMutex : public rtl::Static<osl::Mutex, theLocalisationOptionsMutex>{};
}

//*****************************************************************************************************************
//  private method
//*****************************************************************************************************************
Mutex& SvtLocalisationOptions::GetOwnStaticMutex()
{
    return theLocalisationOptionsMutex::get();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>handle missing values gracefully<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_unotools.hxx"

#include <unotools/localisationoptions.hxx>
#include <unotools/configmgr.hxx>
#include <unotools/configitem.hxx>
#include <tools/debug.hxx>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Sequence.hxx>

#include <rtl/logfile.hxx>
#include "itemholder1.hxx"

//_________________________________________________________________________________________________________________
//  namespaces
//_________________________________________________________________________________________________________________

using namespace ::utl                   ;
using namespace ::rtl                   ;
using namespace ::osl                   ;
using namespace ::com::sun::star::uno   ;

//_________________________________________________________________________________________________________________
//  const
//_________________________________________________________________________________________________________________

#define ROOTNODE_LOCALISATION           OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/View/Localisation"))
#define DEFAULT_AUTOMNEMONIC            sal_False
#define DEFAULT_DIALOGSCALE             0

#define PROPERTYNAME_AUTOMNEMONIC       OUString(RTL_CONSTASCII_USTRINGPARAM("AutoMnemonic" ))
#define PROPERTYNAME_DIALOGSCALE        OUString(RTL_CONSTASCII_USTRINGPARAM("DialogScale"  ))

#define PROPERTYHANDLE_AUTOMNEMONIC     0
#define PROPERTYHANDLE_DIALOGSCALE      1

#define PROPERTYCOUNT                   2

//_________________________________________________________________________________________________________________
//  private declarations!
//_________________________________________________________________________________________________________________

class SvtLocalisationOptions_Impl : public ConfigItem
{
    //-------------------------------------------------------------------------------------------------------------
    //  public methods
    //-------------------------------------------------------------------------------------------------------------

    public:

        //---------------------------------------------------------------------------------------------------------
        //  constructor / destructor
        //---------------------------------------------------------------------------------------------------------

         SvtLocalisationOptions_Impl();
        ~SvtLocalisationOptions_Impl();

        //---------------------------------------------------------------------------------------------------------
        //  overloaded methods of baseclass
        //---------------------------------------------------------------------------------------------------------

        /*-****************************************************************************************************//**
            @short      called for notify of configmanager
            @descr      These method is called from the ConfigManager before application ends or from the
                         PropertyChangeListener if the sub tree broadcasts changes. You must update your
                        internal values.

            @seealso    baseclass ConfigItem

            @param      "seqPropertyNames" is the list of properties which should be updated.
            @return     -

            @onerror    -
        *//*-*****************************************************************************************************/

        virtual void Notify( const Sequence< OUString >& seqPropertyNames );

        /*-****************************************************************************************************//**
            @short      write changes to configuration
            @descr      These method writes the changed values into the sub tree
                        and should always called in our destructor to guarantee consistency of config data.

            @seealso    baseclass ConfigItem

            @param      -
            @return     -

            @onerror    -
        *//*-*****************************************************************************************************/

        virtual void Commit();

        //---------------------------------------------------------------------------------------------------------
        //  public interface
        //---------------------------------------------------------------------------------------------------------

        /*-****************************************************************************************************//**
            @short      access method to get internal values
            @descr      These method give us a chance to regulate acces to ouer internal values.
                        It's not used in the moment - but it's possible for the feature!

            @seealso    -

            @param      -
            @return     -

            @onerror    -
        *//*-*****************************************************************************************************/

        sal_Bool    IsAutoMnemonic  (                   ) const ;
        void        SetAutoMnemonic ( sal_Bool  bState  )       ;
        sal_Int32   GetDialogScale  (                   ) const ;
        void        SetDialogScale  ( sal_Int32 nScale  )       ;

    //-------------------------------------------------------------------------------------------------------------
    //  private methods
    //-------------------------------------------------------------------------------------------------------------

    private:

        /*-****************************************************************************************************//**
            @short      return list of key names of ouer configuration management which represent oue module tree
            @descr      These methods return a static const list of key names. We need it to get needed values from our
                        configuration management.

            @seealso    -

            @param      -
            @return     A list of needed configuration keys is returned.

            @onerror    -
        *//*-*****************************************************************************************************/

        static Sequence< OUString > GetPropertyNames();

    //-------------------------------------------------------------------------------------------------------------
    //  private member
    //-------------------------------------------------------------------------------------------------------------

    private:

        sal_Bool    m_bAutoMnemonic     ;
        sal_Int32   m_nDialogScale      ;
};

//_________________________________________________________________________________________________________________
//  definitions
//_________________________________________________________________________________________________________________

//*****************************************************************************************************************
//  constructor
//*****************************************************************************************************************
SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()
    // Init baseclasses first
    :   ConfigItem          ( ROOTNODE_LOCALISATION )
    // Init member then.
    ,   m_bAutoMnemonic     ( DEFAULT_AUTOMNEMONIC  )
    ,   m_nDialogScale      ( DEFAULT_DIALOGSCALE   )
{
    // Use our static list of configuration keys to get his values.
    Sequence< OUString >    seqNames    = GetPropertyNames  (           );
    Sequence< Any >         seqValues   = GetProperties     ( seqNames  );

    // Safe impossible cases.
    // We need values from ALL configuration keys.
    // Follow assignment use order of values in relation to our list of key names!
    DBG_ASSERT( !(seqNames.getLength()!=seqValues.getLength()), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nI miss some values of configuration keys!\n" );

    // Copy values from list in right order to our internal member.
    sal_Int32 nPropertyCount = seqValues.getLength();
    for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty )
    {
        if (!seqValues[nProperty].hasValue())
            continue;
        switch( nProperty )
        {
            case PROPERTYHANDLE_AUTOMNEMONIC    :   {
                                                        DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\AutoMnemonic\"?" );
                                                        seqValues[nProperty] >>= m_bAutoMnemonic;
                                                    }
                                                    break;

            case PROPERTYHANDLE_DIALOGSCALE     :   {
                                                        DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\DialogScale\"?" );
                                                        seqValues[nProperty] >>= m_nDialogScale;
                                                    }
                                                    break;
        }
    }

    // Enable notification mechanism of ouer baseclass.
    // We need it to get information about changes outside these class on ouer used configuration keys!
    EnableNotification( seqNames );
}

//*****************************************************************************************************************
//  destructor
//*****************************************************************************************************************
SvtLocalisationOptions_Impl::~SvtLocalisationOptions_Impl()
{
    // We must save our current values .. if user forget it!
    if( IsModified() == sal_True )
    {
        Commit();
    }
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
void SvtLocalisationOptions_Impl::Notify( const Sequence< OUString >& seqPropertyNames )
{
    // Use given list of updated properties to get his values from configuration directly!
    Sequence< Any > seqValues = GetProperties( seqPropertyNames );
    // Safe impossible cases.
    // We need values from ALL notified configuration keys.
    DBG_ASSERT( !(seqPropertyNames.getLength()!=seqValues.getLength()), "SvtLocalisationOptions_Impl::Notify()\nI miss some values of configuration keys!\n" );
    // Step over list of property names and get right value from coreesponding value list to set it on internal members!
    sal_Int32 nCount = seqPropertyNames.getLength();
    for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty )
    {
        if( seqPropertyNames[nProperty] == PROPERTYNAME_AUTOMNEMONIC )
        {
            DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\AutoMnemonic\"?" );
            seqValues[nProperty] >>= m_bAutoMnemonic;
        }
        else
        if( seqPropertyNames[nProperty] == PROPERTYNAME_DIALOGSCALE )
        {
            DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\DialogScale\"?" );
            seqValues[nProperty] >>= m_nDialogScale;
        }
        #if OSL_DEBUG_LEVEL > 1
        else DBG_ASSERT( sal_False, "SvtLocalisationOptions_Impl::Notify()\nUnkown property detected ... I can't handle these!\n" );
        #endif
    }

    NotifyListeners(0);
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
void SvtLocalisationOptions_Impl::Commit()
{
    // Get names of supported properties, create a list for values and copy current values to it.
    Sequence< OUString >    seqNames    = GetPropertyNames  ();
    sal_Int32               nCount      = seqNames.getLength();
    Sequence< Any >         seqValues   ( nCount );
    for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty )
    {
        switch( nProperty )
        {
            case PROPERTYHANDLE_AUTOMNEMONIC    :   {
                                                        seqValues[nProperty] <<= m_bAutoMnemonic;
                                                    }
                                                    break;

            case PROPERTYHANDLE_DIALOGSCALE     :   {
                                                        seqValues[nProperty] <<= m_nDialogScale;
                                                    }
                                                    break;
        }
    }
    // Set properties in configuration.
    PutProperties( seqNames, seqValues );
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
sal_Bool SvtLocalisationOptions_Impl::IsAutoMnemonic() const
{
    return m_bAutoMnemonic;
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
void SvtLocalisationOptions_Impl::SetAutoMnemonic( sal_Bool bState )
{
    m_bAutoMnemonic = bState;
    SetModified();
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
sal_Int32 SvtLocalisationOptions_Impl::GetDialogScale() const
{
    return m_nDialogScale;
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
void SvtLocalisationOptions_Impl::SetDialogScale( sal_Int32 nScale )
{
    m_nDialogScale = nScale;
    SetModified();
}

Sequence< OUString > SvtLocalisationOptions_Impl::GetPropertyNames()
{
    // Build static list of configuration key names.
    const OUString aProperties[] =
    {
        PROPERTYNAME_AUTOMNEMONIC   ,
        PROPERTYNAME_DIALOGSCALE    ,
    };
    // Initialize return sequence with these list ...
    Sequence< OUString > seqPropertyNames(aProperties, PROPERTYCOUNT);
    // ... and return it.
    return seqPropertyNames;
}

//*****************************************************************************************************************
//  initialize static member
//  DON'T DO IT IN YOUR HEADER!
//  see definition for further informations
//*****************************************************************************************************************
SvtLocalisationOptions_Impl*    SvtLocalisationOptions::m_pDataContainer    = NULL  ;
sal_Int32                       SvtLocalisationOptions::m_nRefCount         = 0     ;

//*****************************************************************************************************************
//  constructor
//*****************************************************************************************************************
SvtLocalisationOptions::SvtLocalisationOptions()
{
    // Global access, must be guarded (multithreading!).
    MutexGuard aGuard( GetOwnStaticMutex() );
    // Increase ouer refcount ...
    ++m_nRefCount;
    // ... and initialize ouer data container only if it not already exist!
    if( m_pDataContainer == NULL )
    {
        RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtLocalisationOptions_Impl::ctor()");
        m_pDataContainer = new SvtLocalisationOptions_Impl;

        ItemHolder1::holdConfigItem(E_LOCALISATIONOPTIONS);
    }
}

//*****************************************************************************************************************
//  destructor
//*****************************************************************************************************************
SvtLocalisationOptions::~SvtLocalisationOptions()
{
    // Global access, must be guarded (multithreading!)
    MutexGuard aGuard( GetOwnStaticMutex() );
    // Decrease ouer refcount.
    --m_nRefCount;
    // If last instance was deleted ...
    // we must destroy ouer static data container!
    if( m_nRefCount <= 0 )
    {
        delete m_pDataContainer;
        m_pDataContainer = NULL;
    }
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
sal_Bool SvtLocalisationOptions::IsAutoMnemonic() const
{
    MutexGuard aGuard( GetOwnStaticMutex() );
    return m_pDataContainer->IsAutoMnemonic();
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
void SvtLocalisationOptions::SetAutoMnemonic( sal_Bool bState )
{
    MutexGuard aGuard( GetOwnStaticMutex() );
    m_pDataContainer->SetAutoMnemonic( bState );
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
sal_Int32 SvtLocalisationOptions::GetDialogScale() const
{
    MutexGuard aGuard( GetOwnStaticMutex() );
    return m_pDataContainer->GetDialogScale();
}

//*****************************************************************************************************************
//  public method
//*****************************************************************************************************************
void SvtLocalisationOptions::SetDialogScale( sal_Int32 nScale )
{
    MutexGuard aGuard( GetOwnStaticMutex() );
    m_pDataContainer->SetDialogScale( nScale );
}

namespace
{
    class theLocalisationOptionsMutex : public rtl::Static<osl::Mutex, theLocalisationOptionsMutex>{};
}

//*****************************************************************************************************************
//  private method
//*****************************************************************************************************************
Mutex& SvtLocalisationOptions::GetOwnStaticMutex()
{
    return theLocalisationOptionsMutex::get();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include <iostream>
#include "common.h"
#include "Overlap.h"
#include "params.h"
#include "ReadTrim.h"
#include "Graph.h"
#include "OverlapUtils.h"
#include "IO.h"
#include "GraphUtils.h"
#include "Unitig.h"
#include "UnitigUtils.h"

int main() {

    Overlaps overlaps;
    Params   params( getDefaultParams());

    std::cout << "1) Reading overlaps and reads" << std::endl;
    loadPAF( overlaps, "../test-data/lambda_overlaps.paf", params );

    std::cout << "2) Proposing read trims" << std::endl;
    ReadTrims readTrims;
    proposeReadTrims( readTrims, overlaps, params, false );

    std::cout << "3) Trimming reads" << std::endl;
    trimReads( overlaps, readTrims, params );

    std::cout << "3) Filtering reads" << std::endl;
    filterReads( overlaps, readTrims, params );

    std::cout << "4) Proposing read trims" << std::endl;
    ReadTrims readTrims2;
    proposeReadTrims( readTrims2, overlaps, params, true );

    std::cout << "5) Trimming reads" << std::endl;
    trimReads( overlaps, readTrims2, params );

    mergeTrims( readTrims, readTrims2 );

    std::cout << "6) Chimering reads" << std::endl;
    filterChimeric( overlaps, readTrims, params );

    std::cout << "7) Filtering contained reads" << std::endl;
    filterContained( overlaps, readTrims, params );

    //    logTrimmedOverlaps( overlaps, readTrims );

    std::cout << "8) Generating graph" << std::endl;
    Graph g;
    generateGraph( g, overlaps, readTrims, params );

    //    logGraph(g);

    std::cout << "9) Filtering transitive edges" << std::endl;
    filterTransitiveEdges( g, 1000 );

    //    logGraph(g);

    std::cout << "10) Removing asymetric edges" << std::endl;
    removeAsymetricEdges( g );

    std::cout << "11) Cutting tips" << std::endl;
    cutTips( g, readTrims, params );

    writeGraphToSIF( "../test-data/notips.sif", g );

    std::cout << "12) Popping bubbles" << std::endl;
    popBubbles( g, readTrims );

    writeGraphToSIF( "../test-data/nobubles.sif", g );

    //    logGraph(g);

    Unitigs unitigs;
    std::cout << "13) Generating unitigs" << std::endl;
    generateUnitigs( unitigs, g, readTrims );

    assignSequencesToUnitigs( unitigs, readTrims, "../test-data/lambda_reads.fasta" );

    logUnitigs( unitigs, readTrims );

    //    logGraph(g);

    //    std::cout << "Left with " << overlaps.size() << " trimmed overlaps" << std::endl;

    //
    //    for (auto const &readTrim: readTrims) {
    //        std::cout << readTrim.first << " " << readTrim.second.toString() << std::endl;
    //    }

    //    writeOverlapsToSIF("mnebijemte.sif", overlaps);

    return 0;
}
<commit_msg>easier dataset change<commit_after>#include <iostream>
#include "common.h"
#include "Overlap.h"
#include "params.h"
#include "ReadTrim.h"
#include "Graph.h"
#include "OverlapUtils.h"
#include "IO.h"
#include "GraphUtils.h"
#include "Unitig.h"
#include "UnitigUtils.h"

#define DATASET "ecoli"

int main() {

    Overlaps overlaps;
    Params   params( getDefaultParams());

    std::cout << "1) Reading overlaps and reads" << std::endl;
    loadPAF( overlaps, "../test-data/" DATASET "_overlaps.paf", params );

    std::cout << "2) Proposing read trims" << std::endl;
    ReadTrims readTrims;
    proposeReadTrims( readTrims, overlaps, params, false );

    std::cout << "3) Trimming reads" << std::endl;
    trimReads( overlaps, readTrims, params );

    std::cout << "3) Filtering reads" << std::endl;
    filterReads( overlaps, readTrims, params );

    std::cout << "4) Proposing read trims" << std::endl;
    ReadTrims readTrims2;
    proposeReadTrims( readTrims2, overlaps, params, true );

    std::cout << "5) Trimming reads" << std::endl;
    trimReads( overlaps, readTrims2, params );

    mergeTrims( readTrims, readTrims2 );

    std::cout << "6) Chimering reads" << std::endl;
    filterChimeric( overlaps, readTrims, params );

    std::cout << "7) Filtering contained reads" << std::endl;
    filterContained( overlaps, readTrims, params );

    //    logTrimmedOverlaps( overlaps, readTrims );

    std::cout << "8) Generating graph" << std::endl;
    Graph g;
    generateGraph( g, overlaps, readTrims, params );

    //    logGraph(g);

    std::cout << "9) Filtering transitive edges" << std::endl;
    filterTransitiveEdges( g, 1000 );

    //    logGraph(g);

    std::cout << "10) Removing asymetric edges" << std::endl;
    removeAsymetricEdges( g );

    std::cout << "11) Cutting tips" << std::endl;
    cutTips( g, readTrims, params );

    writeGraphToSIF( "../test-data/" DATASET "_notips.sif", g );

    std::cout << "12) Popping bubbles" << std::endl;
    popBubbles( g, readTrims );

    writeGraphToSIF( "../test-data/" DATASET "_nobubles.sif", g );

    //    logGraph(g);

    Unitigs unitigs;
    std::cout << "13) Generating unitigs" << std::endl;
    generateUnitigs( unitigs, g, readTrims );

    assignSequencesToUnitigs( unitigs, readTrims, "../test-data/" DATASET "_reads.fasta" );

    logUnitigs( unitigs, readTrims );

    //    logGraph(g);

    //    std::cout << "Left with " << overlaps.size() << " trimmed overlaps" << std::endl;

    //
    //    for (auto const &readTrim: readTrims) {
    //        std::cout << readTrim.first << " " << readTrim.second.toString() << std::endl;
    //    }

    //    writeOverlapsToSIF("mnebijemte.sif", overlaps);

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <iterator>
#include <sstream>
#include <cassert>

int main(int argc, char* argv[])
{
    std::stringstream str;
    str << "Cat";

    std::istream_iterator<char> eos;
    std::istream_iterator<char> i(str);

    char a, b;
    a = *i++;
    b = *i++;
    std::cout << a << b << std::endl;

    return 0;
}

// vim: set ts=4 sw=4 :
<commit_msg>Removed some old testing code<commit_after>#include <iostream>
#include <cassert>

int main(int argc, char* argv[])
{
    return 0;
}

// vim: set ts=4 sw=4 :
<|endoftext|>