<commit_before>/*
 * main.cpp
 *
 * contains main function
 *
 */

#include "clutter.hpp"

int main(int argc, char* argv[])
{
	initPaths();
	init_screen("Particle-Viewer");
	cam.initGL();
	part = new Particle();
	setupGLStuff();
	setupScreenFBO();

	while (!glfwWindowShouldClose(window))
	{

		glfwPollEvents();
		cam.Move();
		//readInput(event);

		beforeDraw();
		drawFunct();
		cam.RenderSphere();
		drawFBO();
		//render GUI

		glfwSwapBuffers(window);

		if(set->frames > 1)			{ set->readPosVelFile(curFrame,part,false);}
		if(set->isPlaying)			{ curFrame++;}
		if(curFrame > set->frames)	{ curFrame = set->frames;}
		minor_keyCallback();
		if (curFrame < 0)			{ curFrame = 0;}
	}
	cleanup();
	return 0;
}

void beforeDraw()
{
	glEnable(GL_DEPTH_TEST);
	glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
	cam.update(deltaTime);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	upDeltaTime();
	view = cam.setupCam();

}

void drawFunct()
{
	set->getCOM(curFrame, com);
	cam.setSphereCenter(com);
	sphereShader.Use();
	part->pushVBO();
	glBindVertexArray(circleVAO);
	glBindBuffer(GL_ARRAY_BUFFER, part->instanceVBO);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glUniformMatrix4fv(glGetUniformLocation(sphereShader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));
	glUniformMatrix4fv(glGetUniformLocation(sphereShader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(cam.projection));
	glUniform1f(glGetUniformLocation(sphereShader.Program, "radius"), sphereRadius);
	glUniform1f(glGetUniformLocation(sphereShader.Program, "scale"), sphereScale);
	glDrawArraysInstanced(GL_POINTS,0,1,part->n);
	glBindVertexArray(0);
	//take screenshot
	if(set->isPlaying && isRecording)
	{
		glReadPixels(0,0,(int)SCREEN_WIDTH, (int)SCREEN_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, pixels);
		for (int i = 0; i < SCREEN_WIDTH * 3; i++)
		{
			for(int j = 0; j < SCREEN_HEIGHT; j++)
			{
				pixels2[i + SCREEN_WIDTH* 3 * j] = pixels[i+ SCREEN_WIDTH* 3 * (SCREEN_HEIGHT - j)];
			}
		}
		//
		if(!stbi_write_tga(std::string(recordFolder+"/" + std::to_string(curFrame) + ".tga").c_str(), (int)SCREEN_WIDTH, (int)SCREEN_HEIGHT, 3, pixels2))
		{
			if(imageError < imageErrorMax)
			{
				imageError++;
				std::cout << "Unable to save image: Error "<< imageError << std::endl;
			}
			else
			{
				std::cout << "Max Image Error Count Reached! Ending Recording!"<< std::endl;
				isRecording = false;
			}
		}
	}

}

/*
 * Sets up the basic OpenGL stuff.
 */
void setupGLStuff()
{
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_PROGRAM_POINT_SIZE );
	glEnable(GL_MULTISAMPLE);
	sphereShader = Shader(sphereVertexShader.c_str(),sphereFragmentShader.c_str());
	screenShader = Shader(screenVertexShader.c_str(),screenFragmentShader.c_str());
	/* Sets up sphere array in OpenGL */
	glGenVertexArrays(1, &circleVAO);
	glGenBuffers(1, &circleVBO);
	glBindVertexArray(circleVAO);
	glBindBuffer(GL_ARRAY_BUFFER, circleVBO);

	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);
	glEnableVertexAttribArray(0);
	part->setUpInstanceArray();
	glBindVertexArray(0);
	/* ============================== */
}

/*
 * Increment / decrement current frame by x amount.
 */
void seekFrame(int frame, bool isForward)
{
	if(isForward)	{ curFrame += frame;}
	else			{ curFrame -= frame;}

}

void cleanup()
{
	delete part;
	delete[] pixels;
	delete[] pixels2;
	glDeleteFramebuffers(1, &framebuffer);
}
<commit_msg>Last feature commit<commit_after>/*
 * main.cpp
 *
 * contains main function
 *
 */

#include "clutter.hpp"

int main(int argc, char* argv[])
{
	initPaths();
	init_screen("Particle-Viewer");
	cam.initGL();
	part = new Particle();
	setupGLStuff();
	setupScreenFBO();

	while (!glfwWindowShouldClose(window))
	{

		glfwPollEvents();
		cam.Move();
		//readInput(event);

		beforeDraw();
		drawFunct();
		cam.RenderSphere();
		drawFBO();
		//render GUI

		glfwSwapBuffers(window);

		if(set->frames > 1)			{ set->readPosVelFile(curFrame,part,false);}
		if(set->isPlaying)			{ curFrame++;}
		if(curFrame > set->frames)	{ curFrame = set->frames;}
		minor_keyCallback();
		if (curFrame < 0)			{ curFrame = 0;}
	}
	cleanup();
	return 0;
}

void beforeDraw()
{
	glEnable(GL_DEPTH_TEST);
	glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
	cam.update(deltaTime);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	upDeltaTime();
	view = cam.setupCam();

}

void drawFunct()
{
	set->getCOM(curFrame, com);
	cam.setSphereCenter(com);
	sphereShader.Use();
	part->pushVBO();
	glBindVertexArray(circleVAO);
	glBindBuffer(GL_ARRAY_BUFFER, part->instanceVBO);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glUniformMatrix4fv(glGetUniformLocation(sphereShader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));
	glUniformMatrix4fv(glGetUniformLocation(sphereShader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(cam.projection));
	glUniform1f(glGetUniformLocation(sphereShader.Program, "radius"), sphereRadius);
	glUniform1f(glGetUniformLocation(sphereShader.Program, "scale"), sphereScale);
	glDrawArraysInstanced(GL_POINTS,0,1,part->n);
	glBindVertexArray(0);
	//take screenshot
	//std::cout << "FPS: " << 1/deltaTime << std::endl; //get FPS
	if(set->isPlaying && isRecording)
	{
		glReadPixels(0,0,(int)SCREEN_WIDTH, (int)SCREEN_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, pixels);
		for (int i = 0; i < SCREEN_WIDTH * 3; i++)
		{
			for(int j = 0; j < SCREEN_HEIGHT; j++)
			{
				pixels2[i + SCREEN_WIDTH* 3 * j] = pixels[i+ SCREEN_WIDTH* 3 * (SCREEN_HEIGHT - j)];
			}
		}

		if(!stbi_write_tga(std::string(recordFolder+"/" + std::to_string(curFrame) + ".tga").c_str(), (int)SCREEN_WIDTH, (int)SCREEN_HEIGHT, 3, pixels2))
		{
			if(imageError < imageErrorMax)
			{
				imageError++;
				std::cout << "Unable to save image: Error "<< imageError << std::endl;
			}
			else
			{
				std::cout << "Max Image Error Count Reached! Ending Recording!"<< std::endl;
				isRecording = false;
			}
		}
	}

}

/*
 * Sets up the basic OpenGL stuff.
 */
void setupGLStuff()
{
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_PROGRAM_POINT_SIZE );
	glEnable(GL_MULTISAMPLE);
	sphereShader = Shader(sphereVertexShader.c_str(),sphereFragmentShader.c_str());
	screenShader = Shader(screenVertexShader.c_str(),screenFragmentShader.c_str());
	/* Sets up sphere array in OpenGL */
	glGenVertexArrays(1, &circleVAO);
	glGenBuffers(1, &circleVBO);
	glBindVertexArray(circleVAO);
	glBindBuffer(GL_ARRAY_BUFFER, circleVBO);

	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);
	glEnableVertexAttribArray(0);
	part->setUpInstanceArray();
	glBindVertexArray(0);
	/* ============================== */
}

/*
 * Increment / decrement current frame by x amount.
 */
void seekFrame(int frame, bool isForward)
{
	if(isForward)	{ curFrame += frame;}
	else			{ curFrame -= frame;}

}

void cleanup()
{
	delete part;
	delete[] pixels;
	delete[] pixels2;
	glDeleteFramebuffers(1, &framebuffer);
}
<|endoftext|>


<commit_before>#include <string>
#include <sstream>
#include <vector>
#include <vector>
#include <map>

#include "util/SequencedMap.h"
#include "util/Sysout.h"
#include "util/Sysin.h"

#include "Grammar.h"

SequencedMap<std::string, std::string> cmdByAlias;

bool alistatify(std::vector<std::string>* inputWords)
{
    // If we have no words
    if(inputWords->size() == 0)
    {
        // Then obviously it cannot match anything

        // Return unsuccessful
        return false;
    }

    // Loop through all commands
    for(unsigned int cait = 0; cait < cmdByAlias.size(); ++ cait)
    {
        // Info
        Sysout::print(" Testing for ");
        Sysout::println(cmdByAlias.first(cait));

        // Split the command's alias into a vector of individual words
        std::vector<std::string> cmdsWords;
        Sysin::splitWords(cmdByAlias.first(cait), &cmdsWords);

        // Check if we have enough input for it to be possible
        if(inputWords->size() < cmdsWords.size())
        {
            // [It cannot be this command]

            // Skip this one
            continue;
        }

        // Keeps track if the command comparison proves the input to start with the needed command
        bool commandMatches = true;

        // Get iterator for command words
        std::vector<std::string>::iterator commandWordFocus = cmdsWords.begin();

        // Iterate through the input words parallel
        std::vector<std::string>::iterator inputWordFocus = inputWords->begin();

        // Iterate through the command words
        while(commandWordFocus != cmdsWords.end())
        {
            // Check if this word is different
            if(*commandWordFocus != *inputWordFocus)
            {
                // [It is not]

                // The command therefore does not match
                commandMatches = false;

                // Stop checking, because it cannot possibly be it anymore
                break;
            }

            // Next
            ++ commandWordFocus;
            ++ inputWordFocus;
        }

        // If the command matches
        if(commandMatches)
        {
            // Loop through that command's sentence structures
            // To see if they fit.

            // Return successful
            return true;
        }
    }

    // [None of the commands matched]

    // Return unsuccessful
    return false;
}

int main()
{
    // Register commands
    cmdByAlias.append("eat", "MUNCH!");
    cmdByAlias.append("two words", "DOUBLE TROUBLE!");
    cmdByAlias.append("take a dump", "PLOP!");
    cmdByAlias.append("take", "KLEPTOMANIA!");

    // Legend
    Sysout::println("Fuzzy Computing Machine");

    // Running
    bool running = true;

    // Last input vector
    std::vector<std::string> lastInput;

    // While running, run!
    while(running)
    {
        Sysout::println("Enter something:");

        Sysout::print("FCM:\\>");
        Sysin::getWords(&lastInput);
        Sysout::println();

        Sysout::print("You entered:");
        Sysout::println(&lastInput);

        Sysout::println("Trying to recognize command...");

        alistatify(&lastInput);

        Sysout::println();
    }

    // Died quietly
    return 0;
}
<commit_msg>Comment brackets<commit_after>#include <string>
#include <sstream>
#include <vector>
#include <vector>
#include <map>

#include "util/SequencedMap.h"
#include "util/Sysout.h"
#include "util/Sysin.h"

#include "Grammar.h"

SequencedMap<std::string, std::string> cmdByAlias;

bool alistatify(std::vector<std::string>* inputWords)
{
    // If we have no words
    if(inputWords->size() == 0)
    {
        // [Then obviously it cannot match anything]

        // Return unsuccessful
        return false;
    }

    // Loop through all commands
    for(unsigned int cait = 0; cait < cmdByAlias.size(); ++ cait)
    {
        // Info
        Sysout::print(" Testing for ");
        Sysout::println(cmdByAlias.first(cait));

        // Split the command's alias into a vector of individual words
        std::vector<std::string> cmdsWords;
        Sysin::splitWords(cmdByAlias.first(cait), &cmdsWords);

        // Check if we have enough input for it to be possible
        if(inputWords->size() < cmdsWords.size())
        {
            // [It cannot be this command]

            // Skip this one
            continue;
        }

        // Keeps track if the command comparison proves the input to start with the needed command
        bool commandMatches = true;

        // Get iterator for command words
        std::vector<std::string>::iterator commandWordFocus = cmdsWords.begin();

        // Iterate through the input words parallel
        std::vector<std::string>::iterator inputWordFocus = inputWords->begin();

        // Iterate through the command words
        while(commandWordFocus != cmdsWords.end())
        {
            // Check if this word is different
            if(*commandWordFocus != *inputWordFocus)
            {
                // [It is not]

                // The command therefore does not match
                commandMatches = false;

                // Stop checking, because it cannot possibly be it anymore
                break;
            }

            // Next
            ++ commandWordFocus;
            ++ inputWordFocus;
        }

        // If the command matches
        if(commandMatches)
        {
            // Loop through that command's sentence structures
            // To see if they fit.

            // Return successful
            return true;
        }
    }

    // [None of the commands matched]

    // Return unsuccessful
    return false;
}

int main()
{
    // Register commands
    cmdByAlias.append("eat", "MUNCH!");
    cmdByAlias.append("two words", "DOUBLE TROUBLE!");
    cmdByAlias.append("take a dump", "PLOP!");
    cmdByAlias.append("take", "KLEPTOMANIA!");

    // Legend
    Sysout::println("Fuzzy Computing Machine");

    // Running
    bool running = true;

    // Last input vector
    std::vector<std::string> lastInput;

    // While running, run!
    while(running)
    {
        Sysout::println("Enter something:");

        Sysout::print("FCM:\\>");
        Sysin::getWords(&lastInput);
        Sysout::println();

        Sysout::print("You entered:");
        Sysout::println(&lastInput);

        Sysout::println("Trying to recognize command...");

        alistatify(&lastInput);

        Sysout::println();
    }

    // Died quietly
    return 0;
}
<|endoftext|>


<commit_before>// Copyright (C) 2015 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "GamepadWin.h"
#include "Engine.h"
#include "Utils.h"

namespace ouzel
{
    GamepadWin::GamepadWin(int32_t playerIndex):
        _playerIndex(playerIndex)
    {
        memset(&_state, 0, sizeof(XINPUT_STATE));
    }

    void GamepadWin::update(XINPUT_STATE const& state)
    {
        if (state.dwPacketNumber > _state.dwPacketNumber)
        {
            checkButton(state, XINPUT_GAMEPAD_DPAD_UP, GamepadButton::DPAD_UP);
            checkButton(state, XINPUT_GAMEPAD_DPAD_DOWN, GamepadButton::DPAD_DOWN);
            checkButton(state, XINPUT_GAMEPAD_DPAD_LEFT, GamepadButton::DPAD_LEFT);
            checkButton(state, XINPUT_GAMEPAD_DPAD_RIGHT, GamepadButton::DPAD_RIGHT);
            checkButton(state, XINPUT_GAMEPAD_START, GamepadButton::START);
            checkButton(state, XINPUT_GAMEPAD_BACK, GamepadButton::BACK);
            checkButton(state, XINPUT_GAMEPAD_LEFT_THUMB, GamepadButton::LEFT_THUMB);
            checkButton(state, XINPUT_GAMEPAD_RIGHT_THUMB, GamepadButton::RIGHT_THUMB);
            checkButton(state, XINPUT_GAMEPAD_LEFT_SHOULDER, GamepadButton::LEFT_SHOULDER);
            checkButton(state, XINPUT_GAMEPAD_RIGHT_SHOULDER, GamepadButton::RIGHT_SHOULDER);
            checkButton(state, XINPUT_GAMEPAD_A, GamepadButton::A);
            checkButton(state, XINPUT_GAMEPAD_B, GamepadButton::B);
            checkButton(state, XINPUT_GAMEPAD_X, GamepadButton::X);
            checkButton(state, XINPUT_GAMEPAD_Y, GamepadButton::Y);

            if (state.Gamepad.bLeftTrigger != _state.Gamepad.bLeftTrigger)
            {
                handleButtonValueChange(GamepadButton::LEFT_TRIGGER, state.Gamepad.bLeftTrigger != 0, static_cast<float>(state.Gamepad.bLeftTrigger) / 255.0f);
            }

            if (state.Gamepad.bLeftTrigger != _state.Gamepad.bLeftTrigger)
            {
                handleButtonValueChange(GamepadButton::RIGHT_TRIGGER, state.Gamepad.bRightTrigger != 0, static_cast<float>(state.Gamepad.bRightTrigger) / 255.0f);
            }

            _state = state;
        }
    }

    int32_t GamepadWin::getPlayerIndex() const
    {
        return _playerIndex;
    }

    void GamepadWin::checkButton(XINPUT_STATE const& state, WORD mask, GamepadButton button)
    {
        if ((state.Gamepad.wButtons & mask) != (_state.Gamepad.wButtons & mask))
        {
            bool pressed = (state.Gamepad.wButtons & mask);
            handleButtonValueChange(button, pressed, pressed ? 1.0f : 0.0f);
        }
    }

    void GamepadWin::handleButtonValueChange(GamepadButton button, bool pressed, float value)
    {
        GamepadEvent event;
        event.type = Event::Type::GAMEPAD_BUTTON_CHANGE;
        event.gamepad = shared_from_this();
        event.button = button;
        event.pressed = pressed;
        event.value = value;

        Engine::getInstance()->getEventDispatcher()->dispatchGamepadButtonChangeEvent(event, Engine::getInstance()->getInput());
    }
}
<commit_msg>Implement XInput thumbstick events<commit_after>// Copyright (C) 2015 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "GamepadWin.h"
#include "Engine.h"
#include "Utils.h"

namespace ouzel
{
    const int32_t MAX_THUMB_VALUE = 32767;
    const int32_t MIN_THUMB_VALUE = -32768;

    GamepadWin::GamepadWin(int32_t playerIndex):
        _playerIndex(playerIndex)
    {
        memset(&_state, 0, sizeof(XINPUT_STATE));
    }

    void GamepadWin::update(XINPUT_STATE const& state)
    {
        if (state.dwPacketNumber > _state.dwPacketNumber)
        {
            checkButton(state, XINPUT_GAMEPAD_DPAD_UP, GamepadButton::DPAD_UP);
            checkButton(state, XINPUT_GAMEPAD_DPAD_DOWN, GamepadButton::DPAD_DOWN);
            checkButton(state, XINPUT_GAMEPAD_DPAD_LEFT, GamepadButton::DPAD_LEFT);
            checkButton(state, XINPUT_GAMEPAD_DPAD_RIGHT, GamepadButton::DPAD_RIGHT);
            checkButton(state, XINPUT_GAMEPAD_START, GamepadButton::START);
            checkButton(state, XINPUT_GAMEPAD_BACK, GamepadButton::BACK);
            checkButton(state, XINPUT_GAMEPAD_LEFT_THUMB, GamepadButton::LEFT_THUMB);
            checkButton(state, XINPUT_GAMEPAD_RIGHT_THUMB, GamepadButton::RIGHT_THUMB);
            checkButton(state, XINPUT_GAMEPAD_LEFT_SHOULDER, GamepadButton::LEFT_SHOULDER);
            checkButton(state, XINPUT_GAMEPAD_RIGHT_SHOULDER, GamepadButton::RIGHT_SHOULDER);
            checkButton(state, XINPUT_GAMEPAD_A, GamepadButton::A);
            checkButton(state, XINPUT_GAMEPAD_B, GamepadButton::B);
            checkButton(state, XINPUT_GAMEPAD_X, GamepadButton::X);
            checkButton(state, XINPUT_GAMEPAD_Y, GamepadButton::Y);

            if (state.Gamepad.bLeftTrigger != _state.Gamepad.bLeftTrigger)
            {
                handleButtonValueChange(GamepadButton::LEFT_TRIGGER,
                                        state.Gamepad.bLeftTrigger > XINPUT_GAMEPAD_TRIGGER_THRESHOLD,
                                        static_cast<float>(state.Gamepad.bLeftTrigger) / 255.0f);
            }

            if (state.Gamepad.bLeftTrigger != _state.Gamepad.bLeftTrigger)
            {
                handleButtonValueChange(GamepadButton::RIGHT_TRIGGER,
                                        state.Gamepad.bRightTrigger > XINPUT_GAMEPAD_TRIGGER_THRESHOLD,
                                        static_cast<float>(state.Gamepad.bRightTrigger) / 255.0f);
            }

            if (state.Gamepad.sThumbLX != _state.Gamepad.sThumbLX)
            {
                if (state.Gamepad.sThumbLX > 0)
                {
                    handleButtonValueChange(GamepadButton::LEFT_THUMB_RIGHT,
                                            state.Gamepad.sThumbLX > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE,
                                            static_cast<float>(state.Gamepad.sThumbLX) / static_cast<float>(MAX_THUMB_VALUE));
                }
                else if (state.Gamepad.sThumbLX < 0)
                {
                    handleButtonValueChange(GamepadButton::LEFT_THUMB_LEFT,
                                            state.Gamepad.sThumbLX < -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE,
                                            static_cast<float>(state.Gamepad.sThumbLX) / static_cast<float>(MIN_THUMB_VALUE));
                }
                else // thumbstick is 0
                {
                    if (_state.Gamepad.sThumbLX > state.Gamepad.sThumbLX)
                    {
                        handleButtonValueChange(GamepadButton::LEFT_THUMB_RIGHT, false, 0.0f);
                    }
                    else
                    {
                        handleButtonValueChange(GamepadButton::LEFT_THUMB_LEFT, false, 0.0f);
                    }
                }
            }

            if (state.Gamepad.sThumbLY != _state.Gamepad.sThumbLY)
            {
                if (state.Gamepad.sThumbLY > 0)
                {
                    handleButtonValueChange(GamepadButton::LEFT_THUMB_UP,
                                            state.Gamepad.sThumbLY > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE,
                                            static_cast<float>(state.Gamepad.sThumbLY) / static_cast<float>(MAX_THUMB_VALUE));
                }
                else if (state.Gamepad.sThumbLY < 0)
                {
                    handleButtonValueChange(GamepadButton::LEFT_THUMB_DOWN,
                                            state.Gamepad.sThumbLY < -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE,
                                            static_cast<float>(state.Gamepad.sThumbLY) / static_cast<float>(MIN_THUMB_VALUE));
                }
                else // thumbstick is 0
                {
                    if (_state.Gamepad.sThumbLY > state.Gamepad.sThumbLY)
                    {
                        handleButtonValueChange(GamepadButton::LEFT_THUMB_UP, false, 0.0f);
                    }
                    else
                    {
                        handleButtonValueChange(GamepadButton::LEFT_THUMB_DOWN, false, 0.0f);
                    }
                }
            }

            if (state.Gamepad.sThumbRX != _state.Gamepad.sThumbRX)
            {
                if (state.Gamepad.sThumbRX > 0)
                {
                    handleButtonValueChange(GamepadButton::RIGHT_THUMB_RIGHT,
                                            state.Gamepad.sThumbRX > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE,
                                            static_cast<float>(state.Gamepad.sThumbRX) / static_cast<float>(MAX_THUMB_VALUE));
                }
                else if (state.Gamepad.sThumbRX < 0)
                {
                    handleButtonValueChange(GamepadButton::RIGHT_THUMB_LEFT,
                                            state.Gamepad.sThumbRX < -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE,
                                            static_cast<float>(state.Gamepad.sThumbRX) / static_cast<float>(MIN_THUMB_VALUE));
                }
                else // thumbstick is 0
                {
                    if (_state.Gamepad.sThumbRX > state.Gamepad.sThumbRX)
                    {
                        handleButtonValueChange(GamepadButton::RIGHT_THUMB_RIGHT, false, 0.0f);
                    }
                    else
                    {
                        handleButtonValueChange(GamepadButton::RIGHT_THUMB_LEFT, false, 0.0f);
                    }
                }
            }

            if (state.Gamepad.sThumbRY != _state.Gamepad.sThumbRY)
            {
                if (state.Gamepad.sThumbRY > 0)
                {
                    handleButtonValueChange(GamepadButton::RIGHT_THUMB_UP,
                                            state.Gamepad.sThumbRY > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE,
                                            static_cast<float>(state.Gamepad.sThumbRY) / static_cast<float>(MAX_THUMB_VALUE));
                }
                else if (state.Gamepad.sThumbRY < 0)
                {
                    handleButtonValueChange(GamepadButton::RIGHT_THUMB_DOWN,
                                            state.Gamepad.sThumbRY < -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE,
                                            static_cast<float>(state.Gamepad.sThumbRY) / static_cast<float>(MIN_THUMB_VALUE));
                }
                else // thumbstick is 0
                {
                    if (_state.Gamepad.sThumbRY > state.Gamepad.sThumbRY)
                    {
                        handleButtonValueChange(GamepadButton::RIGHT_THUMB_UP, false, 0.0f);
                    }
                    else
                    {
                        handleButtonValueChange(GamepadButton::RIGHT_THUMB_DOWN, false, 0.0f);
                    }
                }
            }

            _state = state;
        }
    }

    int32_t GamepadWin::getPlayerIndex() const
    {
        return _playerIndex;
    }

    void GamepadWin::checkButton(XINPUT_STATE const& state, WORD mask, GamepadButton button)
    {
        if ((state.Gamepad.wButtons & mask) != (_state.Gamepad.wButtons & mask))
        {
            bool pressed = (state.Gamepad.wButtons & mask);
            handleButtonValueChange(button, pressed, pressed ? 1.0f : 0.0f);
        }
    }

    void GamepadWin::handleButtonValueChange(GamepadButton button, bool pressed, float value)
    {
        GamepadEvent event;
        event.type = Event::Type::GAMEPAD_BUTTON_CHANGE;
        event.gamepad = shared_from_this();
        event.button = button;
        event.pressed = pressed;
        event.value = value;

        Engine::getInstance()->getEventDispatcher()->dispatchGamepadButtonChangeEvent(event, Engine::getInstance()->getInput());
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2003 Thomer M. Gil (thomer@csail.mit.edu)
 *                    Massachusetts Institute of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "topologies/topologyfactory.h"
#include "failuremodels/failuremodelfactory.h"
#include "network.h"
#include "parse.h"
#include <iostream>
using namespace std;

Topology::Topology()
{
  _med_lat = 0;
  _lossrate = 0;
}

Topology::~Topology()
{
}

Topology*
Topology::parse(char *filename)
{
  extern bool with_failure_model;

  ifstream in(filename);
  if(!in) {
    cerr << "no such file " << filename << endl;
    threadexitsall(0);
  }

  string line;
  Topology *top = 0;
  FailureModel *failure_model = 0;
  while(getline(in,line)) {
    vector<string> words = split(line);

    // break on first empty line
    if(words.empty())
      break;

    // skip empty lines and commented lines
    if(words[0][0] == '#')
      continue;

    // topology
    if(words[0] == "topology") {
      words.erase(words.begin());
      string topology = words[0];
      words.erase(words.begin());
      top = TopologyFactory::create(topology, &words);

    // noise
    } else if(words[0] == "noise") {
      if(!top) {
        cerr << "topology keyword must appear before noise keyword" << filename << endl;
	continue;
      }
      top->_noise = (unsigned) (atof(words[1].c_str()) * 100);
      cout << "noise = " << top->noise_variance() << endl;
      assert(top->noise_variance() >= 0);

    // loss_rate
    } else if(words[0] == "loss_rate") {
      if(!top) {
        cerr << "topology keyword must appear before loss_rate keyword" << filename << endl;
	continue;
      }
      top->_lossrate = (unsigned) (atof(words[1].c_str()) * 100);
      assert(top->lossrate() >= 0 && top->lossrate() <= 10000);

    // failure_model
    } else if(words[0] == "failure_model") {
      if(!with_failure_model) {
        cerr << "warning: -f flag but found failure_model keyword. ignoring failure_model!" << filename << endl;
	continue;
      }
      words.erase(words.begin());
      string fm = words[0];
      words.erase(words.begin());
      failure_model = FailureModelFactory::create(fm, &words);
    } else {
      cerr << "header lines in topology file should be ``topology [T]'' or ``failure_model [F]" << endl;
      exit(-1);
    }
  }

  if(!top) {
    cerr << "the topology you specified is unknown" << endl;
    exit(-1);
  }

  if(!failure_model) {
    if (!with_failure_model) {
      vector<string> words;
      failure_model = FailureModelFactory::create("NullFailureModel", &words);
      assert (failure_model);
    } else {
      cerr << "the failure_model you specified is unknown" << endl;
      exit(-1);
    }
  }

  // create the network.
  Network::Instance(top, failure_model);

  // leave the rest of the file to the specific topology
  top->parse(in);

  return top;
}
<commit_msg>default value for noise is zero<commit_after>/*
 * Copyright (c) 2003 Thomer M. Gil (thomer@csail.mit.edu)
 *                    Massachusetts Institute of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "topologies/topologyfactory.h"
#include "failuremodels/failuremodelfactory.h"
#include "network.h"
#include "parse.h"
#include <iostream>
using namespace std;

Topology::Topology()
{
  _med_lat = 0;
  _lossrate = 0;
  _noise = 0;
}

Topology::~Topology()
{
}

Topology*
Topology::parse(char *filename)
{
  extern bool with_failure_model;

  ifstream in(filename);
  if(!in) {
    cerr << "no such file " << filename << endl;
    threadexitsall(0);
  }

  string line;
  Topology *top = 0;
  FailureModel *failure_model = 0;
  while(getline(in,line)) {
    vector<string> words = split(line);

    // break on first empty line
    if(words.empty())
      break;

    // skip empty lines and commented lines
    if(words[0][0] == '#')
      continue;

    // topology
    if(words[0] == "topology") {
      words.erase(words.begin());
      string topology = words[0];
      words.erase(words.begin());
      top = TopologyFactory::create(topology, &words);

    // noise
    } else if(words[0] == "noise") {
      if(!top) {
        cerr << "topology keyword must appear before noise keyword" << filename << endl;
	continue;
      }
      top->_noise = (unsigned) (atof(words[1].c_str()) * 100);
      cout << "noise = " << top->noise_variance() << endl;
      assert(top->noise_variance() >= 0);

    // loss_rate
    } else if(words[0] == "loss_rate") {
      if(!top) {
        cerr << "topology keyword must appear before loss_rate keyword" << filename << endl;
	continue;
      }
      top->_lossrate = (unsigned) (atof(words[1].c_str()) * 100);
      assert(top->lossrate() >= 0 && top->lossrate() <= 10000);

    // failure_model
    } else if(words[0] == "failure_model") {
      if(!with_failure_model) {
        cerr << "warning: -f flag but found failure_model keyword. ignoring failure_model!" << filename << endl;
	continue;
      }
      words.erase(words.begin());
      string fm = words[0];
      words.erase(words.begin());
      failure_model = FailureModelFactory::create(fm, &words);
    } else {
      cerr << "header lines in topology file should be ``topology [T]'' or ``failure_model [F]" << endl;
      exit(-1);
    }
  }

  if(!top) {
    cerr << "the topology you specified is unknown" << endl;
    exit(-1);
  }

  if(!failure_model) {
    if (!with_failure_model) {
      vector<string> words;
      failure_model = FailureModelFactory::create("NullFailureModel", &words);
      assert (failure_model);
    } else {
      cerr << "the failure_model you specified is unknown" << endl;
      exit(-1);
    }
  }

  // create the network.
  Network::Instance(top, failure_model);

  // leave the rest of the file to the specific topology
  top->parse(in);

  return top;
}
<|endoftext|>


<commit_before>
#include "backend/bridge/dml/expr/pg_func_map.h"

namespace peloton {
namespace bridge {

/**
 * @brief Mapping PG Function Id to Peloton Function Meta Info.
 */
std::unordered_map<Oid, const PltFuncMetaInfo> kPgFuncMap({

    //====--------------------------------
    // Relational comparison
    //====--------------------------------
    {63, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},
    {65, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},
    {67, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},
    {158, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},
    {159, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},
    {287, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},
    {293, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},
    {1718, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},

    {84, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {144, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {145, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {157, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {164, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {165, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {288, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {294, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {1719, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},

    {56, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {64, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {66, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {160, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {161, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {1246, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {289, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {295, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {1722, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},

    {57, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {73, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {146, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {147, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {162, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {163, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {291, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {297, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {1720, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},

    {74, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {150, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {151, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {168, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {169, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {1692, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {292, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {298, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {1721, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},

    {72, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {148, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {149, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {166, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {167, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {1691, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {290, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {296, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {1723, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},

    //====--------------------------------
    // Basic arithmetics
    //====--------------------------------
    {176, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},
    {177, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},
    {178, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},
    {179, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},
    {204, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},
    {218, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},
    {1724, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},

    {180, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},
    {181, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},
    {182, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},
    {183, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},
    {205, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},
    {219, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},
    {1725, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},

    {141, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},
    {152, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},
    {170, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},
    {171, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},
    {202, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},
    {216, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},
    {1726, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},

    {153, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},
    {154, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},
    {172, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},
    {173, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},
    {203, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},
    {217, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},
    {1727, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},

    //====--------------------------------
    // Cast
    //====--------------------------------
    {480, {EXPRESSION_TYPE_CAST, 1}},   // int8 -> int4
    {481, {EXPRESSION_TYPE_CAST, 1}},   // int4 -> int8
    {668, {EXPRESSION_TYPE_CAST, 3}},   // bpchar -> bpchar
    {669, {EXPRESSION_TYPE_CAST, 3}},   // varchar -> varchar
    {1703, {EXPRESSION_TYPE_CAST, 2}},  // numeric -> numeric
    {1740, {EXPRESSION_TYPE_CAST, 3}},  // int8 -> numeric
    {1742, {EXPRESSION_TYPE_CAST, 3}},  // float4 -> numeric
    {1743, {EXPRESSION_TYPE_CAST, 3}},  // float8 -> numeric
    {1744, {EXPRESSION_TYPE_CAST, 1}},  // numeric -> int4
    {1745, {EXPRESSION_TYPE_CAST, 1}},  // numeric -> float4
    {1746, {EXPRESSION_TYPE_CAST, 1}},  // numeric -> float8
    {1781, {EXPRESSION_TYPE_CAST, 1}},  // int8 -> numeric
    {1782, {EXPRESSION_TYPE_CAST, 1}},  // int2 -> numeric

});

/**
 * @brief Mapping PG transit function to Aggregate types.
 * We have to separate it from kPgFuncMap,
 * because the two maps may have overlapping functions that have
 * different meaning in Peloton.
 * For example, PG Function Id 218 (float8pl) means an PLUS in
 * 'ordinary' expressions,
 * but means a SUM(float) in an aggregation.
 */
std::unordered_map<Oid, const PltFuncMetaInfo> kPgTransitFuncMap(
    {//====--------------------------------
     // "Transit function" of Aggregates
     //====--------------------------------
     {768, {EXPRESSION_TYPE_AGGREGATE_MAX, 1}},
     {770, {EXPRESSION_TYPE_AGGREGATE_MAX, 1}},
     {223, {EXPRESSION_TYPE_AGGREGATE_MAX, 1}},

     {769, {EXPRESSION_TYPE_AGGREGATE_MIN, 1}},
     {771, {EXPRESSION_TYPE_AGGREGATE_MIN, 1}},
     {224, {EXPRESSION_TYPE_AGGREGATE_MIN, 1}},

     {1840, {EXPRESSION_TYPE_AGGREGATE_SUM, 1}},
     {1841, {EXPRESSION_TYPE_AGGREGATE_SUM, 1}},
     {1842, {EXPRESSION_TYPE_AGGREGATE_SUM, 1}},
     {218, {EXPRESSION_TYPE_AGGREGATE_SUM, 1}},

     {222, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},
     {1834, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},
     {1835, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},
     {1836, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},
     {1833, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},
     {1962, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},
     {1963, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},

     {1219, {EXPRESSION_TYPE_AGGREGATE_COUNT, 1}},
     {2804, {EXPRESSION_TYPE_AGGREGATE_COUNT, 1}}

    });
}
}
<commit_msg>Add function mapping for timestamp operators and sum aggregate function<commit_after>
#include "backend/bridge/dml/expr/pg_func_map.h"

namespace peloton {
namespace bridge {

/**
 * @brief Mapping PG Function Id to Peloton Function Meta Info.
 */
std::unordered_map<Oid, const PltFuncMetaInfo> kPgFuncMap({

    //====--------------------------------
    // Relational comparison
    //====--------------------------------
    {63, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},
    {65, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},
    {67, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},
    {158, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},
    {159, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},
    {287, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},
    {293, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},
    {1718, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},
    {2052, {EXPRESSION_TYPE_COMPARE_EQUAL, 2}},

    {84, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {144, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {145, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {157, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {164, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {165, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {288, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {294, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {1719, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},
    {2053, {EXPRESSION_TYPE_COMPARE_NOTEQUAL, 2}},

    {56, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {64, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {66, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {160, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {161, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {1246, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {289, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {295, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {1722, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},
    {2054, {EXPRESSION_TYPE_COMPARE_LESSTHAN, 2}},

    {57, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {73, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {146, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {147, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {162, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {163, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {291, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {297, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {1720, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},
    {2057, {EXPRESSION_TYPE_COMPARE_GREATERTHAN, 2}},

    {74, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {150, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {151, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {168, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {169, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {1692, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {292, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {298, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {1721, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},
    {2056, {EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO, 2}},

    {72, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {148, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {149, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {166, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {167, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {1691, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {290, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {296, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {1723, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},
    {2055, {EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO, 2}},

    //====--------------------------------
    // Basic arithmetics
    //====--------------------------------
    {176, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},
    {177, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},
    {178, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},
    {179, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},
    {204, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},
    {218, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},
    {1724, {EXPRESSION_TYPE_OPERATOR_PLUS, 2}},

    {180, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},
    {181, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},
    {182, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},
    {183, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},
    {205, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},
    {219, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},
    {1725, {EXPRESSION_TYPE_OPERATOR_MINUS, 2}},

    {141, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},
    {152, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},
    {170, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},
    {171, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},
    {202, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},
    {216, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},
    {1726, {EXPRESSION_TYPE_OPERATOR_MULTIPLY, 2}},

    {153, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},
    {154, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},
    {172, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},
    {173, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},
    {203, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},
    {217, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},
    {1727, {EXPRESSION_TYPE_OPERATOR_DIVIDE, 2}},

    //====--------------------------------
    // Cast
    //====--------------------------------
    {480, {EXPRESSION_TYPE_CAST, 1}},   // int8 -> int4
    {481, {EXPRESSION_TYPE_CAST, 1}},   // int4 -> int8
    {668, {EXPRESSION_TYPE_CAST, 3}},   // bpchar -> bpchar
    {669, {EXPRESSION_TYPE_CAST, 3}},   // varchar -> varchar
    {1703, {EXPRESSION_TYPE_CAST, 2}},  // numeric -> numeric
    {1740, {EXPRESSION_TYPE_CAST, 3}},  // int8 -> numeric
    {1742, {EXPRESSION_TYPE_CAST, 3}},  // float4 -> numeric
    {1743, {EXPRESSION_TYPE_CAST, 3}},  // float8 -> numeric
    {1744, {EXPRESSION_TYPE_CAST, 1}},  // numeric -> int4
    {1745, {EXPRESSION_TYPE_CAST, 1}},  // numeric -> float4
    {1746, {EXPRESSION_TYPE_CAST, 1}},  // numeric -> float8
    {1781, {EXPRESSION_TYPE_CAST, 1}},  // int8 -> numeric
    {1782, {EXPRESSION_TYPE_CAST, 1}},  // int2 -> numeric

});

/**
 * @brief Mapping PG transit function to Aggregate types.
 * We have to separate it from kPgFuncMap,
 * because the two maps may have overlapping functions that have
 * different meaning in Peloton.
 * For example, PG Function Id 218 (float8pl) means an PLUS in
 * 'ordinary' expressions,
 * but means a SUM(float) in an aggregation.
 */
std::unordered_map<Oid, const PltFuncMetaInfo> kPgTransitFuncMap(
    {//====--------------------------------
     // "Transit function" of Aggregates
     //====--------------------------------
     {768, {EXPRESSION_TYPE_AGGREGATE_MAX, 1}},
     {770, {EXPRESSION_TYPE_AGGREGATE_MAX, 1}},
     {223, {EXPRESSION_TYPE_AGGREGATE_MAX, 1}},

     {769, {EXPRESSION_TYPE_AGGREGATE_MIN, 1}},
     {771, {EXPRESSION_TYPE_AGGREGATE_MIN, 1}},
     {224, {EXPRESSION_TYPE_AGGREGATE_MIN, 1}},

     {1840, {EXPRESSION_TYPE_AGGREGATE_SUM, 1}},
     {1841, {EXPRESSION_TYPE_AGGREGATE_SUM, 1}},
     {1842, {EXPRESSION_TYPE_AGGREGATE_SUM, 1}},
     {218, {EXPRESSION_TYPE_AGGREGATE_SUM, 1}},

     {222, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},
     {1834, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},
     {1835, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},
     {1836, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},
     {1833, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},
     {1962, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},
     {1963, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},
     {2858, {EXPRESSION_TYPE_AGGREGATE_AVG, 1}},

     {1219, {EXPRESSION_TYPE_AGGREGATE_COUNT, 1}},
     {2804, {EXPRESSION_TYPE_AGGREGATE_COUNT, 1}}

    });
}
}
<|endoftext|>


<commit_before>#include <cstdlib>
#include <string>
#include <iostream>
#include "utils.h"
#include "Lexer.h"
#include "Parser.h"
#include <exception>
#include "ParseException.h"
#include "opcodes.h"

static uint16_t generate_opcode(const std::string& op, const std::vector<std::string>& args)
{
    auto itr = OPERATORS.find(op);
    return itr->second(args);
}

static void write_rom(const std::string& filePath, const std::vector<Instruction>& instructions, const std::map<std::string, uint16_t>& labels)
{
    std::FILE *fp = std::fopen(filePath.c_str(), "wb");
    if (!fp) {
        throw std::runtime_error("Unable to open file for writing.");
    }

    /* Now perform the binary conversion and write it to the file */
    for (const auto& i : instructions) {
        uint16_t op = 0;
        /* Replace labels with their addresses */
        if (one_of<std::string>(i.op, { "JMP", "CALL", "ZJMP", "ILOAD" })) {
            auto label = i.args[0];
            auto arg = from_hex(labels.at(label));
            op = generate_opcode(i.op, { arg });
        } else {
            op = generate_opcode(i.op, i.args);
        }
        /* Correct for the host machine endianness to chip 8 big endian */
        op = endi(op);

        std::fwrite(&op, sizeof(op), 1, fp);
    }
    std::fclose(fp);

#ifndef NDEBUG
    LOG("-------- Label Addresses --------");
    for (const auto& it : labels) {
        LOG("%s -> 0x%04X", it.first.c_str(), it.second);
    }
    LOG("-------- End Addresses --------");
#endif
}

static void dump_asm(const std::vector<Instruction>& instructions, const std::map<std::string, uint16_t>& labels)
{
    std::cout << "-------- Asm Dump --------\n";
    for (const auto& i : instructions) {
        uint16_t op = 0;
        /* Replace labels with their addresses */
        if (one_of<std::string>(i.op, { "JMP", "CALL", "ZJMP", "ILOAD" })) {
            auto label = i.args[0];
            auto arg = from_hex(labels.at(label));
            op = generate_opcode(i.op, { arg });
        } else {
            op = generate_opcode(i.op, i.args);
        }
        std::cout << from_hex(i.addr) << " -- " << from_hex(op) << " ; ";
        std::string s = i.op + " ";
        for (const auto& a : i.args) {
            s += a;
            s += ", ";
        }
        /* Remove the last comma */
        s = s.substr(0, s.find_last_of(","));
        std::cout << s << "\n";
    }
    std::cout << "-------- End Dump --------\n";
}

static std::string read_file(const char *path)
{
    std::FILE *fp = std::fopen(path, "r");
    if (!fp) { return ""; }

    fseek(fp, 0, SEEK_END);
    auto fsize = std::ftell(fp);
    std::rewind(fp);

    std::string buf(fsize, '\0');
    std::fread(&buf[0], sizeof(char), fsize, fp);
    std::fclose(fp);

    return buf;
}

static bool parse_args(int argc, char **argv, AsmOpts *opts)
{
    if (argc < 2) {
        return false;
    }

    std::string first(argv[1]);
    if (first == "-h") {
        opts->show_help = true;
        return true;
    }
    opts->in_file = argv[1];

    for (int i = 2; i < argc; ++i) {
        std::string arg(argv[i]);
        if (arg == "--dump-asm") {
            opts->dump_asm = true;
        } else if (arg == "--output" || arg == "-o") {
            opts->out_file = argv[i + 1];
            if (opts->out_file == nullptr) {
                std::cerr << "Output flag specified without an output file!\n";
                return false;
            }
            ++i;
        } else {
            return false;
        }
    }
    return true;
}

static void show_help()
{
    std::cout << "chip8asm is an assembler for the chip 8 VM.\n";
    std::cout << "The only required argument is the input .asm file.\n";
    std::cout << "The first argument should be one of the input file or help.\n";
    std::cout << "Here are the supported options:\n";
    std::cout << "   --dump-asm | -dasm -- dumps the assembled statements with memory locations\n";
    std::cout << "   --output | -o -- the name of the output ROM file. By default, it is 'a.rom'\n";
    std::cout << "   --help | -h -- displays this help screen\n";
}

int main(int argc, char **argv)
{
    try {
        AsmOpts opts;
        if (!parse_args(argc, argv, &opts)) {
            show_help();
            return EXIT_FAILURE;
        }

        if (opts.show_help) {
            show_help();
            return EXIT_SUCCESS;
        }

        std::cout << "Reading from '" << opts.in_file << "' and writing to '" << opts.out_file << "'.\n";
        std::cout << "Dump ASM: " << (opts.dump_asm ? "true" : "false") << "\n";

        const std::string text = read_file(argv[1]);
        if (text.empty()) {
            std::cerr << "Error reading from " << argv[1] << "!\n";
            return EXIT_FAILURE;
        }

        emu::Lexer lexer(text);
        c8::Parser parser(lexer);
        parser.parse();

        auto instructions = parser.getInstructions();
        auto labels = parser.getLabels();
        write_rom(opts.out_file, instructions, labels);
        if (opts.dump_asm) {
            dump_asm(instructions, labels);
        }

        std::cout << "Binary ROM successfully generated!\n";

    } catch (const std::invalid_argument& e) {
        std::cerr << "Caught invalid argument: " << e.what() << "\n";
    } catch (const ParseException& e) {
        std::cerr << "Caught Parse Exception: " << e.what() << "\n";
    } catch (const std::exception& e) {
        std::cerr << "Caught generic exception: " << e.what() << "\n";
    } catch (...) {
        std::cerr << "Unknown error! Please retry!\n";
    }
}
<commit_msg>Moved to C I/O<commit_after>#include <cstdlib>
#include <string>
#include "utils.h"
#include "Lexer.h"
#include "Parser.h"
#include <exception>
#include "ParseException.h"
#include "opcodes.h"

static uint16_t generate_opcode(const std::string& op, const std::vector<std::string>& args)
{
    auto itr = OPERATORS.find(op);
    return itr->second(args);
}

static void write_rom(const std::string& filePath, const std::vector<Instruction>& instructions, const std::map<std::string, uint16_t>& labels)
{
    std::FILE *fp = std::fopen(filePath.c_str(), "wb");
    if (!fp) {
        throw std::runtime_error("Unable to open file for writing.");
    }

    /* Now perform the binary conversion and write it to the file */
    for (const auto& i : instructions) {
        uint16_t op = 0;
        /* Replace labels with their addresses */
        if (one_of<std::string>(i.op, { "JMP", "CALL", "ZJMP", "ILOAD" })) {
            auto label = i.args[0];
            auto arg = from_hex(labels.at(label));
            op = generate_opcode(i.op, { arg });
        } else {
            op = generate_opcode(i.op, i.args);
        }
        /* Correct for the host machine endianness to chip 8 big endian */
        op = endi(op);

        std::fwrite(&op, sizeof(op), 1, fp);
    }
    std::fclose(fp);

#ifndef NDEBUG
    LOG("-------- Label Addresses --------");
    for (const auto& it : labels) {
        LOG("%s -> 0x%04X", it.first.c_str(), it.second);
    }
    LOG("-------- End Addresses --------");
#endif
}

static void dump_asm(const std::vector<Instruction>& instructions, const std::map<std::string, uint16_t>& labels)
{
    std::puts("-------- ASM Dump --------");
    for (const auto& i : instructions) {
        uint16_t op = 0;
        /* Replace labels with their addresses */
        if (one_of<std::string>(i.op, { "JMP", "CALL", "ZJMP", "ILOAD" })) {
            auto label = i.args[0];
            auto arg = from_hex(labels.at(label));
            op = generate_opcode(i.op, { arg });
        } else {
            op = generate_opcode(i.op, i.args);
        }
        std::string s = i.op + " ";
        for (const auto& a : i.args) {
            s += a;
            s += ", ";
        }
        /* Remove the last comma */
        s = s.substr(0, s.find_last_of(","));
        std::printf("0x%04X | 0x%04X ; %s\n", i.addr, op, s.c_str());
    }
    std::puts("-------- End Dump --------");
}

static std::string read_file(const char *path)
{
    std::FILE *fp = std::fopen(path, "r");
    if (!fp) { return ""; }

    fseek(fp, 0, SEEK_END);
    auto fsize = std::ftell(fp);
    std::rewind(fp);

    std::string buf(fsize, '\0');
    std::fread(&buf[0], sizeof(char), fsize, fp);
    std::fclose(fp);

    return buf;
}

static bool parse_args(int argc, char **argv, AsmOpts *opts)
{
    if (argc < 2) {
        return false;
    }

    std::string first(argv[1]);
    if (first == "-h") {
        opts->show_help = true;
        return true;
    }
    opts->in_file = argv[1];

    for (int i = 2; i < argc; ++i) {
        std::string arg(argv[i]);
        if (arg == "--dump-asm") {
            opts->dump_asm = true;
        } else if (arg == "--output" || arg == "-o") {
            opts->out_file = argv[i + 1];
            if (opts->out_file == nullptr) {
                std::fprintf(stderr, "Output flag specified without an output file!\n");
                return false;
            }
            ++i;
        } else {
            return false;
        }
    }
    return true;
}

static void show_help()
{
    std::puts("chip8asm is an assembler for the chip 8 VM.");
    std::puts("The only required argument is the input .asm file.");
    std::puts("The first argument should be one of the input file or help.");
    std::puts("Here are the supported options:");
    std::puts("   --dump-asm | -dasm -- dumps the assembled statements with memory locations");
    std::puts("   --output | -o -- the name of the output ROM file. By default, it is 'a.rom'");
    std::puts("   --help | -h -- displays this help screen");
}

int main(int argc, char **argv)
{
    try {
        AsmOpts opts;
        if (!parse_args(argc, argv, &opts)) {
            show_help();
            return EXIT_FAILURE;
        }

        if (opts.show_help) {
            show_help();
            return EXIT_SUCCESS;
        }

        const std::string text = read_file(argv[1]);
        if (text.empty()) {
            std::fprintf(stderr, "Error reading from '%s'\n", text.c_str());
            return EXIT_FAILURE;
        }

        emu::Lexer lexer(text);
        c8::Parser parser(lexer);
        parser.parse();

        auto instructions = parser.getInstructions();
        auto labels = parser.getLabels();
        write_rom(opts.out_file, instructions, labels);
        if (opts.dump_asm) {
            dump_asm(instructions, labels);
        }

        std::puts("Done.");

    } catch (const ParseException& e) {
        std::fprintf(stderr, "Caught Parse Exception: %s\n", e.what());
    } catch (const std::exception& e) {
        std::fprintf(stderr, "Caught generic exception: %s\n", e.what());
    } catch (...) {
        std::fprintf(stderr, "Unknown error! Please retry!\n");
    }
}
<|endoftext|>


<commit_before>// This file was developed by Thomas Müller <thomas94@gmx.net>.
// It is published under the BSD 3-Clause License within the LICENSE file.

#include "../include/ImageViewer.h"
#include "../include/SharedQueue.h"
#include "../include/ThreadPool.h"

#include <args.hxx>
#include <ImfThreading.h>

#include <iostream>
#include <thread>

using namespace args;
using namespace std;

TEV_NAMESPACE_BEGIN

int mainFunc(int argc, char* argv[]) {
    Imf::setGlobalThreadCount(thread::hardware_concurrency());

    ArgumentParser parser{
        "Inspection tool for images with a high dynamic range.",
        "",
    };

    HelpFlag helpFlag{
        parser,
        "help",
        "Display this help menu",
        {'h', "help"},
    };

    ValueFlag<float> exposureFlag{
        parser,
        "exposure",
        "Exposure scales the brightness of an image prior to tonemapping by 2^Exposure. "
        "It can be controlled via the GUI, or by pressing E/Shift+E.",
        {'e', "exposure"},
    };

    ValueFlag<string> filterFlag{
        parser,
        "filter",
        "Filters visible images and layers according to a supplied string. "
        "The string must have the format 'image:layer'. "
        "Only images whose name contains 'image' and layers whose name contains 'layer' will be visible.",
        {'f', "filter"},
    };

    ValueFlag<bool> maximizeFlag{
        parser,
        "maximize",
        "Whether to maximize the window on startup or not. "
        "If no images were supplied via the command line, then the default is false. "
        "Otherwise, the default is true.",
        {"max", "maximize"},
    };

    ValueFlag<string> metricFlag{
        parser,
        "metric",
        "The metric to use when comparing two images. "
        R"(
        The available metrics are:
        E   - Error
        AE  - Absolute Error
        SE  - Squared Error
        RAE - Relative Absolute Error
        RSE - Relative Squared Error
        )"
        "Default is E.",
        {'m', "metric"},
    };

    ValueFlag<float> offsetFlag{
        parser,
        "offset",
        "The offset is added to the image after exposure has been applied. "
        "It can be controlled via the GUI, or by pressing O/Shift+O.",
        {'o', "offset"},
    };

    ValueFlag<string> tonemapFlag{
        parser,
        "tonemap",
        "The tonemapping algorithm to use. "
        R"(
        The available tonemaps are:
        sRGB   - sRGB
        Gamma  - Gamma curve (2.2)
        FC     - False Color
        PN     - Positive=Green, Negative=Red
        )"
        "Default is sRGB.",
        {'t', "tonemap"},
    };

    PositionalList<string> imageFiles{
        parser,
        "images or channel selectors",
        "The image files to be opened by the viewer. "
        "If a filename starting with a ':' is encountered, "
        "then this filename is not treated as an image file "
        "but as a comma-separated channel selector. Until the next channel "
        "selector is encountered only channels containing "
        "elements from the current selector will be loaded. This is "
        "especially useful for selectively loading a specific "
        "part of a multi-part EXR file.",
    };

    // Parse command line arguments and react to parsing
    // errors using exceptions.
    try {
        parser.ParseCLI(argc, argv);
    } catch (args::Help) {
        std::cout << parser;
        return 0;
    } catch (args::ParseError e) {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return -1;
    } catch (args::ValidationError e) {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return -2;
    }

    auto ipc = make_shared<Ipc>();

    // If we're not the primary instance, simply send the to-be-opened images
    // to the primary instance.
    if (!ipc->isPrimaryInstance()) {
        string channelSelector;
        for (auto imageFile : get(imageFiles)) {
            if (!imageFile.empty() && imageFile[0] == ':') {
                channelSelector = imageFile.substr(1);
                continue;
            }

            try {
                ipc->sendToPrimaryInstance(absolutePath(imageFile) + ":" + channelSelector);
            } catch (runtime_error e) {
                cerr << "Invalid file '" << imageFile << "': " << e.what() << endl;
            }
        }

        return 0;
    }

    cout << "Loading window..." << endl;

    // Load images passed via command line in the background prior to
    // creating our main application such that they are not stalled
    // by the potentially slow initialization of opengl / glfw.
    shared_ptr<SharedQueue<ImageAddition>> imagesToAdd = make_shared<SharedQueue<ImageAddition>>();
    string channelSelector;
    for (auto imageFile : get(imageFiles)) {
        if (!imageFile.empty() && imageFile[0] == ':') {
            channelSelector = imageFile.substr(1);
            continue;
        }

        ThreadPool::singleWorker().enqueueTask([imageFile, channelSelector, &imagesToAdd] {
            auto image = tryLoadImage(imageFile, channelSelector);
            if (image) {
                imagesToAdd->push({false, image});
            }
        });
    }

    // Init nanogui application
    nanogui::init();

    {
        auto app = unique_ptr<ImageViewer>{new ImageViewer{ipc, imagesToAdd}};
        app->drawAll();
        app->setVisible(true);

        // Do what the maximize flag tells us---if it exists---and
        // maximize if we have images otherwise.
        if (maximizeFlag ? get(maximizeFlag) : imageFiles) {
            app->maximize();
        }

        // Apply parameter flags
        if (exposureFlag) { app->setExposure(get(exposureFlag)); }
        if (filterFlag)   { app->setFilter(get(filterFlag)); }
        if (metricFlag)   { app->setMetric(toMetric(get(metricFlag))); }
        if (offsetFlag)   { app->setOffset(get(offsetFlag)); }
        if (tonemapFlag)  { app->setTonemap(toTonemap(get(tonemapFlag))); }

        // Refresh only every 250ms if there are no user interactions.
        // This makes an idling tev surprisingly energy-efficient. :)
        nanogui::mainloop(250);
    }

    // On some linux distributions glfwTerminate() (which is called by
    // nanogui::shutdown()) causes segfaults. Since we are done with our
    // program here anyways, let's let the OS clean up after us.
    //nanogui::shutdown();

    // Let all threads gracefully terminate.
    ThreadPool::shutdown();

    return 0;
}

TEV_NAMESPACE_END

int main(int argc, char* argv[]) {
    try {
        tev::mainFunc(argc, argv);
    } catch (const runtime_error& e) {
        cerr << "Uncaught exception: " << e.what() << endl;
        return 1;
    }
}
<commit_msg>Only spin up Imf threads in the primary instance<commit_after>// This file was developed by Thomas Müller <thomas94@gmx.net>.
// It is published under the BSD 3-Clause License within the LICENSE file.

#include "../include/ImageViewer.h"
#include "../include/SharedQueue.h"
#include "../include/ThreadPool.h"

#include <args.hxx>
#include <ImfThreading.h>

#include <iostream>
#include <thread>

using namespace args;
using namespace std;

TEV_NAMESPACE_BEGIN

int mainFunc(int argc, char* argv[]) {
    ArgumentParser parser{
        "Inspection tool for images with a high dynamic range.",
        "",
    };

    HelpFlag helpFlag{
        parser,
        "help",
        "Display this help menu",
        {'h', "help"},
    };

    ValueFlag<float> exposureFlag{
        parser,
        "exposure",
        "Exposure scales the brightness of an image prior to tonemapping by 2^Exposure. "
        "It can be controlled via the GUI, or by pressing E/Shift+E.",
        {'e', "exposure"},
    };

    ValueFlag<string> filterFlag{
        parser,
        "filter",
        "Filters visible images and layers according to a supplied string. "
        "The string must have the format 'image:layer'. "
        "Only images whose name contains 'image' and layers whose name contains 'layer' will be visible.",
        {'f', "filter"},
    };

    ValueFlag<bool> maximizeFlag{
        parser,
        "maximize",
        "Whether to maximize the window on startup or not. "
        "If no images were supplied via the command line, then the default is false. "
        "Otherwise, the default is true.",
        {"max", "maximize"},
    };

    ValueFlag<string> metricFlag{
        parser,
        "metric",
        "The metric to use when comparing two images. "
        R"(
        The available metrics are:
        E   - Error
        AE  - Absolute Error
        SE  - Squared Error
        RAE - Relative Absolute Error
        RSE - Relative Squared Error
        )"
        "Default is E.",
        {'m', "metric"},
    };

    ValueFlag<float> offsetFlag{
        parser,
        "offset",
        "The offset is added to the image after exposure has been applied. "
        "It can be controlled via the GUI, or by pressing O/Shift+O.",
        {'o', "offset"},
    };

    ValueFlag<string> tonemapFlag{
        parser,
        "tonemap",
        "The tonemapping algorithm to use. "
        R"(
        The available tonemaps are:
        sRGB   - sRGB
        Gamma  - Gamma curve (2.2)
        FC     - False Color
        PN     - Positive=Green, Negative=Red
        )"
        "Default is sRGB.",
        {'t', "tonemap"},
    };

    PositionalList<string> imageFiles{
        parser,
        "images or channel selectors",
        "The image files to be opened by the viewer. "
        "If a filename starting with a ':' is encountered, "
        "then this filename is not treated as an image file "
        "but as a comma-separated channel selector. Until the next channel "
        "selector is encountered only channels containing "
        "elements from the current selector will be loaded. This is "
        "especially useful for selectively loading a specific "
        "part of a multi-part EXR file.",
    };

    // Parse command line arguments and react to parsing
    // errors using exceptions.
    try {
        parser.ParseCLI(argc, argv);
    } catch (args::Help) {
        std::cout << parser;
        return 0;
    } catch (args::ParseError e) {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return -1;
    } catch (args::ValidationError e) {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return -2;
    }

    auto ipc = make_shared<Ipc>();

    // If we're not the primary instance, simply send the to-be-opened images
    // to the primary instance.
    if (!ipc->isPrimaryInstance()) {
        string channelSelector;
        for (auto imageFile : get(imageFiles)) {
            if (!imageFile.empty() && imageFile[0] == ':') {
                channelSelector = imageFile.substr(1);
                continue;
            }

            try {
                ipc->sendToPrimaryInstance(absolutePath(imageFile) + ":" + channelSelector);
            } catch (runtime_error e) {
                cerr << "Invalid file '" << imageFile << "': " << e.what() << endl;
            }
        }

        return 0;
    }

    Imf::setGlobalThreadCount(thread::hardware_concurrency());

    cout << "Loading window..." << endl;

    // Load images passed via command line in the background prior to
    // creating our main application such that they are not stalled
    // by the potentially slow initialization of opengl / glfw.
    shared_ptr<SharedQueue<ImageAddition>> imagesToAdd = make_shared<SharedQueue<ImageAddition>>();
    string channelSelector;
    for (auto imageFile : get(imageFiles)) {
        if (!imageFile.empty() && imageFile[0] == ':') {
            channelSelector = imageFile.substr(1);
            continue;
        }

        ThreadPool::singleWorker().enqueueTask([imageFile, channelSelector, &imagesToAdd] {
            auto image = tryLoadImage(imageFile, channelSelector);
            if (image) {
                imagesToAdd->push({false, image});
            }
        });
    }

    // Init nanogui application
    nanogui::init();

    {
        auto app = unique_ptr<ImageViewer>{new ImageViewer{ipc, imagesToAdd}};
        app->drawAll();
        app->setVisible(true);

        // Do what the maximize flag tells us---if it exists---and
        // maximize if we have images otherwise.
        if (maximizeFlag ? get(maximizeFlag) : imageFiles) {
            app->maximize();
        }

        // Apply parameter flags
        if (exposureFlag) { app->setExposure(get(exposureFlag)); }
        if (filterFlag)   { app->setFilter(get(filterFlag)); }
        if (metricFlag)   { app->setMetric(toMetric(get(metricFlag))); }
        if (offsetFlag)   { app->setOffset(get(offsetFlag)); }
        if (tonemapFlag)  { app->setTonemap(toTonemap(get(tonemapFlag))); }

        // Refresh only every 250ms if there are no user interactions.
        // This makes an idling tev surprisingly energy-efficient. :)
        nanogui::mainloop(250);
    }

    // On some linux distributions glfwTerminate() (which is called by
    // nanogui::shutdown()) causes segfaults. Since we are done with our
    // program here anyways, let's let the OS clean up after us.
    //nanogui::shutdown();

    // Let all threads gracefully terminate.
    ThreadPool::shutdown();

    return 0;
}

TEV_NAMESPACE_END

int main(int argc, char* argv[]) {
    try {
        tev::mainFunc(argc, argv);
    } catch (const runtime_error& e) {
        cerr << "Uncaught exception: " << e.what() << endl;
        return 1;
    }
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "TwitchBot.h"

static struct botData {
	std::string name;
	std::string channel;
	std::string pass;
};

botData readSettings(const std::string &appDir);

int main() {

	botData bd;

	try {
		bd = readSettings(utils::getApplicationDirectory());
		if (bd.name.empty()) {
			throw std::runtime_error("Could not extract name from settings.txt");
		}
		if (bd.channel.empty()) {
			throw std::runtime_error("Could not extract channel from settings.txt");
		}
		if (bd.pass.empty()) {
			throw std::runtime_error("Could not extract password from settings.txt");
		}
	}
	catch (std::runtime_error &e) {
		std::cerr << e.what();
		std::cin.get();
		return 1;
	}

	TwitchBot bot(bd.name, bd.channel, bd.pass);

	if (bot.isConnected()) {
		bot.serverLoop();
	}

	return 0;

}

botData readSettings(const std::string &appDir) {

	// open settings.cfg
	std::ifstream reader(appDir + "\\settings.txt");
	if (!reader.is_open()) {
		throw std::runtime_error("Could not locate settings.txt");
	}

	std::string line;
	uint8_t lineNum = 0;
	botData bd;

	while (std::getline(reader, line)) {

		lineNum++;
		// remove whitespace
		line.erase(std::remove_if(line.begin(), line.end(), isspace), line.end());

		// lines starting with * are comments
		if (utils::startsWith(line, "*")) {
			continue;
		}
		else {
			std::regex lineRegex("(name|channel|password):(.+?)");
			std::smatch match;
			const std::string s = line;
			if (std::regex_match(s.begin(), s.end(), match, lineRegex)) {
				if (match[1].str() == "name") {
					bd.name = match[2];
				}
				else if (match[1].str() == "channel") {
					if (!utils::startsWith(match[2].str(), "#")) {
						throw std::runtime_error("Channel name must start with #.");
					}
					bd.channel = match[2];
				}
				else {
					if (!utils::startsWith(match[2].str(), "oauth:")) {
						throw std::runtime_error("Password must be a valid oauth token, starting with \"oauth:\".");
					}
					bd.pass = match[2];
				}
			}
			else {
				throw std::runtime_error("Syntax error on line " + std::to_string(lineNum) + " of settings.txt.");
			}
		}

	}

	reader.close();
	return bd;

}<commit_msg>Minor change<commit_after>#include "stdafx.h"
#include "TwitchBot.h"
#include <pencode.h>

struct botData {
	std::string name;
	std::string channel;
	std::string pass;
};

botData readSettings(const std::string &appDir);

int main() {

	botData bd;

	try {
		bd = readSettings(utils::getApplicationDirectory());
		if (bd.name.empty()) {
			throw std::runtime_error("Could not extract name from settings.txt");
		}
		if (bd.channel.empty()) {
			throw std::runtime_error("Could not extract channel from settings.txt");
		}
		if (bd.pass.empty()) {
			throw std::runtime_error("Could not extract password from settings.txt");
		}
	}
	catch (std::runtime_error &e) {
		std::cerr << e.what();
		std::cin.get();
		return 1;
	}

	TwitchBot bot(bd.name, bd.channel, bd.pass);

	if (bot.isConnected()) {
		bot.serverLoop();
	}

	return 0;

}

botData readSettings(const std::string &appDir) {

	// open settings.cfg
	std::ifstream reader(appDir + "\\settings.txt");
	if (!reader.is_open()) {
		throw std::runtime_error("Could not locate settings.txt");
	}

	std::string line;
	uint8_t lineNum = 0;
	botData bd;

	while (std::getline(reader, line)) {

		lineNum++;
		// remove whitespace
		line.erase(std::remove_if(line.begin(), line.end(), isspace), line.end());

		// lines starting with * are comments
		if (utils::startsWith(line, "*")) {
			continue;
		}
		else {
			std::regex lineRegex("(name|channel|password):(.+?)");
			std::smatch match;
			const std::string s = line;
			if (std::regex_match(s.begin(), s.end(), match, lineRegex)) {
				if (match[1].str() == "name") {
					bd.name = match[2];
				}
				else if (match[1].str() == "channel") {
					if (!utils::startsWith(match[2].str(), "#")) {
						throw std::runtime_error("Channel name must start with #.");
					}
					bd.channel = match[2];
				}
				else {
					if (!utils::startsWith(match[2].str(), "oauth:")) {
						throw std::runtime_error("Password must be a valid oauth token, starting with \"oauth:\".");
					}
					bd.pass = match[2];
				}
			}
			else {
				throw std::runtime_error("Syntax error on line " + std::to_string(lineNum) + " of settings.txt.");
			}
		}

	}

	reader.close();
	return bd;

}<|endoftext|>