<commit_before>#include "game.hpp"
#include "bitboard.hpp"
//#include "newbitmove.hpp"

#if defined(_WIN32) || defined(_WIN64)
	#include <windows.h>
#elif defined(__unix__) || defined(unix) || defined(__unix) || defined(__APPLE__)
	#include <unistd.h>

	#include <sys/time.h>
	#include <sys/types.h>
	#include <sys/select.h>
#endif

bool is_input_available() {

#if defined(_WIN32) || defined(_WIN64)

	static bool init = false, is_pipe;
	static HANDLE stdin_h;
	DWORD val, error;
	bool UseDebug = false;

	// val = 0; // needed to make the compiler happy?

	// have a look at the "local" buffer first, *this time before init (no idea if it helps)*

	if (UseDebug && !init) printf("info string init=%d stdin->_cnt=%d\n",int(init),stdin->_cnt);

	if (stdin->_cnt > 0) return true; // HACK: assumes FILE internals

	// input init (only done once)

	if (!init) {

		init = true;

		stdin_h = GetStdHandle(STD_INPUT_HANDLE);

		if (UseDebug && (stdin_h == NULL || stdin_h == INVALID_HANDLE_VALUE)) {
			error = GetLastError();
			printf("info string GetStdHandle() failed, error=%d\n",error);
		}

		is_pipe = !GetConsoleMode(stdin_h,&val); // HACK: assumes pipe on failure

		if (UseDebug) printf("info string init=%d is_pipe=%d\n",int(init),int(is_pipe));

		if (UseDebug && is_pipe) { // GetConsoleMode() failed, everybody assumes pipe then
			error = GetLastError();
			printf("info string GetConsoleMode() failed, error=%d\n",error);
		}

		if (!is_pipe) {
			SetConsoleMode(stdin_h,val&~(ENABLE_MOUSE_INPUT|ENABLE_WINDOW_INPUT));
			FlushConsoleInputBuffer(stdin_h); // no idea if we can lose data doing this
		}
	}

	// different polling depending on input type
	// does this code work at all for pipes?

	if (is_pipe) {

		if (!PeekNamedPipe(stdin_h,NULL,0,NULL,&val ,NULL)) {

			if (UseDebug) { // PeekNamedPipe() failed, everybody assumes EOF then
				error = GetLastError();
				printf("info string PeekNamedPipe() failed, error=%d\n",error);
			}

			return true; // HACK: assumes EOF on failure
		}

		if (UseDebug && val < 0) printf("info string PeekNamedPipe(): val=%d\n",val);

		return val > 0; // != 0???

	} else {

		GetNumberOfConsoleInputEvents(stdin_h,&val);
		return val > 1; // no idea why 1
	}

	return false;

#else // assume POSIX

	int val;
	fd_set set[1];
	struct timeval time_val[1];

	FD_ZERO(set);
	FD_SET(STDIN_FILENO,set);

	time_val->tv_sec = 0;
	time_val->tv_usec = 0;

	val = select(STDIN_FILENO+1,set,NULL,NULL,time_val);
	//if (val == -1 && errno != EINTR) {
	//my_fatal("input_available(): select(): %s\n",strerror(errno));
	//}

	return val > 0;

#endif
}

int main() {
	/*setBitMoveConstants();
	NewBitMove bitMove;
	bitMove.setAttackedFigure(WHITE | KING);
	std::cout << bitMove.getAttackedFigure() << "\n";*/

	Game* game = new Game();

	std::cout << sizeof(Hash) << "\n";
	game->startGame();

	delete game;
}
<commit_msg>размер ячейки таблицы транспозиции уменьшен с 80 до 32 байт (в будущем планируется уменьшение до 16-17 байт), добавлена кнопка очистки кеша<commit_after>#include "game.hpp"
#include "bitboard.hpp"
//#include "newbitmove.hpp"

#if defined(_WIN32) || defined(_WIN64)
	#include <windows.h>
#elif defined(__unix__) || defined(unix) || defined(__unix) || defined(__APPLE__)
	#include <unistd.h>

	#include <sys/time.h>
	#include <sys/types.h>
	#include <sys/select.h>
#endif

bool is_input_available() {

#if defined(_WIN32) || defined(_WIN64)

	static bool init = false, is_pipe;
	static HANDLE stdin_h;
	DWORD val, error;
	bool UseDebug = false;

	// val = 0; // needed to make the compiler happy?

	// have a look at the "local" buffer first, *this time before init (no idea if it helps)*

	if (UseDebug && !init) printf("info string init=%d stdin->_cnt=%d\n",int(init),stdin->_cnt);

	if (stdin->_cnt > 0) return true; // HACK: assumes FILE internals

	// input init (only done once)

	if (!init) {

		init = true;

		stdin_h = GetStdHandle(STD_INPUT_HANDLE);

		if (UseDebug && (stdin_h == NULL || stdin_h == INVALID_HANDLE_VALUE)) {
			error = GetLastError();
			printf("info string GetStdHandle() failed, error=%d\n",error);
		}

		is_pipe = !GetConsoleMode(stdin_h,&val); // HACK: assumes pipe on failure

		if (UseDebug) printf("info string init=%d is_pipe=%d\n",int(init),int(is_pipe));

		if (UseDebug && is_pipe) { // GetConsoleMode() failed, everybody assumes pipe then
			error = GetLastError();
			printf("info string GetConsoleMode() failed, error=%d\n",error);
		}

		if (!is_pipe) {
			SetConsoleMode(stdin_h,val&~(ENABLE_MOUSE_INPUT|ENABLE_WINDOW_INPUT));
			FlushConsoleInputBuffer(stdin_h); // no idea if we can lose data doing this
		}
	}

	// different polling depending on input type
	// does this code work at all for pipes?

	if (is_pipe) {

		if (!PeekNamedPipe(stdin_h,NULL,0,NULL,&val ,NULL)) {

			if (UseDebug) { // PeekNamedPipe() failed, everybody assumes EOF then
				error = GetLastError();
				printf("info string PeekNamedPipe() failed, error=%d\n",error);
			}

			return true; // HACK: assumes EOF on failure
		}

		if (UseDebug && val < 0) printf("info string PeekNamedPipe(): val=%d\n",val);

		return val > 0; // != 0???

	} else {

		GetNumberOfConsoleInputEvents(stdin_h,&val);
		return val > 1; // no idea why 1
	}

	return false;

#else // assume POSIX

	int val;
	fd_set set[1];
	struct timeval time_val[1];

	FD_ZERO(set);
	FD_SET(STDIN_FILENO,set);

	time_val->tv_sec = 0;
	time_val->tv_usec = 0;

	val = select(STDIN_FILENO+1,set,NULL,NULL,time_val);
	//if (val == -1 && errno != EINTR) {
	//my_fatal("input_available(): select(): %s\n",strerror(errno));
	//}

	return val > 0;

#endif
}

int main() {
	/*setBitMoveConstants();
	NewBitMove bitMove;
	bitMove.setAttackedFigure(WHITE | KING);
	std::cout << bitMove.getAttackedFigure() << "\n";*/

	Game* game = new Game();
	game->startGame();

	delete game;
}
<|endoftext|>


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

static sf::RenderWindow * main_window;

void resized(const sf::Event::SizeEvent & size)
{
    sf::View * default_view = &main_window->GetDefaultView();
    default_view->SetHalfSize(size.Width / 2, size.Height / 2);
}

int main()
{
    main_window = new sf::RenderWindow(sf::VideoMode(800, 600, 32), "grinch");
    main_window->UseVerticalSync(true);

    sf::Image * image = new sf::Image();
    if (!image->LoadFromFile("sample.png"))
        return 1;
    sf::Sprite * sprite = new sf::Sprite(*image);
    sprite->SetPosition(10, 10);
    sprite->SetScale(1.0f / 8, 1.0f / 8);

    while (main_window->IsOpened()) {
        sf::Event event;
        while (main_window->GetEvent(event)) {
            switch (event.Type) {
                case sf::Event::Closed:
                    main_window->Close();
                    break;
                case sf::Event::Resized:
                    resized(event.Size);
                    break;
                case sf::Event::KeyPressed:
                    // only check for closing here
                    if (event.Key.Code == sf::Key::Escape || (event.Key.Alt && event.Key.Code == sf::Key::F4))
                        main_window->Close();
                    break;
            }
        }

        const sf::Input * input = &main_window->GetInput();
        if (input->IsKeyDown(sf::Key::Up)) main_window->GetDefaultView().Move(0, -5);
        if (input->IsKeyDown(sf::Key::Left)) main_window->GetDefaultView().Move(-5, 0);
        if (input->IsKeyDown(sf::Key::Down)) main_window->GetDefaultView().Move(0, 5);
        if (input->IsKeyDown(sf::Key::Right)) main_window->GetDefaultView().Move(5, 0);

        if (input->IsKeyDown(sf::Key::Comma)) main_window->GetDefaultView().Zoom(0.9f);
        if (input->IsKeyDown(sf::Key::Period)) main_window->GetDefaultView().Zoom(1.0f / 0.9f);

        main_window->Clear();

        main_window->Draw(sf::Shape::Line(10, 10, 710, 100, 15, sf::Color::Red));
        main_window->Draw(sf::Shape::Circle(200, 200, 100, sf::Color::Yellow, 10, sf::Color::Blue));
        main_window->Draw(sf::Shape::Rectangle(350, 200, 600, 350, sf::Color::Green));
        main_window->Draw(*sprite);

        main_window->Display();
    }
    return 0;
}

<commit_msg>the druple thing moves around with the arrows<commit_after>
#include <SFML/Graphics.hpp>

static sf::RenderWindow * main_window;

void resized(const sf::Event::SizeEvent & size)
{
    main_window->GetDefaultView().SetHalfSize(size.Width / 2, size.Height / 2);
}

static float position_x = 0;
static float position_y = 0;
static float velocity_x = 0;
static float velocity_y = 0;

int main()
{
    main_window = new sf::RenderWindow(sf::VideoMode(800, 600, 32), "grinch");
    main_window->UseVerticalSync(true);

    sf::Image * image = new sf::Image();
    if (!image->LoadFromFile("sample.png"))
        return 1;
    sf::Sprite * sprite = new sf::Sprite(*image);
    sprite->SetCenter(image->GetWidth() / 2, image->GetHeight() / 2);
    sprite->SetPosition(10, 10);
    sprite->SetScale(1.0f / 8, 1.0f / 8);

    while (main_window->IsOpened()) {
        sf::Event event;
        while (main_window->GetEvent(event)) {
            switch (event.Type) {
                case sf::Event::Closed:
                    main_window->Close();
                    break;
                case sf::Event::Resized:
                    resized(event.Size);
                    break;
                case sf::Event::KeyPressed: {
                    // only check for closing here
                    bool alt_f4 = event.Key.Alt && event.Key.Code == sf::Key::F4;
                    if (event.Key.Code == sf::Key::Escape || alt_f4) {
                        main_window->Close();
                        goto break_main_loop;
                    }
                    break;
                }
            }
        }

        float elapsed_time = main_window->GetFrameTime();

        const sf::Input * input = &main_window->GetInput();
        if (input->IsKeyDown(sf::Key::W)) velocity_y -= elapsed_time * 2000.0f;
        if (input->IsKeyDown(sf::Key::A)) velocity_x -= elapsed_time * 2000.0f;
        if (input->IsKeyDown(sf::Key::S)) velocity_y += elapsed_time * 2000.0f;
        if (input->IsKeyDown(sf::Key::D)) velocity_x += elapsed_time * 2000.0f;
        position_x += elapsed_time * velocity_x;
        position_y += elapsed_time * velocity_y;
        sprite->SetPosition(position_x, position_y);

        sf::View * view = &main_window->GetDefaultView();
        view->SetCenter(position_x, position_y);
        if (input->IsKeyDown(sf::Key::Comma)) view->Zoom(0.98f);
        if (input->IsKeyDown(sf::Key::Period)) view->Zoom(1.0f / 0.98f);

        main_window->Clear();

        main_window->Draw(sf::Shape::Line(10, 10, 710, 100, 15, sf::Color::Red));
        main_window->Draw(sf::Shape::Circle(200, 200, 100, sf::Color::Yellow, 10, sf::Color::Blue));
        main_window->Draw(sf::Shape::Rectangle(350, 200, 600, 350, sf::Color::Green));
        main_window->Draw(*sprite);

        main_window->Display();
    }
    break_main_loop:
    return 0;
}

<|endoftext|>


<commit_before>691acaa3-2749-11e6-be12-e0f84713e7b8<commit_msg>Put the thingie in the thingie<commit_after>69286a68-2749-11e6-8b69-e0f84713e7b8<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <stdlib.h>     /* srand, rand */
#include <time.h>

using namespace std;

int main()
{
    // Initialize variables
    int randomInt, userMove;
    char playAgain;
    int playerWins = 0;
    int compWins = 0;

    const string moves[] = {"rock", "paper", "scissors"};

    // Initialize rng
    srand(time(NULL));

    bool playing = true;

    cout << "Welcome. Please press the enter key to begin playing Rock Paper Scissors SHOOT!";
    cin.get(); // "Pauses" the program until the enter key is pressed

    while(playing)
    {
        cout << "Enter 1 to play Rock, 2 to play Paper, and 3 to play Scissors!: ";
        cin >> userMove;

        if(userMove != 1 and userMove !=2 and userMove !=3)
            cout << "Unknown command! Please try that again..." << endl;
        else
        {
            // Create random integer in range [1,3] to simulate the 'computer' selecting a move
            randomInt = rand() % 3 + 1;

            if(userMove == randomInt)
                cout << "Tie game! Both you and the computer chose " << moves[randomInt - 1] << endl;
            else
            {
                if(userMove - randomInt == 1 or userMove - randomInt == -2)
                {
                    cout << "Congratulations, you won!" << endl;
                    playerWins++;
                } else
                {
                    cout << "Sorry, better luck next time!" << endl;
                    compWins++;
                }

                cout << "You chose " << moves[userMove - 1] << " and the computer chose " << moves[randomInt - 1] << endl;
            }

            cout << "(Player: " << playerWins << " | Computer: " << compWins << ")" << endl;

            cout << "Play again? [y/n]: ";
            cin >> playAgain;

            if(playAgain != 'y')
                playing = false;
        }

    }

    return 0;
}
<commit_msg>I/O consistency<commit_after>#include <iostream>
#include <string>
#include <stdlib.h>     /* srand, rand */
#include <time.h>

using namespace std;

int main()
{
    // Initialize variables
    int randomInt, userMove;
    char playAgain;
    int playerWins = 0;
    int compWins = 0;

    const string moves[] = {"rock", "paper", "scissors"};

    // Initialize rng
    srand(time(NULL));

    bool playing = true;

    cout << "Welcome. Please press the enter key to begin playing Rock Paper Scissors SHOOT!";
    cin.get(); // "Pauses" the program until the enter key is pressed

    while(playing)
    {
        cout << "Enter 1 to play Rock, 2 to play Paper, and 3 to play Scissors!: ";
        cin >> userMove;

        if(userMove != 1 and userMove !=2 and userMove !=3)
            cout << "Unknown command! Please try that again..." << endl;
        else
        {
            // Create random integer in range [1,3] to simulate the 'computer' selecting a move
            randomInt = rand() % 3 + 1;

            if(userMove == randomInt)
                cout << "Tie game!\nBoth you and the computer chose " << moves[randomInt - 1] << endl;
            else
            {
                if(userMove - randomInt == 1 or userMove - randomInt == -2)
                {
                    cout << "Congratulations, you won!" << endl;
                    playerWins++;
                } else
                {
                    cout << "Sorry, better luck next time!" << endl;
                    compWins++;
                }

                cout << "You chose " << moves[userMove - 1] << " and the computer chose " << moves[randomInt - 1] << endl;
            }

            cout << "(Player: " << playerWins << " | Computer: " << compWins << ")" << endl;

            cout << "Play again? [y/n]: ";
            cin >> playAgain;

            if(playAgain != 'y')
                playing = false;
        }

    }

    return 0;
}
<|endoftext|>


<commit_before>#include <time.h>
#include <SDL2/SDL.h>

#include "kdmap.h"
#include "kdtree.h"
#include "client.h"
#include "menu.h"
#include "engine.h"

#include "r_world.h"
#include "r_splash.h"
#include "r_gui.h"

#include "c_var.h"

#include "u_file.h"
#include "u_misc.h"

// we load assets in a different thread
enum {
    kLoadInProgress, // loading in progress
    kLoadFailed,     // loading failed
    kLoadSucceeded   // loading succeeded
};

struct loadThreadData {
    kdMap gMap;
    r::world gWorld;
    SDL_atomic_t done;
};

static bool loadThread(void *threadData) {
    loadThreadData *data = (loadThreadData*)threadData;

    auto read = u::read(neoGamePath() + "maps/garden.kdgz", "rb");
    if (read) {
        if (!data->gMap.load(*read))
            goto error;
        if (!data->gWorld.load(data->gMap))
            goto error;
        SDL_AtomicSet(&data->done, kLoadSucceeded);
        return true;
    }
error:
    SDL_AtomicSet(&data->done, kLoadFailed);
    return false;
}

template <typename T>
static inline void memput(unsigned char *&store, const T &data) {
  memcpy(store, &data, sizeof(T));
  store += sizeof(T);
}

bool bmpWrite(const u::string &file, int width, int height, unsigned char *rgb) {
    struct {
        char bfType[2];
        int32_t bfSize;
        int32_t bfReserved;
        int32_t bfDataOffset;
        int32_t biSize;
        int32_t biWidth;
        int32_t biHeight;
        int16_t biPlanes;
        int16_t biBitCount;
        int32_t biCompression;
        int32_t biSizeImage;
        int32_t biXPelsPerMeter;
        int32_t biYPelsPerMeter;
        int32_t biClrUsed;
        int32_t biClrImportant;
    } bmph;

    const size_t bytesPerLine = (3 * (width + 1) / 4) * 4;
    const size_t headerSize = 54;
    const size_t imageSize = bytesPerLine * height;
    const size_t dataSize = headerSize + imageSize;

    // Populate header
    strncpy(bmph.bfType, "BM", 2);
    bmph.bfSize = dataSize;
    bmph.bfReserved = 0;
    bmph.bfDataOffset = headerSize;
    bmph.biSize = 40;
    bmph.biWidth = width;
    bmph.biHeight = height;
    bmph.biPlanes = 1;
    bmph.biBitCount = 24;
    bmph.biCompression = 0;
    bmph.biSizeImage = imageSize;
    bmph.biXPelsPerMeter = 0;
    bmph.biYPelsPerMeter = 0;
    bmph.biClrUsed = 0;
    bmph.biClrImportant = 0;

    // line and data buffer
    u::vector<unsigned char> line;
    line.resize(bytesPerLine);
    u::vector<unsigned char> data;
    data.resize(dataSize);

    bmph.bfSize = u::endianSwap(bmph.bfSize);
    bmph.bfReserved = u::endianSwap(bmph.bfReserved);
    bmph.bfDataOffset = u::endianSwap(bmph.bfDataOffset);
    bmph.biSize = u::endianSwap(bmph.biSize);
    bmph.biWidth = u::endianSwap(bmph.biWidth);
    bmph.biHeight = u::endianSwap(bmph.biHeight);
    bmph.biPlanes = u::endianSwap(bmph.biPlanes);
    bmph.biBitCount = u::endianSwap(bmph.biBitCount);
    bmph.biCompression = u::endianSwap(bmph.biCompression);
    bmph.biSizeImage = u::endianSwap(bmph.biSizeImage);
    bmph.biXPelsPerMeter = u::endianSwap(bmph.biXPelsPerMeter);
    bmph.biYPelsPerMeter = u::endianSwap(bmph.biYPelsPerMeter);
    bmph.biClrUsed = u::endianSwap(bmph.biClrUsed);
    bmph.biClrImportant = u::endianSwap(bmph.biClrImportant);

    unsigned char *store = &data[0];
    memput(store, bmph.bfType);
    memput(store, bmph.bfSize);
    memput(store, bmph.bfReserved);
    memput(store, bmph.bfDataOffset);
    memput(store, bmph.biSize);
    memput(store, bmph.biWidth);
    memput(store, bmph.biHeight);
    memput(store, bmph.biPlanes);
    memput(store, bmph.biBitCount);
    memput(store, bmph.biCompression);
    memput(store, bmph.biSizeImage);
    memput(store, bmph.biXPelsPerMeter);
    memput(store, bmph.biYPelsPerMeter);
    memput(store, bmph.biClrUsed);
    memput(store, bmph.biClrImportant);

    // Write the bitmap
    for (int i = height - 1; i >= 0; i--) {
        for (int j = 0; j < width; j++) {
            int ipos = 3 * (width * i + j);
            line[3*j]   = rgb[ipos + 2];
            line[3*j+1] = rgb[ipos + 1];
            line[3*j+2] = rgb[ipos];
        }
        memcpy(store, &line[0], line.size());
        store += line.size();
    }

    return u::write(data, file, "wb");
}

static void screenShot() {
    // Generate a unique filename from the time
    time_t t = time(nullptr);
    struct tm tm = *localtime(&t);
    u::string file = u::format("%sscreenshots/%d-%d-%d-%d%d%d.bmp",
        neoUserPath(), tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
        tm.tm_hour, tm.tm_min, tm.tm_sec);

    // Get metrics for reading the final composite from GL
    const int screenWidth = int(neoWidth());
    const int screenHeight = int(neoHeight());
    const int screenSize = screenWidth * screenHeight;
    auto pixels = u::unique_ptr<unsigned char>(new unsigned char[screenSize * 3]);

    // make sure we're reading from the final framebuffer when obtaining the pixels
    // for the screenshot.
    gl::BindFramebuffer(GL_READ_FRAMEBUFFER, 0);
    gl::PixelStorei(GL_PACK_ALIGNMENT, 1);
    gl::ReadPixels(0, 0, screenWidth, screenHeight, GL_RGB, GL_UNSIGNED_BYTE,
        (GLvoid *)pixels.get());
    gl::PixelStorei(GL_PACK_ALIGNMENT, 8);

    // Reorient because it will be upside down
    auto temp = u::unique_ptr<unsigned char>(new unsigned char[screenSize * 3]);
    texture::reorient(pixels.get(), screenWidth, screenHeight, 3, screenWidth * 3,
        temp.get(), false, true, false);

    // Write the data
    if (bmpWrite(file, screenWidth, screenHeight, temp.get()))
        u::print("[screenshot] => %s\n", file);
}

VAR(float, cl_fov, "field of view", 45.0f, 270.0f, 90.0f);
VAR(float, cl_nearp, "near plane", 0.0f, 10.0f, 1.0f);
VAR(float, cl_farp, "far plane", 128.0f, 4096.0f, 2048.0f);

int neoMain(frameTimer &timer, int, char **) {
    r::splashScreen gSplash;
    if (!gSplash.load("textures/logo"))
        neoFatal("failed to load splash screen");
    gSplash.upload();

    r::gui gGui;
    if (!gGui.load("fonts/droidsans"))
        neoFatal("failed to load font");
    if (!gGui.upload())
        neoFatal("failed to initialize GUI rendering method\n");

    r::rendererPipeline pipeline;
    m::perspectiveProjection projection;
    projection.fov = cl_fov;
    projection.width = neoWidth();
    projection.height = neoHeight();
    projection.nearp = cl_nearp;
    projection.farp = cl_farp;

    pipeline.setPerspectiveProjection(projection);
    pipeline.setWorldPosition(m::vec3::origin);

    // create a loader thread
    loadThreadData loadData;
    SDL_AtomicSet(&loadData.done, kLoadInProgress);
    SDL_CreateThread((SDL_ThreadFunction)&loadThread, nullptr, (void*)&loadData);

    // while that thread is running render the loading screen
    while (SDL_AtomicGet(&loadData.done) == kLoadInProgress) {
        gl::Clear(GL_COLOR_BUFFER_BIT);
        pipeline.setTime(timer.ticks() / 500.0f);
        gSplash.render(pipeline);
        neoSwap();
    }

    if (SDL_AtomicGet(&loadData.done) != kLoadSucceeded)
        return 1;

    // Now render the menu
    client gClient;

    bool running = true;
    bool playing = false;
    bool input = false;
    u::string inputString = "";

    menuRegister("running", running);
    menuRegister("playing", playing);
    menuReset(); // To initialize

    neoSetWindowTitle("Neothyne");
    neoCenterMouse();
    int mouse[4] = {0}; // X, Y, Scroll, Button
    while (running) {
        if (!input)
            gClient.update(loadData.gMap, timer.delta());

        pipeline.setRotation(gClient.getRotation());
        pipeline.setPosition(gClient.getPosition());
        pipeline.setTime(timer.ticks());

        if (playing) {
            loadData.gWorld.upload(projection);
            gl::ClearColor(0.0f, 0.0f, 0.0f, 0.0f);
            loadData.gWorld.render(pipeline);
        } else {
            gl::ClearColor(40/255.0f, 30/255.0f, 50/255.0f, 0.1f);
            gl::Clear(GL_COLOR_BUFFER_BIT);
        }
        gGui.render(pipeline);
        neoSwap();

        SDL_Event e;
        mouse[2] = 0;
        while (SDL_PollEvent(&e)) {
            switch (e.type) {
                case SDL_QUIT:
                    running = false;
                    break;
                case SDL_WINDOWEVENT:
                    switch (e.window.event) {
                        case SDL_WINDOWEVENT_RESIZED:
                            // Resize the window
                            neoResize(e.window.data1, e.window.data2);
                            projection.width = neoWidth();
                            projection.height = neoHeight();
                            pipeline.setPerspectiveProjection(projection);
                            break;
                    }
                    break;
                case SDL_KEYDOWN:
                    switch (e.key.keysym.sym) {
                        case SDLK_ESCAPE:
                            // The effect of the ESC key is strange. When in game
                            // it should bring up the menu. While in the menu it
                            // should always bring you to main menu, except while
                            // in game and in menu and already at main menu then
                            // ESC should bring you back in game.
                            if (playing && gMenuState & kMenuMain) {
                                if (gMenuState & kMenuConsole) {
                                    gMenuState = kMenuConsole;
                                } else {
                                    gMenuState &= ~kMenuMain;
                                    //neoRelativeMouse(true);
                                }
                            } else {
                                // If the console is opened leave it open
                                gMenuState = (gMenuState & kMenuConsole)
                                    ? kMenuMain | kMenuConsole
                                    : kMenuMain;
                            }
                            if (playing && !(gMenuState & kMenuMain))
                                neoRelativeMouse(true);
                            else
                                neoRelativeMouse(false);
                            neoCenterMouse();
                            break;
                        case SDLK_F8:
                            screenShot();
                            break;
                        case SDLK_F9:
                            u::print("%d fps : %.2f mspf\n", timer.fps(), timer.mspf());
                            break;
                        case SDLK_F11:
                            gMenuState ^= kMenuConsole;
                            break;
                        case SDLK_BACKSPACE:
                            if (input)
                                inputString.pop_back();
                            break;
                        case SDLK_SLASH:
                            input = !input;
                            if (input) {
                                SDL_StartTextInput();
                            } else {
                                SDL_StopTextInput();
                            }
                            inputString.reset();
                            break;
                        case SDLK_RETURN:
                            if (input) {
                                auto split = u::split(inputString);
                                switch (c::varChange(split[0], split[1], true)) {
                                    case c::kVarNotFoundError:
                                        u::print("'%s' not found\n", split[0]);
                                        break;
                                    case c::kVarRangeError:
                                        u::print("invalid range '%s' for '%s'\n", split[1], split[0]);
                                        break;
                                    case c::kVarReadOnlyError:
                                        u::print("'%s' is read only\n", split[0]);
                                        break;
                                    case c::kVarTypeError:
                                        u::print("value '%s' wrong type for '%s'\n", split[1], split[0]);
                                        break;
                                    case c::kVarSuccess:
                                        u::print("'%s' changed\n", split[0]);
                                        break;
                                }
                                input = false;
                                inputString.reset();
                            }
                    }
                    neoKeyState(e.key.keysym.sym, true);
                    break;
                case SDL_KEYUP:
                    neoKeyState(e.key.keysym.sym, false, true);
                    break;
                case SDL_MOUSEMOTION:
                    mouse[0] = e.motion.x;
                    mouse[1] = neoHeight() - e.motion.y;
                    break;
                case SDL_MOUSEWHEEL:
                    mouse[2] = e.wheel.y;
                    break;
                case SDL_MOUSEBUTTONDOWN:
                    switch (e.button.button) {
                        case SDL_BUTTON_LEFT:
                            mouse[3] |= gui::kMouseButtonLeft;
                            break;
                        case SDL_BUTTON_RIGHT:
                            mouse[3] |= gui::kMouseButtonRight;
                            break;
                    }
                    break;
                case SDL_MOUSEBUTTONUP:
                    switch (e.button.button) {
                        case SDL_BUTTON_LEFT:
                            mouse[3] &= ~gui::kMouseButtonLeft;
                            break;
                        case SDL_BUTTON_RIGHT:
                            mouse[3] &= ~gui::kMouseButtonRight;
                            break;
                    }
                    break;
                case SDL_TEXTINPUT:
                    inputString += e.text.text;
                    break;
            }
        }

        gui::begin(mouse);

        // Must come first as we want the menu to go over the cross hair if it's
        // launched after playing
        if (playing) {
            gui::drawRectangle(neoWidth() / 2 - 5, neoHeight() / 2 - 5, 10, 10, 5, 0xFFFFFFE1);
            gui::drawLine(neoWidth() / 2, neoHeight() / 2 - 10, neoWidth() / 2, neoHeight() / 2 + 10, 2, 0xFFFFFFE1);
            gui::drawLine(neoWidth() / 2 + 10, neoHeight() / 2, neoWidth() / 2 - 10, neoHeight() / 2, 2, 0xFFFFFFE1);
        }

        menuUpdate();

        // Render FPS/MSPF
        gui::drawText(neoWidth() - 10, 10, gui::kAlignRight,
            u::format("%d fps : %.2f mspf\n", timer.fps(), timer.mspf()),
            gui::RGBA(255, 255, 255, 255));

        if (input) {
            if (inputString[0] == '/')
                inputString.pop_front();
            // Accepting console commands
            gui::drawTriangle(5, 10, 10, 10, 1, gui::RGBA(155, 155, 155, 255));
            gui::drawText(20, 10, gui::kAlignLeft,
                inputString, gui::RGBA(255, 255, 255, 255));
        }

        gui::finish();
    }

    c::writeConfig();

    SDL_Quit();
    return 0;
}
<commit_msg>Better cross hair shape.<commit_after>#include <time.h>
#include <SDL2/SDL.h>

#include "kdmap.h"
#include "kdtree.h"
#include "client.h"
#include "menu.h"
#include "engine.h"

#include "r_world.h"
#include "r_splash.h"
#include "r_gui.h"

#include "c_var.h"

#include "u_file.h"
#include "u_misc.h"

// we load assets in a different thread
enum {
    kLoadInProgress, // loading in progress
    kLoadFailed,     // loading failed
    kLoadSucceeded   // loading succeeded
};

struct loadThreadData {
    kdMap gMap;
    r::world gWorld;
    SDL_atomic_t done;
};

static bool loadThread(void *threadData) {
    loadThreadData *data = (loadThreadData*)threadData;

    auto read = u::read(neoGamePath() + "maps/garden.kdgz", "rb");
    if (read) {
        if (!data->gMap.load(*read))
            goto error;
        if (!data->gWorld.load(data->gMap))
            goto error;
        SDL_AtomicSet(&data->done, kLoadSucceeded);
        return true;
    }
error:
    SDL_AtomicSet(&data->done, kLoadFailed);
    return false;
}

template <typename T>
static inline void memput(unsigned char *&store, const T &data) {
  memcpy(store, &data, sizeof(T));
  store += sizeof(T);
}

bool bmpWrite(const u::string &file, int width, int height, unsigned char *rgb) {
    struct {
        char bfType[2];
        int32_t bfSize;
        int32_t bfReserved;
        int32_t bfDataOffset;
        int32_t biSize;
        int32_t biWidth;
        int32_t biHeight;
        int16_t biPlanes;
        int16_t biBitCount;
        int32_t biCompression;
        int32_t biSizeImage;
        int32_t biXPelsPerMeter;
        int32_t biYPelsPerMeter;
        int32_t biClrUsed;
        int32_t biClrImportant;
    } bmph;

    const size_t bytesPerLine = (3 * (width + 1) / 4) * 4;
    const size_t headerSize = 54;
    const size_t imageSize = bytesPerLine * height;
    const size_t dataSize = headerSize + imageSize;

    // Populate header
    strncpy(bmph.bfType, "BM", 2);
    bmph.bfSize = dataSize;
    bmph.bfReserved = 0;
    bmph.bfDataOffset = headerSize;
    bmph.biSize = 40;
    bmph.biWidth = width;
    bmph.biHeight = height;
    bmph.biPlanes = 1;
    bmph.biBitCount = 24;
    bmph.biCompression = 0;
    bmph.biSizeImage = imageSize;
    bmph.biXPelsPerMeter = 0;
    bmph.biYPelsPerMeter = 0;
    bmph.biClrUsed = 0;
    bmph.biClrImportant = 0;

    // line and data buffer
    u::vector<unsigned char> line;
    line.resize(bytesPerLine);
    u::vector<unsigned char> data;
    data.resize(dataSize);

    bmph.bfSize = u::endianSwap(bmph.bfSize);
    bmph.bfReserved = u::endianSwap(bmph.bfReserved);
    bmph.bfDataOffset = u::endianSwap(bmph.bfDataOffset);
    bmph.biSize = u::endianSwap(bmph.biSize);
    bmph.biWidth = u::endianSwap(bmph.biWidth);
    bmph.biHeight = u::endianSwap(bmph.biHeight);
    bmph.biPlanes = u::endianSwap(bmph.biPlanes);
    bmph.biBitCount = u::endianSwap(bmph.biBitCount);
    bmph.biCompression = u::endianSwap(bmph.biCompression);
    bmph.biSizeImage = u::endianSwap(bmph.biSizeImage);
    bmph.biXPelsPerMeter = u::endianSwap(bmph.biXPelsPerMeter);
    bmph.biYPelsPerMeter = u::endianSwap(bmph.biYPelsPerMeter);
    bmph.biClrUsed = u::endianSwap(bmph.biClrUsed);
    bmph.biClrImportant = u::endianSwap(bmph.biClrImportant);

    unsigned char *store = &data[0];
    memput(store, bmph.bfType);
    memput(store, bmph.bfSize);
    memput(store, bmph.bfReserved);
    memput(store, bmph.bfDataOffset);
    memput(store, bmph.biSize);
    memput(store, bmph.biWidth);
    memput(store, bmph.biHeight);
    memput(store, bmph.biPlanes);
    memput(store, bmph.biBitCount);
    memput(store, bmph.biCompression);
    memput(store, bmph.biSizeImage);
    memput(store, bmph.biXPelsPerMeter);
    memput(store, bmph.biYPelsPerMeter);
    memput(store, bmph.biClrUsed);
    memput(store, bmph.biClrImportant);

    // Write the bitmap
    for (int i = height - 1; i >= 0; i--) {
        for (int j = 0; j < width; j++) {
            int ipos = 3 * (width * i + j);
            line[3*j]   = rgb[ipos + 2];
            line[3*j+1] = rgb[ipos + 1];
            line[3*j+2] = rgb[ipos];
        }
        memcpy(store, &line[0], line.size());
        store += line.size();
    }

    return u::write(data, file, "wb");
}

static void screenShot() {
    // Generate a unique filename from the time
    time_t t = time(nullptr);
    struct tm tm = *localtime(&t);
    u::string file = u::format("%sscreenshots/%d-%d-%d-%d%d%d.bmp",
        neoUserPath(), tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
        tm.tm_hour, tm.tm_min, tm.tm_sec);

    // Get metrics for reading the final composite from GL
    const int screenWidth = int(neoWidth());
    const int screenHeight = int(neoHeight());
    const int screenSize = screenWidth * screenHeight;
    auto pixels = u::unique_ptr<unsigned char>(new unsigned char[screenSize * 3]);

    // make sure we're reading from the final framebuffer when obtaining the pixels
    // for the screenshot.
    gl::BindFramebuffer(GL_READ_FRAMEBUFFER, 0);
    gl::PixelStorei(GL_PACK_ALIGNMENT, 1);
    gl::ReadPixels(0, 0, screenWidth, screenHeight, GL_RGB, GL_UNSIGNED_BYTE,
        (GLvoid *)pixels.get());
    gl::PixelStorei(GL_PACK_ALIGNMENT, 8);

    // Reorient because it will be upside down
    auto temp = u::unique_ptr<unsigned char>(new unsigned char[screenSize * 3]);
    texture::reorient(pixels.get(), screenWidth, screenHeight, 3, screenWidth * 3,
        temp.get(), false, true, false);

    // Write the data
    if (bmpWrite(file, screenWidth, screenHeight, temp.get()))
        u::print("[screenshot] => %s\n", file);
}

VAR(float, cl_fov, "field of view", 45.0f, 270.0f, 90.0f);
VAR(float, cl_nearp, "near plane", 0.0f, 10.0f, 1.0f);
VAR(float, cl_farp, "far plane", 128.0f, 4096.0f, 2048.0f);

int neoMain(frameTimer &timer, int, char **) {
    r::splashScreen gSplash;
    if (!gSplash.load("textures/logo"))
        neoFatal("failed to load splash screen");
    gSplash.upload();

    r::gui gGui;
    if (!gGui.load("fonts/droidsans"))
        neoFatal("failed to load font");
    if (!gGui.upload())
        neoFatal("failed to initialize GUI rendering method\n");

    r::rendererPipeline pipeline;
    m::perspectiveProjection projection;
    projection.fov = cl_fov;
    projection.width = neoWidth();
    projection.height = neoHeight();
    projection.nearp = cl_nearp;
    projection.farp = cl_farp;

    pipeline.setPerspectiveProjection(projection);
    pipeline.setWorldPosition(m::vec3::origin);

    // create a loader thread
    loadThreadData loadData;
    SDL_AtomicSet(&loadData.done, kLoadInProgress);
    SDL_CreateThread((SDL_ThreadFunction)&loadThread, nullptr, (void*)&loadData);

    // while that thread is running render the loading screen
    while (SDL_AtomicGet(&loadData.done) == kLoadInProgress) {
        gl::Clear(GL_COLOR_BUFFER_BIT);
        pipeline.setTime(timer.ticks() / 500.0f);
        gSplash.render(pipeline);
        neoSwap();
    }

    if (SDL_AtomicGet(&loadData.done) != kLoadSucceeded)
        return 1;

    // Now render the menu
    client gClient;

    bool running = true;
    bool playing = false;
    bool input = false;
    u::string inputString = "";

    menuRegister("running", running);
    menuRegister("playing", playing);
    menuReset(); // To initialize

    neoSetWindowTitle("Neothyne");
    neoCenterMouse();
    int mouse[4] = {0}; // X, Y, Scroll, Button
    while (running) {
        if (!input)
            gClient.update(loadData.gMap, timer.delta());

        pipeline.setRotation(gClient.getRotation());
        pipeline.setPosition(gClient.getPosition());
        pipeline.setTime(timer.ticks());

        if (playing) {
            loadData.gWorld.upload(projection);
            gl::ClearColor(0.0f, 0.0f, 0.0f, 0.0f);
            loadData.gWorld.render(pipeline);
        } else {
            gl::ClearColor(40/255.0f, 30/255.0f, 50/255.0f, 0.1f);
            gl::Clear(GL_COLOR_BUFFER_BIT);
        }
        gGui.render(pipeline);
        neoSwap();

        SDL_Event e;
        mouse[2] = 0;
        while (SDL_PollEvent(&e)) {
            switch (e.type) {
                case SDL_QUIT:
                    running = false;
                    break;
                case SDL_WINDOWEVENT:
                    switch (e.window.event) {
                        case SDL_WINDOWEVENT_RESIZED:
                            // Resize the window
                            neoResize(e.window.data1, e.window.data2);
                            projection.width = neoWidth();
                            projection.height = neoHeight();
                            pipeline.setPerspectiveProjection(projection);
                            break;
                    }
                    break;
                case SDL_KEYDOWN:
                    switch (e.key.keysym.sym) {
                        case SDLK_ESCAPE:
                            // The effect of the ESC key is strange. When in game
                            // it should bring up the menu. While in the menu it
                            // should always bring you to main menu, except while
                            // in game and in menu and already at main menu then
                            // ESC should bring you back in game.
                            if (playing && gMenuState & kMenuMain) {
                                if (gMenuState & kMenuConsole) {
                                    gMenuState = kMenuConsole;
                                } else {
                                    gMenuState &= ~kMenuMain;
                                    //neoRelativeMouse(true);
                                }
                            } else {
                                // If the console is opened leave it open
                                gMenuState = (gMenuState & kMenuConsole)
                                    ? kMenuMain | kMenuConsole
                                    : kMenuMain;
                            }
                            if (playing && !(gMenuState & kMenuMain))
                                neoRelativeMouse(true);
                            else
                                neoRelativeMouse(false);
                            neoCenterMouse();
                            break;
                        case SDLK_F8:
                            screenShot();
                            break;
                        case SDLK_F9:
                            u::print("%d fps : %.2f mspf\n", timer.fps(), timer.mspf());
                            break;
                        case SDLK_F11:
                            gMenuState ^= kMenuConsole;
                            break;
                        case SDLK_BACKSPACE:
                            if (input)
                                inputString.pop_back();
                            break;
                        case SDLK_SLASH:
                            input = !input;
                            if (input) {
                                SDL_StartTextInput();
                            } else {
                                SDL_StopTextInput();
                            }
                            inputString.reset();
                            break;
                        case SDLK_RETURN:
                            if (input) {
                                auto split = u::split(inputString);
                                switch (c::varChange(split[0], split[1], true)) {
                                    case c::kVarNotFoundError:
                                        u::print("'%s' not found\n", split[0]);
                                        break;
                                    case c::kVarRangeError:
                                        u::print("invalid range '%s' for '%s'\n", split[1], split[0]);
                                        break;
                                    case c::kVarReadOnlyError:
                                        u::print("'%s' is read only\n", split[0]);
                                        break;
                                    case c::kVarTypeError:
                                        u::print("value '%s' wrong type for '%s'\n", split[1], split[0]);
                                        break;
                                    case c::kVarSuccess:
                                        u::print("'%s' changed\n", split[0]);
                                        break;
                                }
                                input = false;
                                inputString.reset();
                            }
                    }
                    neoKeyState(e.key.keysym.sym, true);
                    break;
                case SDL_KEYUP:
                    neoKeyState(e.key.keysym.sym, false, true);
                    break;
                case SDL_MOUSEMOTION:
                    mouse[0] = e.motion.x;
                    mouse[1] = neoHeight() - e.motion.y;
                    break;
                case SDL_MOUSEWHEEL:
                    mouse[2] = e.wheel.y;
                    break;
                case SDL_MOUSEBUTTONDOWN:
                    switch (e.button.button) {
                        case SDL_BUTTON_LEFT:
                            mouse[3] |= gui::kMouseButtonLeft;
                            break;
                        case SDL_BUTTON_RIGHT:
                            mouse[3] |= gui::kMouseButtonRight;
                            break;
                    }
                    break;
                case SDL_MOUSEBUTTONUP:
                    switch (e.button.button) {
                        case SDL_BUTTON_LEFT:
                            mouse[3] &= ~gui::kMouseButtonLeft;
                            break;
                        case SDL_BUTTON_RIGHT:
                            mouse[3] &= ~gui::kMouseButtonRight;
                            break;
                    }
                    break;
                case SDL_TEXTINPUT:
                    inputString += e.text.text;
                    break;
            }
        }

        gui::begin(mouse);

        // Must come first as we want the menu to go over the cross hair if it's
        // launched after playing
        if (playing) {
            gui::drawLine(neoWidth() / 2, neoHeight() / 2 - 10, neoWidth() / 2, neoHeight() / 2 - 4, 2, 0xFFFFFFE1);
            gui::drawLine(neoWidth() / 2, neoHeight() / 2 + 4, neoWidth() / 2, neoHeight() / 2 + 10, 2, 0xFFFFFFE1);
            gui::drawLine(neoWidth() / 2 + 10, neoHeight() / 2, neoWidth() / 2 + 4, neoHeight() / 2, 2, 0xFFFFFFE1);
            gui::drawLine(neoWidth() / 2 - 10, neoHeight() / 2, neoWidth() / 2 - 4, neoHeight() / 2, 2, 0xFFFFFFE1);
        }

        menuUpdate();

        // Render FPS/MSPF
        gui::drawText(neoWidth() - 10, 10, gui::kAlignRight,
            u::format("%d fps : %.2f mspf\n", timer.fps(), timer.mspf()),
            gui::RGBA(255, 255, 255, 255));

        if (input) {
            if (inputString[0] == '/')
                inputString.pop_front();
            // Accepting console commands
            gui::drawTriangle(5, 10, 10, 10, 1, gui::RGBA(155, 155, 155, 255));
            gui::drawText(20, 10, gui::kAlignLeft,
                inputString, gui::RGBA(255, 255, 255, 255));
        }

        gui::finish();
    }

    c::writeConfig();

    SDL_Quit();
    return 0;
}
<|endoftext|>


<commit_before>222aea63-2748-11e6-8872-e0f84713e7b8<commit_msg>more fixes<commit_after>223b29ae-2748-11e6-a827-e0f84713e7b8<|endoftext|>


<commit_before>5a00aad7-ad59-11e7-a5fe-ac87a332f658<commit_msg>Initial commit.2<commit_after>5ad56fa1-ad59-11e7-b3b0-ac87a332f658<|endoftext|>


<commit_before>df3742a3-4b02-11e5-86bf-28cfe9171a43<commit_msg>fixes, fixes for everyone<commit_after>df4418d9-4b02-11e5-824a-28cfe9171a43<|endoftext|>


<commit_before>314d0294-2748-11e6-baea-e0f84713e7b8<commit_msg>Long commit messages are not required<commit_after>315e28b5-2748-11e6-909d-e0f84713e7b8<|endoftext|>


<commit_before>0d8ad4e8-ad5d-11e7-b515-ac87a332f658<commit_msg>That didn't fix it<commit_after>0e1f0fca-ad5d-11e7-a3b3-ac87a332f658<|endoftext|>


<commit_before>7cb531f3-4b02-11e5-9310-28cfe9171a43<commit_msg>Backup, rebase this later<commit_after>7cc18f94-4b02-11e5-be12-28cfe9171a43<|endoftext|>


<commit_before>#include "CMT.h"
#include "gui.h"

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <iostream>
#include <fstream>
#include <cstdio>

#ifdef __GNUC__
#include <getopt.h>
#else
#include "getopt/getopt.h"
#endif

using cmt::CMT;
using cv::imread;
using cv::namedWindow;
using cv::Scalar;
using cv::VideoCapture;
using cv::waitKey;
using std::cerr;
using std::ifstream;
using std::ofstream;
using std::cout;
using std::endl;

static string WIN_NAME = "CMT";

int display(Mat im, CMT & cmt)
{
    //Visualize the output
    //It is ok to draw on im itself, as CMT only uses the grayscale image
    for(size_t i = 0; i < cmt.points_active.size(); i++)
    {
        circle(im, cmt.points_active[i], 2, Scalar(255,0,0));
    }

    Point2f vertices[4];
    cmt.bb_rot.points(vertices);
    for (int i = 0; i < 4; i++)
    {
        line(im, vertices[i], vertices[(i+1)%4], Scalar(255,0,0));
    }

    imshow(WIN_NAME, im);

    return waitKey(5);
}

int main(int argc, char **argv)
{
    //Create a CMT object
    CMT cmt;

    //Initialization bounding box
    Rect rect;

    //Parse args
    int challenge_flag = 0;
    int verbose_flag = 0;
    int bbox_flag = 0;
    string input_path;

    const int detector_cmd = 1000;
    const int descriptor_cmd = 1001;
    const int bbox_cmd = 1002;

    struct option longopts[] =
    {
        //No-argument options
        {"challenge", no_argument, &challenge_flag, 1},
        {"verbose", no_argument, &verbose_flag, 1},
        //Argument options
        {"bbox", required_argument, 0, bbox_cmd},
        {"detector", required_argument, 0, detector_cmd},
        {"descriptor", required_argument, 0, descriptor_cmd},
        {0, 0, 0, 0}
    };

    int index = 0;
    int c;
    while((c = getopt_long(argc, argv, "v", longopts, &index)) != -1)
    {
        switch (c)
        {
            case 'v':
                verbose_flag = true;
                break;
            case bbox_cmd:
                {
                    //TODO: The following also accepts strings of the form %f,%f,%f,%fxyz...
                    string bbox_format = "%f,%f,%f,%f";
                    float x,y,w,h;
                    int ret = sscanf(optarg, bbox_format.c_str(), &x, &y, &w, &h);
                    if (ret != 4)
                    {
                        cerr << "bounding box must be given in format " << bbox_format << endl;
                        return 1;
                    }

                    bbox_flag = 1;
                    rect = Rect(x,y,w,h);
                }
                break;
            case detector_cmd:
                cmt.str_detector = optarg;
                break;
            case descriptor_cmd:
                cmt.str_descriptor = optarg;
                break;
            case '?':
                return 1;
        }

    }

    //One argument remains
    if (optind == argc - 1)
    {
        input_path = argv[optind];
    }

    else if (optind < argc - 1)
    {
        cerr << "Only one argument is allowed." << endl;
        return 1;
    }

    //Set up logging
    FILELog::ReportingLevel() = verbose_flag ? logDEBUG : logINFO;
    Output2FILE::Stream() = stdout; //Log to stdout

    //Challenge mode
    if (challenge_flag)
    {
        //Read list of images
        ifstream im_file("images.txt");
        vector<string> files;
        string line;
        while(im_file >> line)
        {
            files.push_back(line);
        }

        //Read region
        float x,y,w,h;
        char a;
        ifstream region_file("region.txt");
        region_file >> x >> a >> y >> a >> w >> a >> h;
        rect = Rect(x,y,w,h);

        //Read first image
        Mat im0 = imread(files[0]);
        Mat im0_gray;
        cvtColor(im0, im0_gray, CV_BGR2GRAY);

        //Initialize cmt
        cmt.initialize(im0_gray, rect);

        //Write init region to output file
        ofstream output_file("output.txt");
        output_file << rect.x << ',' << rect.y << ',' << rect.width << ',' << rect.height << std::endl;

        //Process images, write output to file
        for (size_t i = 1; i < files.size(); i++)
        {
            FILE_LOG(logINFO) << "Processing frame " << i << "/" << files.size();
            Mat im = imread(files[i]);
            Mat im_gray;
            cvtColor(im, im_gray, CV_BGR2GRAY);
            cmt.processFrame(im_gray);
            if (verbose_flag)
            {
                display(im, cmt);
            }
            rect = cmt.bb_rot.boundingRect();
            output_file << rect.x << ',' << rect.y << ',' << rect.width << ',' << rect.height << std::endl;
        }

        output_file.close();

        return 0;
    }

    //Normal mode

    //Create window
    namedWindow(WIN_NAME);

    VideoCapture cap;

    bool show_preview = true;

    //If no input was specified
    if (input_path.length() == 0)
    {
        cap.open(0); //Open default camera device
    }

    //Else open the video specified by input_path
    else
    {
        cap.open(input_path);
        show_preview = false;
    }

    //If it doesn't work, stop
    if(!cap.isOpened())
    {
        cerr << "Unable to open video capture." << endl;
        return -1;
    }

    //Show preview until key is pressed
    while (show_preview)
    {
        Mat preview;
        cap >> preview;

        screenLog(preview, "Press a key to start selecting an object.");
        imshow(WIN_NAME, preview);

        char k = waitKey(10);
        if (k != -1) {
            show_preview = false;
        }
    }

    //Get initial image
    Mat im0;
    cap >> im0;

    //If no bounding was specified, get it from user
    if (!bbox_flag)
    {
        rect = getRect(im0, WIN_NAME);
    }

    FILE_LOG(logINFO) << "Using " << rect.x << "," << rect.y << "," << rect.width << "," << rect.height
        << " as initial bounding box.";

    //Convert im0 to grayscale
    Mat im0_gray;
    cvtColor(im0, im0_gray, CV_BGR2GRAY);

    //Initialize CMT
    cmt.initialize(im0_gray, rect);

    int frame = 0;

    //Main loop
    while (true)
    {
        frame++;

        Mat im;
        cap >> im;

        Mat im_gray;
        cvtColor(im, im_gray, CV_BGR2GRAY);

        //Let CMT process the frame
        cmt.processFrame(im_gray);

        char key = display(im, cmt);

        if(key == 'q') break;

        //TODO: Provide meaningful output
        FILE_LOG(logINFO) << "#" << frame << " active: " << cmt.points_active.size();
    }

    return 0;
}
<commit_msg>Added --loop flag<commit_after>#include "CMT.h"
#include "gui.h"

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <iostream>
#include <fstream>
#include <cstdio>

#ifdef __GNUC__
#include <getopt.h>
#else
#include "getopt/getopt.h"
#endif

using cmt::CMT;
using cv::imread;
using cv::namedWindow;
using cv::Scalar;
using cv::VideoCapture;
using cv::waitKey;
using std::cerr;
using std::ifstream;
using std::ofstream;
using std::cout;
using std::endl;

static string WIN_NAME = "CMT";

int display(Mat im, CMT & cmt)
{
    //Visualize the output
    //It is ok to draw on im itself, as CMT only uses the grayscale image
    for(size_t i = 0; i < cmt.points_active.size(); i++)
    {
        circle(im, cmt.points_active[i], 2, Scalar(255,0,0));
    }

    Point2f vertices[4];
    cmt.bb_rot.points(vertices);
    for (int i = 0; i < 4; i++)
    {
        line(im, vertices[i], vertices[(i+1)%4], Scalar(255,0,0));
    }

    imshow(WIN_NAME, im);

    return waitKey(5);
}

int main(int argc, char **argv)
{
    //Create a CMT object
    CMT cmt;

    //Initialization bounding box
    Rect rect;

    //Parse args
    int challenge_flag = 0;
    int loop_flag = 0;
    int verbose_flag = 0;
    int bbox_flag = 0;
    string input_path;

    const int detector_cmd = 1000;
    const int descriptor_cmd = 1001;
    const int bbox_cmd = 1002;

    struct option longopts[] =
    {
        //No-argument options
        {"challenge", no_argument, &challenge_flag, 1},
        {"loop", no_argument, &loop_flag, 1},
        {"verbose", no_argument, &verbose_flag, 1},
        //Argument options
        {"bbox", required_argument, 0, bbox_cmd},
        {"detector", required_argument, 0, detector_cmd},
        {"descriptor", required_argument, 0, descriptor_cmd},
        {0, 0, 0, 0}
    };

    int index = 0;
    int c;
    while((c = getopt_long(argc, argv, "v", longopts, &index)) != -1)
    {
        switch (c)
        {
            case 'v':
                verbose_flag = true;
                break;
            case bbox_cmd:
                {
                    //TODO: The following also accepts strings of the form %f,%f,%f,%fxyz...
                    string bbox_format = "%f,%f,%f,%f";
                    float x,y,w,h;
                    int ret = sscanf(optarg, bbox_format.c_str(), &x, &y, &w, &h);
                    if (ret != 4)
                    {
                        cerr << "bounding box must be given in format " << bbox_format << endl;
                        return 1;
                    }

                    bbox_flag = 1;
                    rect = Rect(x,y,w,h);
                }
                break;
            case detector_cmd:
                cmt.str_detector = optarg;
                break;
            case descriptor_cmd:
                cmt.str_descriptor = optarg;
                break;
            case '?':
                return 1;
        }

    }

    //One argument remains
    if (optind == argc - 1)
    {
        input_path = argv[optind];
    }

    else if (optind < argc - 1)
    {
        cerr << "Only one argument is allowed." << endl;
        return 1;
    }

    //Set up logging
    FILELog::ReportingLevel() = verbose_flag ? logDEBUG : logINFO;
    Output2FILE::Stream() = stdout; //Log to stdout

    //Challenge mode
    if (challenge_flag)
    {
        //Read list of images
        ifstream im_file("images.txt");
        vector<string> files;
        string line;
        while(im_file >> line)
        {
            files.push_back(line);
        }

        //Read region
        float x,y,w,h;
        char a;
        ifstream region_file("region.txt");
        region_file >> x >> a >> y >> a >> w >> a >> h;
        rect = Rect(x,y,w,h);

        //Read first image
        Mat im0 = imread(files[0]);
        Mat im0_gray;
        cvtColor(im0, im0_gray, CV_BGR2GRAY);

        //Initialize cmt
        cmt.initialize(im0_gray, rect);

        //Write init region to output file
        ofstream output_file("output.txt");
        output_file << rect.x << ',' << rect.y << ',' << rect.width << ',' << rect.height << std::endl;

        //Process images, write output to file
        for (size_t i = 1; i < files.size(); i++)
        {
            FILE_LOG(logINFO) << "Processing frame " << i << "/" << files.size();
            Mat im = imread(files[i]);
            Mat im_gray;
            cvtColor(im, im_gray, CV_BGR2GRAY);
            cmt.processFrame(im_gray);
            if (verbose_flag)
            {
                display(im, cmt);
            }
            rect = cmt.bb_rot.boundingRect();
            output_file << rect.x << ',' << rect.y << ',' << rect.width << ',' << rect.height << std::endl;
        }

        output_file.close();

        return 0;
    }

    //Normal mode

    //Create window
    namedWindow(WIN_NAME);

    VideoCapture cap;

    bool show_preview = true;

    //If no input was specified
    if (input_path.length() == 0)
    {
        cap.open(0); //Open default camera device
    }

    //Else open the video specified by input_path
    else
    {
        cap.open(input_path);
        show_preview = false;
    }

    //If it doesn't work, stop
    if(!cap.isOpened())
    {
        cerr << "Unable to open video capture." << endl;
        return -1;
    }

    //Show preview until key is pressed
    while (show_preview)
    {
        Mat preview;
        cap >> preview;

        screenLog(preview, "Press a key to start selecting an object.");
        imshow(WIN_NAME, preview);

        char k = waitKey(10);
        if (k != -1) {
            show_preview = false;
        }
    }

    //Get initial image
    Mat im0;
    cap >> im0;

    //If no bounding was specified, get it from user
    if (!bbox_flag)
    {
        rect = getRect(im0, WIN_NAME);
    }

    FILE_LOG(logINFO) << "Using " << rect.x << "," << rect.y << "," << rect.width << "," << rect.height
        << " as initial bounding box.";

    //Convert im0 to grayscale
    Mat im0_gray;
    cvtColor(im0, im0_gray, CV_BGR2GRAY);

    //Initialize CMT
    cmt.initialize(im0_gray, rect);

    int frame = 0;

    //Main loop
    while (true)
    {
        frame++;

        Mat im;

        //If loop flag is set, reuse initial image (for debugging purposes)
        if (loop_flag) im0.copyTo(im);
        else cap >> im; //Else use next image in stream

        Mat im_gray;
        cvtColor(im, im_gray, CV_BGR2GRAY);

        //Let CMT process the frame
        cmt.processFrame(im_gray);

        char key = display(im, cmt);

        if(key == 'q') break;

        //TODO: Provide meaningful output
        FILE_LOG(logINFO) << "#" << frame << " active: " << cmt.points_active.size();
    }

    return 0;
}
<|endoftext|>


<commit_before>b522a8ba-2747-11e6-b46c-e0f84713e7b8<commit_msg>The previous fix has been fixed<commit_after>b5359c5e-2747-11e6-9b7a-e0f84713e7b8<|endoftext|>


<commit_before>dc44862e-4b02-11e5-8f28-28cfe9171a43<commit_msg>That didn't fix it<commit_after>dc52136e-4b02-11e5-bf98-28cfe9171a43<|endoftext|>


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

     BSD 3-Clause License (https://www.tldrlegal.com/l/bsd3)

     Copyright (c) 2015 Andrés Solís Montero <http://www.solism.ca>, All rights reserved.

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

     1. Redistributions of source code must retain the above copyright notice,
        this list of conditions and the following disclaimer.
     2. Redistributions in binary form must reproduce the above copyright notice,
        this list of conditions and the following disclaimer in the documentation
        and/or other materials provided with the distribution.
     3. Neither the name of the copyright holder nor the names of its contributors
        may be used to endorse or promote products derived from this software
        without specific prior written permission.

     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
     AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
     LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
     OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
     OF THE POSSIBILITY OF SUCH DAMAGE.

 **************************************************************************************************
 **************************************************************************************************/

#include "aprocess.h"

using namespace viva;

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

    const String keys =
        "{help h            |           | print this message}"
        "{@sequence         |           | url, file, folder, sequence}"
        "{m method          |p          | choices =  p | r | a  (i.e., poly, rotated rect, axis aligned rect}"
        "{W width           |-1         | scale input using this width, keeps aspect ratio annotations will be transformed to the initial image size}"
        "{H height          |-1         | scale input using this height, keeps aspect ratio annotations will be transformed to the initial image size}"
        "{r ratio           |-1         | ratio = height/width, -1 no constraints}"
        "{t track           |e          | choices =  e | d | n  (i.e., enable, disable, and new). The 'e' enable option will generate a proposal position for next frame. Disable 'd' option will keep the same position from previous frame. New 'n' will clear the annotations from previous frame}"
        "{o output          |           | filename for annnotation results}"

    ;

    CommandLineParser parser(argc, argv, keys);

    if (parser.has("h"))
        parser.printMessage();

    string sequence = parser.get<string>(0);
    string mname    = parser.get<string>("m");

    Ptr<Input> input = InputFactory::create(sequence,
                                    Size(parser.get<int>("W"),
                                         parser.get<int>("H")));

    int method = AnnotateProcess::POLY;
    if (mname == "a")
        method = AnnotateProcess::AXIS_RECT;
    else if (mname == "r")
        method = AnnotateProcess::ROTA_RECT;

    string track = parser.get<string>("t");
    bool continuity = (track == "d" || track == "e");
    bool tracking   = (track == "e");
    Ptr<AnnotateProcess> process =
                new AnnotateProcess(parser.get<float>("r"),
                                    method, continuity, tracking);

    Processor processor;
    processor.setInput(input);
    Ptr<ProcessFrame> proc = process;
    processor.setProcess(proc);
    processor.startPaused();
    processor.listenToMouseEvents();
    processor.listenToKeyboardEvents();
    processor.run();

    if (parser.has("o"))
    {
        Size org = input->getOrgSize();
        Size cur = Size(input->getWidth(), input->getHeight());

        string annotations = parser.get<string>("o");
        process->writeAnnotations(annotations,
                                  (float)org.width/(float)cur.width,
                                  (float)org.height/(float)cur.height);
    }

    return 0;
}<commit_msg>add the xml output format to the select option<commit_after>/**************************************************************************************************
 **************************************************************************************************

     BSD 3-Clause License (https://www.tldrlegal.com/l/bsd3)

     Copyright (c) 2015 Andrés Solís Montero <http://www.solism.ca>, All rights reserved.

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

     1. Redistributions of source code must retain the above copyright notice,
        this list of conditions and the following disclaimer.
     2. Redistributions in binary form must reproduce the above copyright notice,
        this list of conditions and the following disclaimer in the documentation
        and/or other materials provided with the distribution.
     3. Neither the name of the copyright holder nor the names of its contributors
        may be used to endorse or promote products derived from this software
        without specific prior written permission.

     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
     AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
     LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
     OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
     OF THE POSSIBILITY OF SUCH DAMAGE.

 **************************************************************************************************
 **************************************************************************************************/

#include "aprocess.h"

using namespace viva;

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

    const String keys =
        "{help h            |           | print this message}"
        "{@sequence         |           | url, file, folder, sequence}"
        "{m method          |p          | choices =  p | r | a  (i.e., poly, rotated rect, axis aligned rect}"
        "{W width           |-1         | scale input using this width, keeps aspect ratio annotations will be transformed to the initial image size}"
        "{H height          |-1         | scale input using this height, keeps aspect ratio annotations will be transformed to the initial image size}"
        "{r ratio           |-1         | ratio = height/width, -1 no constraints}"
        "{t track           |e          | choices =  e | d | n  (i.e., enable, disable, and new). The 'e' enable option will generate a proposal position for next frame. Disable 'd' option will keep the same position from previous frame. New 'n' will clear the annotations from previous frame}"
        "{o output          |           | filename for annnotation results}"
		"{ox output XML		|			| filename for xml file annotation results}"

    ;

    CommandLineParser parser(argc, argv, keys);

    if (parser.has("h"))
        parser.printMessage();

    string sequence = parser.get<string>(0);
    string mname    = parser.get<string>("m");

    Ptr<Input> input = InputFactory::create(sequence,
                                    Size(parser.get<int>("W"),
                                         parser.get<int>("H")));

    int method = AnnotateProcess::POLY;
    if (mname == "a")
        method = AnnotateProcess::AXIS_RECT;
    else if (mname == "r")
        method = AnnotateProcess::ROTA_RECT;

    string track = parser.get<string>("t");
    bool continuity = (track == "d" || track == "e");
    bool tracking   = (track == "e");
    Ptr<AnnotateProcess> process =
                new AnnotateProcess(parser.get<float>("r"),
                                    method, continuity, tracking);

    Processor processor;
    processor.setInput(input);
    Ptr<ProcessFrame> proc = process;
    processor.setProcess(proc);
    processor.startPaused();
    processor.listenToMouseEvents();
    processor.listenToKeyboardEvents();
    processor.run();

	Size org = input->getOrgSize();
	Size cur = Size(input->getWidth(), input->getHeight());
    if (parser.has("o"))
    {
        string annotations = parser.get<string>("o");
        process->writeAnnotations(annotations,
                                  (float)org.width/(float)cur.width,
                                  (float)org.height/(float)cur.height);
    }

	if (parser.has("ox"))
	{
		string annotations = parser.get<string>("ox");
		process->writeXMLAnnotations(annotations,
			(float)org.width / (float)cur.width,
			(float)org.height / (float)cur.height);
	}

    return 0;
}
<|endoftext|>


<commit_before>d17381bd-4b02-11e5-805c-28cfe9171a43<commit_msg>Long commit messages are not required<commit_after>d18119e6-4b02-11e5-bb4a-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>
#include <map>
#include <math.h>

using namespace std;

const int n = 9;

bool fun(bool *x)
{
	for (unsigned int j = 0; j < n-2; ++j)
		if ((x[j] != x[j+1]) && (x[j] != x[j+2]))
			return false;
	return true;
}

class Expr
{
public:
	Expr(){}
	virtual operator bool() const = 0;
};
typedef shared_ptr<Expr> PExpr;

class Disjunction: public Expr
{
public:
	Disjunction(PExpr pLeft, PExpr pRight)
		: left (pLeft )
		, right(pRight)
	{}
	operator bool() const
	{
		return *left || *right;
	}

private:
	PExpr left;
	PExpr right;
};

class Conjunction: public Expr
{
public:
	Conjunction(PExpr pLeft, PExpr pRight)
		: left (pLeft )
		, right(pRight)
	{}
	operator bool() const
	{
		return *left && *right;
	}

private:
	PExpr left;
	PExpr right;
};

class Negation: public Expr
{
public:
	Negation(PExpr pExpr)
		: expr(pExpr)
	{}
	operator bool() const
	{
		return !(*expr);
	}

private:
	PExpr expr;
};

class ValueToken: public Expr
{
public:
	ValueToken(bool b)
		: value(b)
	{}
	operator bool() const
	{
		return value;
	}

private:
	bool value;
};

enum Token_value
{
	NAME, NUMBER, END = ';',
	OR = '|', AND = '&', NOT = '!',
	EQV = '=', LP = '(', RP = ')'
};

Token_value curr_tok = END;
bool number_value;
string string_value;
map<string, bool> table;
int no_of_errors;

PExpr expr(bool);

int error(const string& s)
{
	++no_of_errors;
	cerr << "ошибка: " << s << endl;
	return 1;
}

Token_value get_token()
{
	char ch = 0;
	cin >> ch;
	switch(ch)
	{
	case 0:
		return curr_tok = END;
	case ';':
	case '&':
	case '|':
	case '(':
	case ')':
	case '=':
	case '!':
		return curr_tok = Token_value(ch);
	case '0': case '1': case '2': case '3': case '4':
	case '5': case '6': case '7': case '8': case '9':
	case '.':
		cin.putback(ch);
		cin >> number_value;
		return curr_tok = NUMBER;
	default:
		if (isalpha(ch))
		{
			cin.putback(ch);
			cin >> string_value;
			return curr_tok = NAME;
		}
		else
		{
			error("неправильная лексема");
			return curr_tok = END;
		}
	}
}

PExpr prim(bool get)
{
	if (get)
		get_token();

	switch(curr_tok)
	{
	case NUMBER:
	{
		bool v = number_value;
		get_token();
		return make_shared<ValueToken>(v);
	}
	case LP:
	{
		PExpr e = expr(true);
		if (curr_tok != RP)
			error("ожидалась )");
		get_token();
		return e;
	}
	case NOT:
	{
		PExpr e = expr(true);
		e = make_shared<Negation>(e);
		get_token();
		return e;
	}
	default:
		return PExpr();
	}
}

PExpr term(bool get)
{
	PExpr pLeft = prim(get);
	while (true)
	{
		switch(curr_tok)
		{
		case AND:
		{
			PExpr pRight = prim(true);
			pLeft = make_shared<Conjunction>(pLeft, pRight);
			break;
		}
		default:
			return pLeft;
		}
	}
}

PExpr expr(bool get)
{
	PExpr pLeft = term(get);
	while (true)
	{
		switch(curr_tok)
		{
		case OR:
		{
			PExpr pRight = term(true);
			pLeft = make_shared<Disjunction>(pLeft, pRight);
			break;
		}
		default:
			return pLeft;
		}
	}
}

void compile()
{
	freopen("input.txt", "r", stdin);
	while(cin)
	{
		get_token();
		if (curr_tok == END)
			break;
		cout << *expr(false) << endl;
	}
}

void overrun()
{
	for (unsigned int i = 0; i < pow(2, n); ++i)
	{
		bool x[n];
		unsigned k = i;
		for (unsigned int j = 0; j < n; ++j)
		{
			x[n-j-1] = 0x1 & k;
			k >>= 1;
		}
		if (fun(x))
		{
			for (unsigned int j = 0; j < n; ++j)
				cout << x[j];
			cout << endl;
		}
	}
}

int main(int argc, char* argv[])
{
	switch(argc)
	{
	case 1:
		cout << "запуск без параметров. выбран режим работы по умолчанию." << endl;
		overrun();
		return 0;
	case 2:
		if (!strcmp(argv[1],"-d"))
		{
			cout << "режим работы по умолчанию" << endl;
			overrun();
			return 0;
		}
		if (!strcmp(argv[1],"-i"))
		{
			cout << "интерактивный режим работы" << endl;
			compile();
			return(10);
		}
		cout << "неизвестный параметр" << endl;
		return(1);
	default:
		cout << "слишком много параметров" << endl;
		return(2);
	}
}
<commit_msg>add equality<commit_after>#include <iostream>
#include <map>
#include <math.h>

using namespace std;

const int n = 9;

bool fun(bool *x)
{
	for (unsigned int j = 0; j < n-2; ++j)
		if ((x[j] != x[j+1]) && (x[j] != x[j+2]))
			return false;
	return true;
}

class Expr
{
public:
	Expr(){}
	virtual operator bool() const = 0;
};
typedef shared_ptr<Expr> PExpr;

class Equality: public Expr
{
public:
	Equality(PExpr pLeft, PExpr pRight)
		: left (pLeft )
		, right(pRight)
	{}
	operator bool() const
	{
		return *left == *right;
	}

private:
	PExpr left;
	PExpr right;
};

class Disjunction: public Expr
{
public:
	Disjunction(PExpr pLeft, PExpr pRight)
		: left (pLeft )
		, right(pRight)
	{}
	operator bool() const
	{
		return *left || *right;
	}

private:
	PExpr left;
	PExpr right;
};

class Conjunction: public Expr
{
public:
	Conjunction(PExpr pLeft, PExpr pRight)
		: left (pLeft )
		, right(pRight)
	{}
	operator bool() const
	{
		return *left && *right;
	}

private:
	PExpr left;
	PExpr right;
};

class Negation: public Expr
{
public:
	Negation(PExpr pExpr)
		: expr(pExpr)
	{}
	operator bool() const
	{
		return !(*expr);
	}

private:
	PExpr expr;
};

class ValueToken: public Expr
{
public:
	ValueToken(bool b)
		: value(b)
	{}
	operator bool() const
	{
		return value;
	}

private:
	bool value;
};

enum Token_value
{
	NAME, NUMBER, END = ';',
	OR = '|', AND = '&', NOT = '!',
	EQL = '=', LP = '(', RP = ')'
};

Token_value curr_tok = END;
bool number_value;
string string_value;
map<string, bool> table;
int no_of_errors;

PExpr equal_expr(bool);

int error(const string& s)
{
	++no_of_errors;
	cerr << "ошибка: " << s << endl;
	return 1;
}

Token_value get_token()
{
	char ch = 0;
	cin >> ch;
	switch(ch)
	{
	case 0:
		return curr_tok = END;
	case ';':
	case '&':
	case '|':
	case '(':
	case ')':
	case '=':
	case '!':
		return curr_tok = Token_value(ch);
	case '0': case '1': case '2': case '3': case '4':
	case '5': case '6': case '7': case '8': case '9':
	case '.':
		cin.putback(ch);
		cin >> number_value;
		return curr_tok = NUMBER;
	default:
		if (isalpha(ch))
		{
			cin.putback(ch);
			cin >> string_value;
			return curr_tok = NAME;
		}
		else
		{
			error("неправильная лексема");
			return curr_tok = END;
		}
	}
}

PExpr prim(bool get)
{
	if (get)
		get_token();

	switch(curr_tok)
	{
	case NUMBER:
	{
		bool v = number_value;
		get_token();
		return make_shared<ValueToken>(v);
	}
	case LP:
	{
		PExpr e = equal_expr(true);
		if (curr_tok != RP)
			error("ожидалась )");
		get_token();
		return e;
	}
	case NOT:
	{
		PExpr e = equal_expr(true);
		e = make_shared<Negation>(e);
		get_token();
		return e;
	}
	default:
		return PExpr();
	}
}

PExpr term(bool get)
{
	PExpr pLeft = prim(get);
	while (true)
	{
		switch(curr_tok)
		{
		case AND:
		{
			PExpr pRight = prim(true);
			pLeft = make_shared<Conjunction>(pLeft, pRight);
			break;
		}
		default:
			return pLeft;
		}
	}
}

PExpr expr(bool get)
{
	PExpr pLeft = term(get);
	while (true)
	{
		switch(curr_tok)
		{
		case OR:
		{
			PExpr pRight = term(true);
			pLeft = make_shared<Disjunction>(pLeft, pRight);
			break;
		}
		default:
			return pLeft;
		}
	}
}

PExpr equal_expr(bool get)
{
	PExpr pLeft = expr(get);
	while (true)
	{
		switch(curr_tok)
		{
		case EQL:
		{
			PExpr pRight = expr(true);
			pLeft = make_shared<Equality>(pLeft, pRight);
			break;
		}
		default:
			return pLeft;
		}
	}
}

void compile()
{
	freopen("input.txt", "r", stdin);
	while(cin)
	{
		get_token();
		if (curr_tok == END)
			break;
		cout << *equal_expr(false) << endl;
	}
}

void overrun()
{
	for (unsigned int i = 0; i < pow(2, n); ++i)
	{
		bool x[n];
		unsigned k = i;
		for (unsigned int j = 0; j < n; ++j)
		{
			x[n-j-1] = 0x1 & k;
			k >>= 1;
		}
		if (fun(x))
		{
			for (unsigned int j = 0; j < n; ++j)
				cout << x[j];
			cout << endl;
		}
	}
}

int main(int argc, char* argv[])
{
	switch(argc)
	{
	case 1:
		cout << "запуск без параметров. выбран режим работы по умолчанию." << endl;
		overrun();
		return 0;
	case 2:
		if (!strcmp(argv[1],"-d"))
		{
			cout << "режим работы по умолчанию" << endl;
			overrun();
			return 0;
		}
		if (!strcmp(argv[1],"-i"))
		{
			cout << "интерактивный режим работы" << endl;
			compile();
			return(10);
		}
		cout << "неизвестный параметр" << endl;
		return(1);
	default:
		cout << "слишком много параметров" << endl;
		return(2);
	}
}
<|endoftext|>


<commit_before>/** @file
 *****************************************************************************

 Implementation of functions for profiling code blocks.

 See profiling.hpp .

 *****************************************************************************
 * @author     This file is part of libsnark, developed by SCIPR Lab
 *             and contributors (see AUTHORS).
 * @copyright  MIT license (see LICENSE file)
 *****************************************************************************/

#include "common/profiling.hpp"
#include <cassert>
#include <stdexcept>
#include <chrono>
#include <cinttypes>
#include <cstdio>
#include <list>
#include <vector>
#include <ctime>
#include "common/default_types/ec_pp.hpp"
#include "common/utils.hpp"

#ifndef NO_PROCPS
#include <proc/readproc.h>
#endif

namespace libsnark {

int64_t get_nsec_time()
{
    auto timepoint = std::chrono::high_resolution_clock::now();
    return std::chrono::duration_cast<std::chrono::nanoseconds>(timepoint.time_since_epoch()).count();
}

/* Return total CPU time consumed by all threads of the process, in nanoseconds. */
int64_t get_nsec_cpu_time()
{
    ::timespec ts;
    if ( ::clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts) )
        throw ::std::runtime_error("clock_gettime(CLOCK_PROCESS_CPUTIME_ID) failed");
        // If we expected this to work, don't silently ignore failures, because that would hide the problem and incur an unnecessarily system-call overhead. So if we ever observe this exception, we should probably add a suitable #ifdef .
        //TODO: clock_gettime(CLOCK_PROCESS_CPUTIME_ID) is not supported by native Windows. What about Cygwin? Should we #ifdef on CLOCK_PROCESS_CPUTIME_ID or on __linux__?
    return ts.tv_sec * 1000000000ll + ts.tv_nsec;
}

static int64_t start_time;
static int64_t last_time;
static int64_t start_cpu_time;
static int64_t last_cpu_time;

void start_profiling()
{
    printf("Reset time counters for profiling\n");

    last_time = start_time = get_nsec_time();
    last_cpu_time = start_cpu_time = get_nsec_cpu_time();
}

std::map<std::string, size_t> invocation_counts;
static std::map<std::string, int64_t> enter_times;
std::map<std::string, int64_t> last_times;
std::map<std::string, int64_t> cumulative_times;
//TODO: Instead of analogous maps for time and cpu_time, use a single struct-valued map
static std::map<std::string, int64_t> enter_cpu_times;
static std::map<std::string, int64_t> last_cpu_times;
static std::map<std::pair<std::string, std::string>, int64_t> op_counts;
static std::map<std::pair<std::string, std::string>, int64_t> cumulative_op_counts; // ((msg, data_point), value)
    // TODO: Convert op_counts and cumulative_op_counts from pair to structs
static size_t indentation = 0;

static std::vector<std::string> block_names;

static std::list<std::pair<std::string, int64_t*> > op_data_points = {
#ifdef PROFILE_OP_COUNTS
    std::make_pair("Fradd", &Fr<default_ec_pp>::add_cnt),
    std::make_pair("Frsub", &Fr<default_ec_pp>::sub_cnt),
    std::make_pair("Frmul", &Fr<default_ec_pp>::mul_cnt),
    std::make_pair("Frinv", &Fr<default_ec_pp>::inv_cnt),
    std::make_pair("Fqadd", &Fq<default_ec_pp>::add_cnt),
    std::make_pair("Fqsub", &Fq<default_ec_pp>::sub_cnt),
    std::make_pair("Fqmul", &Fq<default_ec_pp>::mul_cnt),
    std::make_pair("Fqinv", &Fq<default_ec_pp>::inv_cnt),
    std::make_pair("G1add", &G1<default_ec_pp>::add_cnt),
    std::make_pair("G1dbl", &G1<default_ec_pp>::dbl_cnt),
    std::make_pair("G2add", &G2<default_ec_pp>::add_cnt),
    std::make_pair("G2dbl", &G2<default_ec_pp>::dbl_cnt)
#endif
};

bool inhibit_profiling_info = true;
bool inhibit_profiling_counters = false;

void clear_profiling_counters()
{
    invocation_counts.clear();
    last_times.clear();
    last_cpu_times.clear();
    cumulative_times.clear();
}

void print_cumulative_time_entry(const std::string &key, const int64_t factor)
{
    const double total_ms = (cumulative_times.at(key) * 1e-6);
    const size_t cnt = invocation_counts.at(key);
    const double avg_ms = total_ms / cnt;
    printf("   %-45s: %12.5fms = %" PRId64 " * %0.5fms (%zu invocations, %0.5fms = %" PRId64 " * %0.5fms per invocation)\n", key.c_str(), total_ms, factor, total_ms/factor, cnt, avg_ms, factor, avg_ms/factor);
}

void print_cumulative_times(const int64_t factor)
{
    printf("Dumping times:\n");
    for (auto& kv : cumulative_times)
    {
        print_cumulative_time_entry(kv.first, factor);
    }
}

void print_cumulative_op_counts(const bool only_fq)
{
#ifdef PROFILE_OP_COUNTS
    printf("Dumping operation counts:\n");
    for (auto& msg : invocation_counts)
    {
        printf("  %-45s: ", msg.first.c_str());
        bool first = true;
        for (auto& data_point : op_data_points)
        {
            if (only_fq && data_point.first.compare(0, 2, "Fq") != 0)
            {
                continue;
            }

            if (!first)
            {
                printf(", ");
            }
            printf("%-5s = %7.0f (%3zu)",
                   data_point.first.c_str(),
                   1. * cumulative_op_counts[std::make_pair(msg.first, data_point.first)] / msg.second,
                   msg.second);
            first = false;
        }
        printf("\n");
    }
#else
    UNUSED(only_fq);
#endif
}

void print_op_profiling(const std::string &msg)
{
#ifdef PROFILE_OP_COUNTS
    printf("\n");
    print_indent();

    printf("(opcounts) = (");
    bool first = true;
    for (std::pair<std::string, int64_t*> p : op_data_points)
    {
        if (!first)
        {
            printf(", ");
        }

        printf("%s=%lld", p.first.c_str(), *(p.second)-op_counts[std::make_pair(msg, p.first)]);
        first = false;
    }
    printf(")");
#else
    UNUSED(msg);
#endif
}

static void print_times_from_last_and_start(int64_t     now, int64_t     last,
                                            int64_t cpu_now, int64_t cpu_last)
{
    int64_t time_from_start = now - start_time;
    int64_t time_from_last = now - last;

    int64_t cpu_time_from_start = cpu_now - start_cpu_time;
    int64_t cpu_time_from_last = cpu_now - cpu_last;

    if (time_from_last != 0) {
        double parallelism_from_last = 1.0 * cpu_time_from_last / time_from_last;
        printf("[%0.4fs x%0.2f]", time_from_last * 1e-9, parallelism_from_last);
    } else {
        printf("[             ]");
    }
    if (time_from_start != 0) {
        double parallelism_from_start = 1.0 * cpu_time_from_start / time_from_start;
        printf("\t(%0.4fs x%0.2f from start)", time_from_start * 1e-9, parallelism_from_start);
    }
}

void print_time(const char* msg)
{
    if (inhibit_profiling_info)
    {
        return;
    }

    int64_t now = get_nsec_time();
    int64_t cpu_now = get_nsec_cpu_time();

    printf("%-35s\t", msg);
    print_times_from_last_and_start(now, last_time, cpu_now, last_cpu_time);
#ifdef PROFILE_OP_COUNTS
    print_op_profiling(msg);
#endif
    printf("\n");

    fflush(stdout);
    last_time = now;
    last_cpu_time = cpu_now;
}

void print_header(const char *msg)
{
    printf("\n================================================================================\n");
    printf("%s\n", msg);
    printf("================================================================================\n\n");
}

void print_indent()
{
    for (size_t i = 0; i < indentation; ++i)
    {
        printf("  ");
    }
}

void op_profiling_enter(const std::string &msg)
{
    for (std::pair<std::string, int64_t*> p : op_data_points)
    {
        op_counts[std::make_pair(msg, p.first)] = *(p.second);
    }
}

void enter_block(const std::string &msg, const bool indent)
{
    if (inhibit_profiling_counters)
    {
        return;
    }

    block_names.emplace_back(msg);
    int64_t t = get_nsec_time();
    enter_times[msg] = t;
    int64_t cpu_t = get_nsec_cpu_time();
    enter_cpu_times[msg] = cpu_t;

    if (inhibit_profiling_info)
    {
        return;
    }

#ifdef MULTICORE
#pragma omp critical
#endif
    {
        op_profiling_enter(msg);

        print_indent();
        printf("(enter) %-35s\t", msg.c_str());
        print_times_from_last_and_start(t, t, cpu_t, cpu_t);
        printf("\n");
        fflush(stdout);

        if (indent)
        {
            ++indentation;
        }
    }
}

void leave_block(const std::string &msg, const bool indent)
{
    if (inhibit_profiling_counters)
    {
        return;
    }

#ifndef MULTICORE
    assert(*(--block_names.end()) == msg);
#endif
    block_names.pop_back();

    ++invocation_counts[msg];

    int64_t t = get_nsec_time();
    last_times[msg] = (t - enter_times[msg]);
    cumulative_times[msg] += (t - enter_times[msg]);

    int64_t cpu_t = get_nsec_cpu_time();
    last_cpu_times[msg] = (cpu_t - enter_cpu_times[msg]);

#ifdef PROFILE_OP_COUNTS
    for (std::pair<std::string, int64_t*> p : op_data_points)
    {
        cumulative_op_counts[std::make_pair(msg, p.first)] += *(p.second)-op_counts[std::make_pair(msg, p.first)];
    }
#endif

    if (inhibit_profiling_info)
    {
        return;
    }

#ifdef MULTICORE
#pragma omp critical
#endif
    {
        if (indent)
        {
            --indentation;
        }

        print_indent();
        printf("(leave) %-35s\t", msg.c_str());
        print_times_from_last_and_start(t, enter_times[msg], cpu_t, enter_cpu_times[msg]);
        print_op_profiling(msg);
        printf("\n");
        fflush(stdout);
    }
}

void print_mem(const std::string &s)
{
#ifndef NO_PROCPS
    struct proc_t usage;
    look_up_our_self(&usage);
    if (s.empty())
    {
        printf("* Peak vsize (physical memory+swap) in mebibytes: %lu\n", usage.vsize >> 20);
    }
    else
    {
        printf("* Peak vsize (physical memory+swap) in mebibytes (%s): %lu\n", s.c_str(), usage.vsize >> 20);
    }
#else
    printf("* Memory profiling not supported in NO_PROCPS mode\n");
#endif
}

void print_compilation_info()
{
#ifdef __GNUC__
    printf("g++ version: %s\n", __VERSION__);
    //printf("Compiled on %s %s\n", __DATE__, __TIME__);
#endif
#ifdef STATIC
    printf("STATIC: yes\n");
#else
    printf("STATIC: no\n");
#endif
#ifdef MULTICORE
    printf("MULTICORE: yes\n");
#else
    printf("MULTICORE: no\n");
#endif
#ifdef DEBUG
    printf("DEBUG: yes\n");
#else
    printf("DEBUG: no\n");
#endif
#ifdef PROFILE_OP_COUNTS
    printf("PROFILE_OP_COUNTS: yes\n");
#else
    printf("PROFILE_OP_COUNTS: no\n");
#endif
#ifdef _GLIBCXX_DEBUG
    printf("_GLIBCXX_DEBUG: yes\n");
#else
    printf("_GLIBCXX_DEBUG: no\n");
#endif
}

} // libsnark
<commit_msg>[build] Fix macOS libsnark build<commit_after>/** @file
 *****************************************************************************

 Implementation of functions for profiling code blocks.

 See profiling.hpp .

 *****************************************************************************
 * @author     This file is part of libsnark, developed by SCIPR Lab
 *             and contributors (see AUTHORS).
 * @copyright  MIT license (see LICENSE file)
 *****************************************************************************/

#include "common/profiling.hpp"
#include <cassert>
#include <stdexcept>
#include <chrono>
#include <cinttypes>
#include <cstdio>
#include <list>
#include <vector>
#include <ctime>
#include "common/default_types/ec_pp.hpp"
#include "common/utils.hpp"

#ifndef NO_PROCPS
#include <proc/readproc.h>
#endif

namespace libsnark {

int64_t get_nsec_time()
{
    auto timepoint = std::chrono::high_resolution_clock::now();
    return std::chrono::duration_cast<std::chrono::nanoseconds>(timepoint.time_since_epoch()).count();
}

/* Return total CPU time consumed by all threads of the process, in nanoseconds. */
int64_t get_nsec_cpu_time()
{
#if defined(__linux__)
    ::timespec ts;
    if ( ::clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts) )
        throw ::std::runtime_error("clock_gettime(CLOCK_PROCESS_CPUTIME_ID) failed");
    return ts.tv_sec * 1000000000ll + ts.tv_nsec;
#else
    return 0;
#endif
}

static int64_t start_time;
static int64_t last_time;
static int64_t start_cpu_time;
static int64_t last_cpu_time;

void start_profiling()
{
    printf("Reset time counters for profiling\n");

    last_time = start_time = get_nsec_time();
    last_cpu_time = start_cpu_time = get_nsec_cpu_time();
}

std::map<std::string, size_t> invocation_counts;
static std::map<std::string, int64_t> enter_times;
std::map<std::string, int64_t> last_times;
std::map<std::string, int64_t> cumulative_times;
//TODO: Instead of analogous maps for time and cpu_time, use a single struct-valued map
static std::map<std::string, int64_t> enter_cpu_times;
static std::map<std::string, int64_t> last_cpu_times;
static std::map<std::pair<std::string, std::string>, int64_t> op_counts;
static std::map<std::pair<std::string, std::string>, int64_t> cumulative_op_counts; // ((msg, data_point), value)
    // TODO: Convert op_counts and cumulative_op_counts from pair to structs
static size_t indentation = 0;

static std::vector<std::string> block_names;

static std::list<std::pair<std::string, int64_t*> > op_data_points = {
#ifdef PROFILE_OP_COUNTS
    std::make_pair("Fradd", &Fr<default_ec_pp>::add_cnt),
    std::make_pair("Frsub", &Fr<default_ec_pp>::sub_cnt),
    std::make_pair("Frmul", &Fr<default_ec_pp>::mul_cnt),
    std::make_pair("Frinv", &Fr<default_ec_pp>::inv_cnt),
    std::make_pair("Fqadd", &Fq<default_ec_pp>::add_cnt),
    std::make_pair("Fqsub", &Fq<default_ec_pp>::sub_cnt),
    std::make_pair("Fqmul", &Fq<default_ec_pp>::mul_cnt),
    std::make_pair("Fqinv", &Fq<default_ec_pp>::inv_cnt),
    std::make_pair("G1add", &G1<default_ec_pp>::add_cnt),
    std::make_pair("G1dbl", &G1<default_ec_pp>::dbl_cnt),
    std::make_pair("G2add", &G2<default_ec_pp>::add_cnt),
    std::make_pair("G2dbl", &G2<default_ec_pp>::dbl_cnt)
#endif
};

bool inhibit_profiling_info = true;
bool inhibit_profiling_counters = false;

void clear_profiling_counters()
{
    invocation_counts.clear();
    last_times.clear();
    last_cpu_times.clear();
    cumulative_times.clear();
}

void print_cumulative_time_entry(const std::string &key, const int64_t factor)
{
    const double total_ms = (cumulative_times.at(key) * 1e-6);
    const size_t cnt = invocation_counts.at(key);
    const double avg_ms = total_ms / cnt;
    printf("   %-45s: %12.5fms = %" PRId64 " * %0.5fms (%zu invocations, %0.5fms = %" PRId64 " * %0.5fms per invocation)\n", key.c_str(), total_ms, factor, total_ms/factor, cnt, avg_ms, factor, avg_ms/factor);
}

void print_cumulative_times(const int64_t factor)
{
    printf("Dumping times:\n");
    for (auto& kv : cumulative_times)
    {
        print_cumulative_time_entry(kv.first, factor);
    }
}

void print_cumulative_op_counts(const bool only_fq)
{
#ifdef PROFILE_OP_COUNTS
    printf("Dumping operation counts:\n");
    for (auto& msg : invocation_counts)
    {
        printf("  %-45s: ", msg.first.c_str());
        bool first = true;
        for (auto& data_point : op_data_points)
        {
            if (only_fq && data_point.first.compare(0, 2, "Fq") != 0)
            {
                continue;
            }

            if (!first)
            {
                printf(", ");
            }
            printf("%-5s = %7.0f (%3zu)",
                   data_point.first.c_str(),
                   1. * cumulative_op_counts[std::make_pair(msg.first, data_point.first)] / msg.second,
                   msg.second);
            first = false;
        }
        printf("\n");
    }
#else
    UNUSED(only_fq);
#endif
}

void print_op_profiling(const std::string &msg)
{
#ifdef PROFILE_OP_COUNTS
    printf("\n");
    print_indent();

    printf("(opcounts) = (");
    bool first = true;
    for (std::pair<std::string, int64_t*> p : op_data_points)
    {
        if (!first)
        {
            printf(", ");
        }

        printf("%s=%lld", p.first.c_str(), *(p.second)-op_counts[std::make_pair(msg, p.first)]);
        first = false;
    }
    printf(")");
#else
    UNUSED(msg);
#endif
}

static void print_times_from_last_and_start(int64_t     now, int64_t     last,
                                            int64_t cpu_now, int64_t cpu_last)
{
    int64_t time_from_start = now - start_time;
    int64_t time_from_last = now - last;

    int64_t cpu_time_from_start = cpu_now - start_cpu_time;
    int64_t cpu_time_from_last = cpu_now - cpu_last;

    if (time_from_last != 0) {
        double parallelism_from_last = 1.0 * cpu_time_from_last / time_from_last;
        printf("[%0.4fs x%0.2f]", time_from_last * 1e-9, parallelism_from_last);
    } else {
        printf("[             ]");
    }
    if (time_from_start != 0) {
        double parallelism_from_start = 1.0 * cpu_time_from_start / time_from_start;
        printf("\t(%0.4fs x%0.2f from start)", time_from_start * 1e-9, parallelism_from_start);
    }
}

void print_time(const char* msg)
{
    if (inhibit_profiling_info)
    {
        return;
    }

    int64_t now = get_nsec_time();
    int64_t cpu_now = get_nsec_cpu_time();

    printf("%-35s\t", msg);
    print_times_from_last_and_start(now, last_time, cpu_now, last_cpu_time);
#ifdef PROFILE_OP_COUNTS
    print_op_profiling(msg);
#endif
    printf("\n");

    fflush(stdout);
    last_time = now;
    last_cpu_time = cpu_now;
}

void print_header(const char *msg)
{
    printf("\n================================================================================\n");
    printf("%s\n", msg);
    printf("================================================================================\n\n");
}

void print_indent()
{
    for (size_t i = 0; i < indentation; ++i)
    {
        printf("  ");
    }
}

void op_profiling_enter(const std::string &msg)
{
    for (std::pair<std::string, int64_t*> p : op_data_points)
    {
        op_counts[std::make_pair(msg, p.first)] = *(p.second);
    }
}

void enter_block(const std::string &msg, const bool indent)
{
    if (inhibit_profiling_counters)
    {
        return;
    }

    block_names.emplace_back(msg);
    int64_t t = get_nsec_time();
    enter_times[msg] = t;
    int64_t cpu_t = get_nsec_cpu_time();
    enter_cpu_times[msg] = cpu_t;

    if (inhibit_profiling_info)
    {
        return;
    }

#ifdef MULTICORE
#pragma omp critical
#endif
    {
        op_profiling_enter(msg);

        print_indent();
        printf("(enter) %-35s\t", msg.c_str());
        print_times_from_last_and_start(t, t, cpu_t, cpu_t);
        printf("\n");
        fflush(stdout);

        if (indent)
        {
            ++indentation;
        }
    }
}

void leave_block(const std::string &msg, const bool indent)
{
    if (inhibit_profiling_counters)
    {
        return;
    }

#ifndef MULTICORE
    assert(*(--block_names.end()) == msg);
#endif
    block_names.pop_back();

    ++invocation_counts[msg];

    int64_t t = get_nsec_time();
    last_times[msg] = (t - enter_times[msg]);
    cumulative_times[msg] += (t - enter_times[msg]);

    int64_t cpu_t = get_nsec_cpu_time();
    last_cpu_times[msg] = (cpu_t - enter_cpu_times[msg]);

#ifdef PROFILE_OP_COUNTS
    for (std::pair<std::string, int64_t*> p : op_data_points)
    {
        cumulative_op_counts[std::make_pair(msg, p.first)] += *(p.second)-op_counts[std::make_pair(msg, p.first)];
    }
#endif

    if (inhibit_profiling_info)
    {
        return;
    }

#ifdef MULTICORE
#pragma omp critical
#endif
    {
        if (indent)
        {
            --indentation;
        }

        print_indent();
        printf("(leave) %-35s\t", msg.c_str());
        print_times_from_last_and_start(t, enter_times[msg], cpu_t, enter_cpu_times[msg]);
        print_op_profiling(msg);
        printf("\n");
        fflush(stdout);
    }
}

void print_mem(const std::string &s)
{
#ifndef NO_PROCPS
    struct proc_t usage;
    look_up_our_self(&usage);
    if (s.empty())
    {
        printf("* Peak vsize (physical memory+swap) in mebibytes: %lu\n", usage.vsize >> 20);
    }
    else
    {
        printf("* Peak vsize (physical memory+swap) in mebibytes (%s): %lu\n", s.c_str(), usage.vsize >> 20);
    }
#else
    printf("* Memory profiling not supported in NO_PROCPS mode\n");
#endif
}

void print_compilation_info()
{
#ifdef __GNUC__
    printf("g++ version: %s\n", __VERSION__);
    //printf("Compiled on %s %s\n", __DATE__, __TIME__);
#endif
#ifdef STATIC
    printf("STATIC: yes\n");
#else
    printf("STATIC: no\n");
#endif
#ifdef MULTICORE
    printf("MULTICORE: yes\n");
#else
    printf("MULTICORE: no\n");
#endif
#ifdef DEBUG
    printf("DEBUG: yes\n");
#else
    printf("DEBUG: no\n");
#endif
#ifdef PROFILE_OP_COUNTS
    printf("PROFILE_OP_COUNTS: yes\n");
#else
    printf("PROFILE_OP_COUNTS: no\n");
#endif
#ifdef _GLIBCXX_DEBUG
    printf("_GLIBCXX_DEBUG: yes\n");
#else
    printf("_GLIBCXX_DEBUG: no\n");
#endif
}

} // libsnark
<|endoftext|>