<commit_before>//=============================================================================
//File Name: Main.cpp
//Description: Unloads /ni-rt/system/FRC_UserProgram.out, then reloads it and
//             exits
//Author: FRC Team 3512, Spartatroniks
//=============================================================================

#include <stdio.h>
#include <ioLib.h>
#include <loadLib.h>
#include <unldLib.h>
#include <taskLib.h>
#include <WPILib/NetworkCommunication/symModuleLink.h>

extern "C" {
INT32 FRC_UserProgram_StartupLibraryInit();
}

int ALFmain() {
    printf( "ALF.out started\n" );

    // Check for startup code already running
    INT32 oldId = taskNameToId( "FRC_RobotTask" );

    if ( oldId != ERROR ) {
        // Find the startup code module.
        char moduleName[256];
        moduleNameFindBySymbolName( "FRC_UserProgram_StartupLibraryInit" , moduleName );
        MODULE_ID startupModId = moduleFindByName( moduleName );

        if ( startupModId != NULL ) {
            // Remove the startup code.
            printf( "%d\n" , unldByModuleId( startupModId , 0 ) );
        }
    }

    int program = open( "/ni-rt/system/FRC_UserProgram.out" , O_RDONLY , 0 );
    loadModule( program , LOAD_ALL_SYMBOLS | LOAD_CPLUS_XTOR_AUTO );
    close( program );

    taskSpawn( "FRC_RobotTask" , // Task name
            101 , // Priority
            VX_FP_TASK , // Task option flag
            0xFFFF , // Stack size
            (FUNCPTR)FRC_UserProgram_StartupLibraryInit , // Entry point
            0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ); // unused task args

    return 0;
}
<commit_msg>Fixed robot rebooting when robot code is broken<commit_after>//=============================================================================
//File Name: Main.cpp
//Description: Unloads /ni-rt/system/FRC_UserProgram.out, then reloads it and
//             exits
//Author: FRC Team 3512, Spartatroniks
//=============================================================================

#define VxWorks

#ifdef UNIX
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#endif

#ifdef VxWorks
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <hostLib.h>
#include <ioLib.h>
#include <sockLib.h>
#include <signal.h>
#include <selectLib.h>
#include <rebootLib.h>
#include <loadLib.h>
#include <unldLib.h>
#include <moduleLib.h>
#include <sysSymTbl.h>
#include <taskLib.h>
#define socklen_t int

/* load on startup */
int alf_entrypoint();
int alf_main();
const int32_t alf_entrystatus = alf_entrypoint();
#endif

void
rebootRobot()
{
    std::printf("rebooting...\n");

#ifdef VxWorks
    reboot(0);
#endif

    std::printf("...not really!\n");

    return;
}

void
reloadRobot()
{
    // Get the task ID of the robot code if it's already running
    INT32 oldId;
    oldId = taskNameToId("pthr1");
    if ( oldId != ERROR ) {
        std::printf( "pthr1 task ID found\n" );
        taskDelete( oldId );
    }

    // Get a list of the first 50 tasks
    int idList[50];
    int numTasks = taskIdListGet( idList , 50 );

    char* name;
    char taskNameStart[5];
    taskNameStart[4] = '\0';

    // Delete any tasks with "FRC_" at the beginning of their names
    for ( int i = 0 ; i < numTasks ; i++ ) {
        // Copy the first 4 bytes of the task's name
        name = taskName( idList[i] );
        std::memcpy( taskNameStart , name , 4 );

        // If they match "FRC_", delete the task b/c the robot code created it
        if ( std::strcmp( taskNameStart , "FRC_" ) == 0 ) {
            taskDelete( idList[i] );
        }
    }

    // Find the startup code module.
    char moduleName[256];
    //strcpy("FRC_UserProgram-1.out", moduleName);
    MODULE_ID startupModId = moduleFindByName("FRC_UserProgram-1.out");
    if ( startupModId != NULL ) {
        std::printf( "unloading module\n" );
        // Remove the startup code.
        moduleDelete( startupModId );
        unldByModuleId(startupModId, UNLD_FORCE);
    }

#if 0
    int program = open( "/ni-rt/system/FRC_UserProgram-1.out" , O_RDONLY , 0 );
    MODULE_ID frcCodeModule = loadModule( program , LOAD_ALL_SYMBOLS | LOAD_CPLUS_XTOR_AUTO );
    close( program );

    if ( frcCodeModule != NULL ) {
        printf( "frc module loaded\n" );
        VOIDFUNCPTR frcFunctionPtr;
        uint8_t symbolType;
        symFindByName( sysSymTbl , "FRC_UserProgram_StartupLibraryInit" , (char**)&frcFunctionPtr , &symbolType );
        printf( "reloading...\n" );
        frcFunctionPtr();
    }
    else {
        std::printf( "...not really!\n" );
    }
#endif

    return;
}

int
procCommands(int sockfd)
{
    char buf[1024];
    char *cbuf;

    for ( cbuf = buf ; *(cbuf-1) != '\n' ; cbuf++ ) {
        if( recv( sockfd , cbuf , 1 , 0 ) != 1 ) {
            return -1;
        }
    }

    // add the null terminator
    *(cbuf-2) = '\0';

    if( std::strcmp( buf , "reboot" ) == 0 ) {
        rebootRobot();
    }
    else if( std::strcmp( buf , "reload" ) == 0 ) {
        reloadRobot();
    }

    return 0;
}

int alf_entrypoint() {
    taskSpawn( "ALF", // Task name
            101, // Priority
            VX_FP_TASK, // Task option flag
            0xFFFF, // Stack size
            (FUNCPTR)alf_main, // Entry point
            0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ); // Unused task args

    return 0;
}

int
alf_main()
{
    int sockfd, nsockfd;
    int portno;
    socklen_t clilen;
    struct sockaddr_in serv_addr, cli_addr;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    bzero((char *) &serv_addr, sizeof(serv_addr));
    portno = 3512;
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(portno);
    bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
    listen(sockfd,5);
    clilen = sizeof(cli_addr);
    signal(SIGPIPE, SIG_IGN);

    while( 1 ) {
        // Accept commands from elsewhere as string and process them
        nsockfd = accept(sockfd, (struct sockaddr *) &cli_addr,
            &clilen);
        while( procCommands(nsockfd) == 0 );
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include "Player.h"
#include "Board.h"
#include "Input.h"
using  namespace std;
int main(){

	const int maxNumPlayers = 10;
	Player players[maxNumPlayers];

	Input inputGame; //Welcome and get numofplayers

	inputGame.playersInfo(players); //Names & Symbols

	bool isOver = false;  //Allow infinite plays/matches
	bool isWon = false;   //know which player wins the round
	char symbol;
	Player player; //current player
	while (!isOver){ //Play another match
		int boardWidth = 3, boardHeight = 3, markersWin = 3;
		//Ask boardsize and number of marks to win:
		inputGame.boardInfo(boardWidth, boardHeight, markersWin);

		Board board;
		board.setBoardSize(boardWidth, boardHeight);
		board.initBoard(); //Initialize board with it size, blank = '.'

		int numOfPlayers = inputGame.getnumPlayers();
		while (!isWon){
			for (int i = 0; i < numOfPlayers; i++){
				//player currently playing: (i: turn)
				player = players[i];
				symbol = player.getPlayerSymbol();
				//x = col,  y = row;
				inputGame.InputTurns(board, player, symbol);

				//isWon = hasWon(board, markersWin, symbol);

				isWon = board.hasWon(markersWin, symbol);

				if (isWon){
					cout << "Congratulations " << player.getPlayerName() << " you win!\n";
					char yesno;
					do
					{
						board.printBoard();
						cout << "Want to keep playing? (Y/N) ";
						cin >> yesno;
					} while (yesno != 'Y' && yesno != 'N');
					isOver = yesno == 'Y' ? false : true;
					break;
				}
			}
		}
		if (!isOver) isWon = false;
	}
	system("PAUSE");
	return 0;
}
<commit_msg>Delete Main.cpp<commit_after><|endoftext|>


<commit_before>
# include <Siv3D.hpp>

class Block
{
public:

	// 引数のないコンストラクタも作っておくといろいろ便利.
	Block() {}

	Block(const RectF& region) :
		m_region(region),
		m_texture(L"Example/Brick.jpg") {}

	// 描画以外の操作をする関数
	void update()
	{
		// 今回は何もない
	}

	// 描画をする関数（描画操作以外行わないこと.）
	void draw()
	{
		m_region(m_texture).draw();
	}

private:

	// ブロックの領域
	RectF m_region;

	// ブロックのテキスチャ（画像）
	Texture m_texture;
};

class Player
{
public:

	Player() :
		m_position(100, 200),
		m_texture(L"Example/Siv3D-kun.png") {}

	// 描画以外の操作をする関数
	void update()
	{
		if (Input::KeyRight.pressed)
		{
			m_position.x += 5.0;
		}
		else if (Input::KeyLeft.pressed)
		{
			m_position.x -= 5.0;
		}
	}

	// 描画をする関数（描画操作以外行わないこと.）
	void draw()
	{
		RectF(m_position.x - 72.5, m_position.y - 200, 145, 200)(m_texture).draw();
	}

private:

	// プレイヤーの座標
	Vec2 m_position;

	// プレイヤーのテクスチャ（画像）
	Texture m_texture;
};

void Main()
{
	Window::Resize(1280, 720);

	Texture background(L"Example/Windmill.png");
	Player player;
	Array<Block> blocks;

	blocks.push_back(Block({-400, 400, 200, 200}));
	blocks.push_back(Block({-200, 400, 200, 200}));
	blocks.push_back(Block({0, 400, 200, 200}));
	blocks.push_back(Block({200, 400, 200, 200}));
	blocks.push_back(Block({200, 200, 200, 200}));
	blocks.push_back(Block({400, 400, 200, 200}));
	blocks.push_back(Block({800, 400, 200, 200}));
	blocks.push_back(Block({1000, 400, 200, 200}));
	blocks.push_back(Block({1300, 200, 400, 30}));

	while (System::Update())
	{
		for (size_t i = 0; i < blocks.size(); i++)
		{
			blocks[i].update();
		}

		player.update();

		// 本来ならリサイズしなくていいように画像を用意すべき.
		background.scale(1280.0 / 480.0).draw();

		for (size_t i = 0; i < blocks.size(); i++)
		{
			blocks[i].draw();
		}

		player.draw();
	}
}
<commit_msg>Make sure to stop if Left and Right key pressed.<commit_after>
# include <Siv3D.hpp>

class Block
{
public:

	// 引数のないコンストラクタも作っておくといろいろ便利.
	Block() {}

	Block(const RectF& region) :
		m_region(region),
		m_texture(L"Example/Brick.jpg") {}

	// 描画以外の操作をする関数
	void update()
	{
		// 今回は何もない
	}

	// 描画をする関数（描画操作以外行わないこと.）
	void draw()
	{
		m_region(m_texture).draw();
	}

private:

	// ブロックの領域
	RectF m_region;

	// ブロックのテキスチャ（画像）
	Texture m_texture;
};

class Player
{
public:

	Player() :
		m_position(100, 200),
		m_texture(L"Example/Siv3D-kun.png") {}

	// 描画以外の操作をする関数
	void update()
	{
		if (Input::KeyRight.pressed)
		{
			m_position.x += 5.0;
		}
		if (Input::KeyLeft.pressed)
		{
			m_position.x -= 5.0;
		}
	}

	// 描画をする関数（描画操作以外行わないこと.）
	void draw()
	{
		RectF(m_position.x - 72.5, m_position.y - 200, 145, 200)(m_texture).draw();
	}

private:

	// プレイヤーの座標
	Vec2 m_position;

	// プレイヤーのテクスチャ（画像）
	Texture m_texture;
};

void Main()
{
	Window::Resize(1280, 720);

	Texture background(L"Example/Windmill.png");
	Player player;
	Array<Block> blocks;

	blocks.push_back(Block({-400, 400, 200, 200}));
	blocks.push_back(Block({-200, 400, 200, 200}));
	blocks.push_back(Block({0, 400, 200, 200}));
	blocks.push_back(Block({200, 400, 200, 200}));
	blocks.push_back(Block({200, 200, 200, 200}));
	blocks.push_back(Block({400, 400, 200, 200}));
	blocks.push_back(Block({800, 400, 200, 200}));
	blocks.push_back(Block({1000, 400, 200, 200}));
	blocks.push_back(Block({1300, 200, 400, 30}));

	while (System::Update())
	{
		for (size_t i = 0; i < blocks.size(); i++)
		{
			blocks[i].update();
		}

		player.update();

		// 本来ならリサイズしなくていいように画像を用意すべき.
		background.scale(1280.0 / 480.0).draw();

		for (size_t i = 0; i < blocks.size(); i++)
		{
			blocks[i].draw();
		}

		player.draw();
	}
}
<|endoftext|>


<commit_before>#include "../common/init.h"
#include "../common/timer.h"

#include <iostream>
#include <vector>
#include <stdexcept>

#include "util/stretch-bitmap.h"
#include "util/font.h"
#include "util/debug.h"
#include "util/load_exception.h"
#include "util/token_exception.h"
#include "util/stretch-bitmap.h"
#include "util/input/input.h"
#include "util/input/input-manager.h"
#include "util/sound.h"
#include "util/exceptions/exception.h"
#include "util/network/network.h"
#include "util/network/chat.h"
#include "util/network/irc.h"
#include "util/thread.h"
#include "util/pointer.h"
#include "util/system.h"

#include "mugen/util.h"
#include "mugen/search.h"
#include "mugen/exception.h"
#include "mugen/options.h"

#include "mugen/widgets.h"

#include <queue>

static bool isChatMessage(const ::Network::Chat::Message & message){
    if (message.getType() == ::Network::Chat::Message::Ping ||
        message.getType() == ::Network::Chat::Message::Unknown){
        return false;
    }
    return true;
}

enum ConnectionType{
    Server,
    Client,
    IrcClient,
};

static std::string unsplit(const std::vector< std::string > & message, unsigned int start = 0){
    std::string all;
    for (unsigned int i = start; i < message.size(); ++i){
        try {
            all+=message.at(i) + (i < message.size()-1 ? " " : "");
        } catch (const std::out_of_range & ex){
        }
    }
    return all;
}

class InputLogicDraw: public PaintownUtil::Logic, public PaintownUtil::Draw, public Mugen::Widgets::ChatPanel::Event{
public:
    InputLogicDraw(const ConnectionType & type, int port, const std::string & host = "127.0.0.1"):
    panel(10, 20, 300, 200),
    escaped(false){
        std::vector< PaintownUtil::ReferenceCount<Gui::ScrollItem> > list;
        Mugen::OptionMenu menu(list);
        panel.setFont(menu.getFont());
        panel.setClient("You");
        panel.subscribe(this);
        if (type == Server){
            server = PaintownUtil::ReferenceCount< ::Network::Chat::Server >(new ::Network::Chat::Server(port));
            server->start();
        } else if (type == Client){
            Global::debug(0) << "Connecting to " << host << " on port " << port << std::endl;
            Network::Socket socket = Network::connect(host, port);
            Global::debug(0) << "Connected" << std::endl;
            client = PaintownUtil::ReferenceCount< ::Network::Chat::Client >(new ::Network::Chat::Client(0, socket));
            client->start();
        } else if (type == IrcClient){
            ircClient = PaintownUtil::ReferenceCount< ::Network::IRC::Client >(new ::Network::IRC::Client(host, port));
            ircClient->connect();
            panel.setClient(ircClient->getName());
        }
    }

    Mugen::Widgets::ChatPanel panel;

    bool escaped;

    Network::Socket socket;

    std::queue< ::Network::Chat::Message > sendable;
    std::queue< ::Network::Chat::Message > messages;

    PaintownUtil::ReferenceCount< ::Network::Chat::Client > client;
    PaintownUtil::ReferenceCount< ::Network::Chat::Server > server;
    PaintownUtil::ReferenceCount< ::Network::IRC::Client > ircClient;

    ::Util::Thread::LockObject lock;
    ::Util::Thread::Id thread;

    double ticks(double system){
        return system;
    }

    void run(){
        try {
            panel.act();
            if (ircClient == NULL){
                sendMessages();
            }
            processMessages();
            if (server != NULL){
                server->cleanup();
            }
        } catch (const Exception::Return & ex){
            escaped = true;
            if (server != NULL){
                server->shutdown();
            } else if (client != NULL){
                client->shutdown();
            }
            throw ex;
        }
    }

    bool done(){
        return escaped;
    }

    void sendMessages(){
        while (!sendable.empty()){
            ::Network::Chat::Message & next = sendable.front();
            if (isChatMessage(next)){
                if (server != NULL){
                    server->global(next);
                } else if (client != NULL){
                    client->sendMessage(next);
                }
            }
            sendable.pop();
        }
    }

    void processMessages(){
        if (server != NULL){
            server->poll();
            while (server->hasMessages()){
                ::Network::Chat::Message message = server->nextMessage();
                if (isChatMessage(message)){
                    panel.addMessage(message.getName(), message.getMessage());
                }
            }
        } else if (client != NULL) {
            while (client->hasMessages()){
                ::Network::Chat::Message message = client->nextMessage();
                if (isChatMessage(message)){
                    panel.addMessage(message.getName(), message.getMessage());
                }
            }
        } else if (ircClient != NULL) {
            while (ircClient->hasCommands()){
                ::Network::IRC::Command command = ircClient->nextCommand();
                std::vector<std::string> params = command.getParameters();
                //Global::debug(0) << "Got message: " << command.getSendable() << std::endl;
                try {
                    if (command.getType() == ::Network::IRC::Command::Ping){
                        ircClient->sendPong(command);
                        panel.addMessage(command.getOwner(), "*** Ping!");
                    } else if (command.getType() == ::Network::IRC::Command::PrivateMessage ||
                              command.getType() == ::Network::IRC::Command::Notice){
                        // Username and message
                        panel.addMessage(command.getOwner(), params.at(1));
                    } else if (command.getType() == ::Network::IRC::Command::ReplyMOTD){
                        panel.addMessage("*** MOTD - " + params.at(1));
                    } else if (command.getType() == ::Network::IRC::Command::Join){
                        panel.addMessage("*** You have joined the channel " + params.at(0) + ".");
                    } else if (command.getType() == ::Network::IRC::Command::ReplyTopic){
                        panel.addMessage("*** The channel topic is \"" + params.at(2) + "\".");
                    } else if (command.getType() == ::Network::IRC::Command::ReplyNames){
                        panel.addMessage("*** Current users on " + params.at(1) + " \"" + params.at(2) + "\".");
                    } else if (command.getType() == ::Network::IRC::Command::Error){
                        Global::debug(0) << "Received Error: " << command.getSendable() << "... Aborting." << std::endl;
                        throw Exception::Return(__FILE__, __LINE__);
                    }
                } catch (const std::out_of_range & ex){
                }
            }
        }
    }

    void sendMessage(const std::string & message){
        ::Util::Thread::ScopedLock scope(lock);
        if (ircClient == NULL){
            if (panel.getClient() == "You"){
                ::Network::Chat::Message ourMessage(::Network::Chat::Message::Chat, "remote", message);
                sendable.push(ourMessage);
            } else {
                ::Network::Chat::Message ourMessage(::Network::Chat::Message::Chat, panel.getClient(), message);
                sendable.push(ourMessage);
            }
        } else if (ircClient != NULL){
            ircClient->sendMessage(message);
        }
    }

    void handleCommand(const std::vector<std::string> & command){
        if (ircClient == NULL){
            try {
                if (command.at(0) == "help"){
                    panel.addMessage("* commands: help, nick");
                } else if (command.at(0) == "nick"){
                    const std::string & nick = command.at(1);
                    if (!nick.empty()){
                        panel.setClient(nick);
                        panel.addMessage("* nick changed to " + nick);
                    }
                } else {
                    panel.addMessage("* Uknown command.");
                }
            } catch (const std::out_of_range & ex){
            }
        } else if (ircClient != NULL){
            if (command.at(0) == "help"){
                panel.addMessage("* commands: help, nick, whisper, ping, join, quit");
            } else if (command.at(0) == "nick"){
                try {
                    const std::string & nick = command.at(1);
                    if (!nick.empty()){
                        ircClient->setName(nick);
                        panel.setClient(nick);
                        panel.addMessage("* nick changed to " + nick);
                    }
                } catch (const std::out_of_range & ex){
                    panel.addMessage("* /nick [name]");
                }
            } else if (command.at(0) == "whisper"){
                try {
                    const std::string & who = command.at(1);
                    const std::string & message = unsplit(command, 2);
                    if (!who.empty() && !message.empty()){
                        ircClient->sendCommand(::Network::IRC::Command::PrivateMessage, who, ":" + message);
                        panel.addMessage("-> " + who + " " + message);
                    }
                } catch (const std::out_of_range & ex){
                    panel.addMessage("* /whisper [nick] [message]");
                }
            } else if (command.at(0) == "ping"){
                const std::string & who = command.at(1);
                if (!who.empty()){
                    std::ostringstream timestamp;
                    timestamp << System::currentMicroseconds();
                    ircClient->sendCommand(::Network::IRC::Command::PrivateMessage, who, ":\001PING " + timestamp.str() + "\001");
                    panel.addMessage("[CTCP] Sending CTCP-PING request to " + who);
                } else {
                    panel.addMessage("* /ping [nick]");
                }
            } else if (command.at(0) == "join"){
                const std::string & channel = command.at(1);
                if (!channel.empty()){
                    ircClient->joinChannel(channel);
                } else {
                    panel.addMessage("* /join [channel]");
                }
            } else if (command.at(0) == "quit"){
                const std::string & message = unsplit(command, 1);
                if (!message.empty()){
                    ircClient->sendCommand(::Network::IRC::Command::Quit, ":" + message);
                    Global::debug(0) << "Quit (" + message + "). Waiting for server to close connection..." << std::endl;
                } else {
                    ircClient->sendCommand(::Network::IRC::Command::Quit);
                    Global::debug(0) << "Quit. Waiting for server to close connection..." << std::endl;
                }
            } else {
                panel.addMessage("* Uknown command.");
            }
        }

    }

    void draw(const Graphics::Bitmap & screen){
        Graphics::StretchedBitmap stretch(320, 240, screen);
        stretch.start();
        stretch.fill(Graphics::makeColor(255,255,255));
        panel.draw(stretch);
        stretch.finish();
        screen.BlitToScreen();
    }
};

static void doServer(int port){
    InputLogicDraw server(Server, port);
    PaintownUtil::standardLoop(server, server);
}

static void doClient(const std::string & host, int port){
    InputLogicDraw client(Client, port, host);
    PaintownUtil::standardLoop(client, client);
}

static void doIrc(const std::string & host, int port){
    InputLogicDraw client(IrcClient, port, host);
    PaintownUtil::standardLoop(client, client);
}

static void arguments(const std::string & application, int status){
    std::cout << "Usage: ./" << application << " server port" << std::endl;
    std::cout << "       ./" << application << " client port [host]" << std::endl;
    std::cout << "       ./" << application << " irc port [host]" << std::endl;
    exit(status);
}

int main(int argc, char ** argv){
    if (argc > 2){
        bool server = (strcmp(argv[1],"server")==0) ? true : false;
        bool client = (strcmp(argv[1],"client")==0) ? true : false;
        bool irc = (strcmp(argv[1],"irc")==0) ? true : false;
        if (!server && !client && !irc){
            arguments(argv[0], 1);
        }
        int port = atoi(argv[2]);
        std::string hostname = "127.0.0.1";
        if ((client || irc) && argc == 4){
            hostname = argv[3];
        }
        Screen::realInit();
        atexit(Screen::realFinish);
        Common::startTimers();

        Sound::initialize();

        Global::setDebug(2);

        Graphics::Bitmap screen(*Graphics::getScreenBuffer());
        Util::Parameter<Graphics::Bitmap*> use(Graphics::screenParameter, &screen);
        Keyboard::pushRepeatState(true);

        InputManager manager;

        Network::init();

        try {
            if (server){
                doServer(port);
            } else if (client){
                doClient(hostname, port);
            } else if (irc){
                doIrc(hostname, port);
            }
        } catch (const Exception::Return & ex){
        } catch (const Network::NetworkException & ex){
            Global::debug(0) << "Network Exception: " << ex.getMessage() << std::endl;
        }
        Network::shutdown();
    } else {
        arguments(argv[0],0);
    }
    return 0;
}
#ifdef USE_ALLEGRO
END_OF_MAIN()
#endif
<commit_msg>[mugen] Change unsplit to join. Do not catch out_of_range.<commit_after>#include "../common/init.h"
#include "../common/timer.h"

#include <iostream>
#include <vector>
#include <stdexcept>

#include "util/stretch-bitmap.h"
#include "util/font.h"
#include "util/debug.h"
#include "util/load_exception.h"
#include "util/token_exception.h"
#include "util/stretch-bitmap.h"
#include "util/input/input.h"
#include "util/input/input-manager.h"
#include "util/sound.h"
#include "util/exceptions/exception.h"
#include "util/network/network.h"
#include "util/network/chat.h"
#include "util/network/irc.h"
#include "util/thread.h"
#include "util/pointer.h"
#include "util/system.h"

#include "mugen/util.h"
#include "mugen/search.h"
#include "mugen/exception.h"
#include "mugen/options.h"

#include "mugen/widgets.h"

#include <queue>

static bool isChatMessage(const ::Network::Chat::Message & message){
    if (message.getType() == ::Network::Chat::Message::Ping ||
        message.getType() == ::Network::Chat::Message::Unknown){
        return false;
    }
    return true;
}

enum ConnectionType{
    Server,
    Client,
    IrcClient,
};

static std::string join(const std::vector< std::string > & message, unsigned int start = 0){
    std::string all;
    for (unsigned int i = start; i < message.size(); ++i){
        all+=message.at(i) + (i < message.size()-1 ? " " : "");
    }
    return all;
}

class InputLogicDraw: public PaintownUtil::Logic, public PaintownUtil::Draw, public Mugen::Widgets::ChatPanel::Event{
public:
    InputLogicDraw(const ConnectionType & type, int port, const std::string & host = "127.0.0.1"):
    panel(10, 20, 300, 200),
    escaped(false){
        std::vector< PaintownUtil::ReferenceCount<Gui::ScrollItem> > list;
        Mugen::OptionMenu menu(list);
        panel.setFont(menu.getFont());
        panel.setClient("You");
        panel.subscribe(this);
        if (type == Server){
            server = PaintownUtil::ReferenceCount< ::Network::Chat::Server >(new ::Network::Chat::Server(port));
            server->start();
        } else if (type == Client){
            Global::debug(0) << "Connecting to " << host << " on port " << port << std::endl;
            Network::Socket socket = Network::connect(host, port);
            Global::debug(0) << "Connected" << std::endl;
            client = PaintownUtil::ReferenceCount< ::Network::Chat::Client >(new ::Network::Chat::Client(0, socket));
            client->start();
        } else if (type == IrcClient){
            ircClient = PaintownUtil::ReferenceCount< ::Network::IRC::Client >(new ::Network::IRC::Client(host, port));
            ircClient->connect();
            panel.setClient(ircClient->getName());
        }
    }

    Mugen::Widgets::ChatPanel panel;

    bool escaped;

    Network::Socket socket;

    std::queue< ::Network::Chat::Message > sendable;
    std::queue< ::Network::Chat::Message > messages;

    PaintownUtil::ReferenceCount< ::Network::Chat::Client > client;
    PaintownUtil::ReferenceCount< ::Network::Chat::Server > server;
    PaintownUtil::ReferenceCount< ::Network::IRC::Client > ircClient;

    ::Util::Thread::LockObject lock;
    ::Util::Thread::Id thread;

    double ticks(double system){
        return system;
    }

    void run(){
        try {
            panel.act();
            if (ircClient == NULL){
                sendMessages();
            }
            processMessages();
            if (server != NULL){
                server->cleanup();
            }
        } catch (const Exception::Return & ex){
            escaped = true;
            if (server != NULL){
                server->shutdown();
            } else if (client != NULL){
                client->shutdown();
            }
            throw ex;
        }
    }

    bool done(){
        return escaped;
    }

    void sendMessages(){
        while (!sendable.empty()){
            ::Network::Chat::Message & next = sendable.front();
            if (isChatMessage(next)){
                if (server != NULL){
                    server->global(next);
                } else if (client != NULL){
                    client->sendMessage(next);
                }
            }
            sendable.pop();
        }
    }

    void processMessages(){
        if (server != NULL){
            server->poll();
            while (server->hasMessages()){
                ::Network::Chat::Message message = server->nextMessage();
                if (isChatMessage(message)){
                    panel.addMessage(message.getName(), message.getMessage());
                }
            }
        } else if (client != NULL) {
            while (client->hasMessages()){
                ::Network::Chat::Message message = client->nextMessage();
                if (isChatMessage(message)){
                    panel.addMessage(message.getName(), message.getMessage());
                }
            }
        } else if (ircClient != NULL) {
            while (ircClient->hasCommands()){
                ::Network::IRC::Command command = ircClient->nextCommand();
                std::vector<std::string> params = command.getParameters();
                //Global::debug(0) << "Got message: " << command.getSendable() << std::endl;
                try {
                    if (command.getType() == ::Network::IRC::Command::Ping){
                        ircClient->sendPong(command);
                        panel.addMessage(command.getOwner(), "*** Ping!");
                    } else if (command.getType() == ::Network::IRC::Command::PrivateMessage ||
                              command.getType() == ::Network::IRC::Command::Notice){
                        // Username and message
                        panel.addMessage(command.getOwner(), params.at(1));
                    } else if (command.getType() == ::Network::IRC::Command::ReplyMOTD){
                        panel.addMessage("*** MOTD - " + params.at(1));
                    } else if (command.getType() == ::Network::IRC::Command::Join){
                        panel.addMessage("*** You have joined the channel " + params.at(0) + ".");
                    } else if (command.getType() == ::Network::IRC::Command::ReplyTopic){
                        panel.addMessage("*** The channel topic is \"" + params.at(2) + "\".");
                    } else if (command.getType() == ::Network::IRC::Command::ReplyNames){
                        panel.addMessage("*** Current users on " + params.at(1) + " \"" + params.at(2) + "\".");
                    } else if (command.getType() == ::Network::IRC::Command::Error){
                        Global::debug(0) << "Received Error: " << command.getSendable() << "... Aborting." << std::endl;
                        throw Exception::Return(__FILE__, __LINE__);
                    }
                } catch (const std::out_of_range & ex){
                }
            }
        }
    }

    void sendMessage(const std::string & message){
        ::Util::Thread::ScopedLock scope(lock);
        if (ircClient == NULL){
            if (panel.getClient() == "You"){
                ::Network::Chat::Message ourMessage(::Network::Chat::Message::Chat, "remote", message);
                sendable.push(ourMessage);
            } else {
                ::Network::Chat::Message ourMessage(::Network::Chat::Message::Chat, panel.getClient(), message);
                sendable.push(ourMessage);
            }
        } else if (ircClient != NULL){
            ircClient->sendMessage(message);
        }
    }

    void handleCommand(const std::vector<std::string> & command){
        if (ircClient == NULL){
            try {
                if (command.at(0) == "help"){
                    panel.addMessage("* commands: help, nick");
                } else if (command.at(0) == "nick"){
                    const std::string & nick = command.at(1);
                    if (!nick.empty()){
                        panel.setClient(nick);
                        panel.addMessage("* nick changed to " + nick);
                    }
                } else {
                    panel.addMessage("* Uknown command.");
                }
            } catch (const std::out_of_range & ex){
            }
        } else if (ircClient != NULL){
            if (command.at(0) == "help"){
                panel.addMessage("* commands: help, nick, whisper, ping, join, quit");
            } else if (command.at(0) == "nick"){
                try {
                    const std::string & nick = command.at(1);
                    if (!nick.empty()){
                        ircClient->setName(nick);
                        panel.setClient(nick);
                        panel.addMessage("* nick changed to " + nick);
                    }
                } catch (const std::out_of_range & ex){
                    panel.addMessage("* /nick [name]");
                }
            } else if (command.at(0) == "whisper"){
                try {
                    const std::string & who = command.at(1);
                    const std::string & message = join(command, 2);
                    if (!who.empty() && !message.empty()){
                        ircClient->sendCommand(::Network::IRC::Command::PrivateMessage, who, ":" + message);
                        panel.addMessage("-> " + who + " " + message);
                    }
                } catch (const std::out_of_range & ex){
                    panel.addMessage("* /whisper [nick] [message]");
                }
            } else if (command.at(0) == "ping"){
                try {
                    const std::string & who = command.at(1);
                    if (!who.empty()){
                        std::ostringstream timestamp;
                        timestamp << System::currentMicroseconds();
                        ircClient->sendCommand(::Network::IRC::Command::PrivateMessage, who, ":\001PING " + timestamp.str() + "\001");
                        panel.addMessage("[CTCP] Sending CTCP-PING request to " + who);
                    }
                } catch (const std::out_of_range & ex){
                    panel.addMessage("* /ping [nick]");
                }
            } else if (command.at(0) == "join"){
                try {
                    const std::string & channel = command.at(1);
                    if (!channel.empty()){
                        ircClient->joinChannel(channel);
                    }
                } catch (const std::out_of_range & ex){
                    panel.addMessage("* /join [channel]");
                }
            } else if (command.at(0) == "quit"){
                const std::string & message = join(command, 1);
                if (!message.empty()){
                    ircClient->sendCommand(::Network::IRC::Command::Quit, ":" + message);
                    Global::debug(0) << "Quit (" + message + "). Waiting for server to close connection..." << std::endl;
                } else {
                    ircClient->sendCommand(::Network::IRC::Command::Quit);
                    Global::debug(0) << "Quit. Waiting for server to close connection..." << std::endl;
                }
            } else {
                panel.addMessage("* Uknown command.");
            }
        }

    }

    void draw(const Graphics::Bitmap & screen){
        Graphics::StretchedBitmap stretch(320, 240, screen);
        stretch.start();
        stretch.fill(Graphics::makeColor(255,255,255));
        panel.draw(stretch);
        stretch.finish();
        screen.BlitToScreen();
    }
};

static void doServer(int port){
    InputLogicDraw server(Server, port);
    PaintownUtil::standardLoop(server, server);
}

static void doClient(const std::string & host, int port){
    InputLogicDraw client(Client, port, host);
    PaintownUtil::standardLoop(client, client);
}

static void doIrc(const std::string & host, int port){
    InputLogicDraw client(IrcClient, port, host);
    PaintownUtil::standardLoop(client, client);
}

static void arguments(const std::string & application, int status){
    std::cout << "Usage: ./" << application << " server port" << std::endl;
    std::cout << "       ./" << application << " client port [host]" << std::endl;
    std::cout << "       ./" << application << " irc port [host]" << std::endl;
    exit(status);
}

int main(int argc, char ** argv){
    if (argc > 2){
        bool server = (strcmp(argv[1],"server")==0) ? true : false;
        bool client = (strcmp(argv[1],"client")==0) ? true : false;
        bool irc = (strcmp(argv[1],"irc")==0) ? true : false;
        if (!server && !client && !irc){
            arguments(argv[0], 1);
        }
        int port = atoi(argv[2]);
        std::string hostname = "127.0.0.1";
        if ((client || irc) && argc == 4){
            hostname = argv[3];
        }
        Screen::realInit();
        atexit(Screen::realFinish);
        Common::startTimers();

        Sound::initialize();

        Global::setDebug(2);

        Graphics::Bitmap screen(*Graphics::getScreenBuffer());
        Util::Parameter<Graphics::Bitmap*> use(Graphics::screenParameter, &screen);
        Keyboard::pushRepeatState(true);

        InputManager manager;

        Network::init();

        try {
            if (server){
                doServer(port);
            } else if (client){
                doClient(hostname, port);
            } else if (irc){
                doIrc(hostname, port);
            }
        } catch (const Exception::Return & ex){
        } catch (const Network::NetworkException & ex){
            Global::debug(0) << "Network Exception: " << ex.getMessage() << std::endl;
        }
        Network::shutdown();
    } else {
        arguments(argv[0],0);
    }
    return 0;
}
#ifdef USE_ALLEGRO
END_OF_MAIN()
#endif
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2001,2002 Steven M. Cherry. All rights reserved.
 *
 * This file is a part of slib - a c++ utility library
 *
 * The slib project, including all files needed to compile
 * it, is free software; you can redistribute it and/or use it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  See file COPYING for details.
 */

/* ******************************************************* */
/* Simple program to test the functions in twine.cpp       */
/* ******************************************************* */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "twine.h"
using namespace SLib;

#include "catch.hpp"

const size_t MAX_INPUT_SIZE = 1024000000;

TEST_CASE( "Twine - short string", "[twine]" )
{
    twine t( "I am a short string" );

    REQUIRE_FALSE( t.empty() );
    REQUIRE( t.size() == 19 );
    REQUIRE( t.capacity() >= 19 );
}

// according to twine.h, a "Short string" is <=32 characters, including the final '\0'
TEST_CASE( "Twine - assignment from const char", "[twine]" )
{
    SECTION( "Short string") {
        SECTION( "Direct assignment" ){
            twine t = "I am a short string";
            REQUIRE_FALSE( t.empty() );
            REQUIRE( t.size() == 19 );
            REQUIRE( t.capacity() >= 19 );
        }

        SECTION( "Assignment after construction" ){
            twine t; t = "I am a short string";
            REQUIRE_FALSE( t.empty() );
            REQUIRE( t.size() == 19 );
            REQUIRE( t.capacity() >= 19 );
        }
    }

    SECTION( "Long string") {
        SECTION( "Direct assignment of a long string" ){
            twine t = "I am a longer string that will not fit in optimized storage.";
            REQUIRE_FALSE( t.empty() );
            REQUIRE( t.size() == 60 );
            REQUIRE( t.capacity() >= 60 );
        }

        SECTION( "Assignment after construction of a long string" ){
            twine t; t = "I am a longer string that will not fit in optimized storage.";
            REQUIRE_FALSE( t.empty() );
            REQUIRE( t.size() == 60 );
            REQUIRE( t.capacity() >= 60 );
        }
    }

    SECTION("Extremely long string") {
        SECTION("MAX_INPUT_SIZE") {

            // This is a valid size, because the exception is
            // thrown when number of non-zero chars in string
            // is greater than MAX_INPUT_SIZE
            char* monster = (char*)malloc((MAX_INPUT_SIZE + 1) * sizeof(*monster));
            for(int i = 0; i < MAX_INPUT_SIZE; ++i)
            {
                monster[i] = (i % 94) + 32; // fill it with printable characters! Why? Who cares!
            }
            monster[MAX_INPUT_SIZE] = 0;

            SECTION( "Direct assignment of a long string" ){
                twine* t = NULL;

                REQUIRE_NOTHROW([&](){t = new twine(monster);}());
                REQUIRE_FALSE(t->empty());
                REQUIRE(t->size() == MAX_INPUT_SIZE);
                REQUIRE(t->capacity() >= MAX_INPUT_SIZE);
                INFO("t.capacity() is " << t->capacity());
                INFO("MAX_INPUT_SIZE is " << MAX_INPUT_SIZE);

                if(t != NULL)
                    delete t;
            }

            SECTION( "Assignment after construction of a long string" ){
                twine t;
                REQUIRE_NOTHROW(t = monster);

                REQUIRE_FALSE(t.empty());
                REQUIRE(t.size() == MAX_INPUT_SIZE);
                REQUIRE(t.capacity() >= MAX_INPUT_SIZE);
                INFO("t.capacity() is " << t.capacity());
                INFO("MAX_INPUT_SIZE is " << MAX_INPUT_SIZE);
            }
        }

        SECTION("MAX_INPUT_SIZE + 1") {
            // This is an invalid size, because the nonzero portion of the string is of length greater
            // than MAX_INPUT_SIZE
            char* monster = (char*)malloc((MAX_INPUT_SIZE + 2) * sizeof(*monster));
            for(int i = 0; i <= MAX_INPUT_SIZE; ++i)
            {
                monster[i] = (i % 94) + 32; // fill it with printable characters! Why? Who cares!
            }
            monster[MAX_INPUT_SIZE + 1] = 0;

            SECTION( "Direct assignment of a long string" ){
                REQUIRE_THROWS([&](){twine t = monster;}());
            }

            SECTION( "Assignment after construction of a long string" ){
                twine t;
                REQUIRE_THROWS(t = monster);
            }
        }
    }

}

TEST_CASE( "Twine - Copy Constructor" )
{
    SECTION( "Copy Empty" ) {
        SECTION( "Calling constructor by name" ){
            twine orig;
            twine t = twine(orig);
            REQUIRE(t.empty());
            REQUIRE(t.size() == 0);
            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);

            REQUIRE(t.compare(orig) == 0);
            REQUIRE(&t != &orig);
        }

        SECTION("Implicitly calling constructor"){
            twine orig;
            twine t = orig;
            REQUIRE(t.empty());
            REQUIRE(t.size() == 0);
            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);

            REQUIRE(t.compare(orig) == 0);
            REQUIRE(&t != &orig);
        }

        SECTION("Calling constructor after initial creation"){
            twine orig;
            twine t; t = orig;
            REQUIRE(t.empty());
            REQUIRE(t.size() == 0);
            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);

            REQUIRE(t.compare(orig) == 0);
            REQUIRE(&t != &orig);
        }
    }

    SECTION( "Copy Short Twine" ) {
        SECTION( "Calling constructor by name" ){
            twine orig = "I am a short string";
            twine t = twine(orig);
            REQUIRE_FALSE(t.empty());
            REQUIRE(t.size() == 19);
            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);

            REQUIRE(t.compare(orig) == 0);
            REQUIRE(&t != &orig);
        }

        SECTION("Implicitly calling constructor"){
            twine orig = "I am a short string";
            twine t = orig;
            REQUIRE_FALSE(t.empty());
            REQUIRE(t.size() == 19);
            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);

            REQUIRE(t.compare(orig) == 0);
            REQUIRE(&t != &orig);
        }

        SECTION("Calling constructor after initial creation"){
            twine orig = "I am a short string";
            twine t; t = orig;
            REQUIRE_FALSE(t.empty());
            REQUIRE(t.size() == 19);
            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);

            REQUIRE(t.compare(orig) == 0);
            REQUIRE(&t != &orig);
        }
    }

    SECTION("Copy Long Twine") {
        twine orig = "";
    }
}
<commit_msg>Added copy long string and a randomized test<commit_after>/*
 * Copyright (c) 2001,2002 Steven M. Cherry. All rights reserved.
 *
 * This file is a part of slib - a c++ utility library
 *
 * The slib project, including all files needed to compile
 * it, is free software; you can redistribute it and/or use it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  See file COPYING for details.
 */

/* ******************************************************* */
/* Simple program to test the functions in twine.cpp       */
/* ******************************************************* */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "twine.h"
using namespace SLib;

#include "catch.hpp"

const size_t MAX_INPUT_SIZE = 1024000000;

TEST_CASE( "Twine - short string", "[twine]" )
{
    twine t( "I am a short string" );

    REQUIRE_FALSE( t.empty() );
    REQUIRE( t.size() == 19 );
    REQUIRE( t.capacity() >= 19 );
}

// according to twine.h, a "Short string" is <=32 characters, including the final '\0'
TEST_CASE( "Twine - assignment from const char", "[twine]" )
{
    SECTION( "Short string") {
        SECTION( "Direct assignment" ){
            twine t = "I am a short string";
            REQUIRE_FALSE( t.empty() );
            REQUIRE( t.size() == 19 );
            REQUIRE( t.capacity() >= 19 );
        }

        SECTION( "Assignment after construction" ){
            twine t; t = "I am a short string";
            REQUIRE_FALSE( t.empty() );
            REQUIRE( t.size() == 19 );
            REQUIRE( t.capacity() >= 19 );
        }
    }

    SECTION( "Long string") {
        SECTION( "Direct assignment of a long string" ){
            twine t = "I am a longer string that will not fit in optimized storage.";
            REQUIRE_FALSE( t.empty() );
            REQUIRE( t.size() == 60 );
            REQUIRE( t.capacity() >= 60 );
        }

        SECTION( "Assignment after construction of a long string" ){
            twine t; t = "I am a longer string that will not fit in optimized storage.";
            REQUIRE_FALSE( t.empty() );
            REQUIRE( t.size() == 60 );
            REQUIRE( t.capacity() >= 60 );
        }
    }

    SECTION("Extremely long string") {
        SECTION("MAX_INPUT_SIZE") {

            // This is a valid size, because the exception is
            // thrown when number of non-zero chars in string
            // is greater than MAX_INPUT_SIZE
            char* monster = (char*)malloc((MAX_INPUT_SIZE + 1) * sizeof(*monster));
            for(int i = 0; i < MAX_INPUT_SIZE; ++i)
            {
                monster[i] = (i % 94) + 32; // fill it with printable characters! Why? Who cares!
            }
            monster[MAX_INPUT_SIZE] = 0;

            SECTION( "Direct assignment of a long string" ){
                twine* t = NULL;

                REQUIRE_NOTHROW([&](){t = new twine(monster);}());
                REQUIRE_FALSE(t->empty());
                REQUIRE(t->size() == MAX_INPUT_SIZE);
                REQUIRE(t->capacity() >= MAX_INPUT_SIZE);
                INFO("t.capacity() is " << t->capacity());
                INFO("MAX_INPUT_SIZE is " << MAX_INPUT_SIZE);

                if(t != NULL)
                    delete t;
            }

            SECTION( "Assignment after construction of a long string" ){
                twine t;
                REQUIRE_NOTHROW(t = monster);

                REQUIRE_FALSE(t.empty());
                REQUIRE(t.size() == MAX_INPUT_SIZE);
                REQUIRE(t.capacity() >= MAX_INPUT_SIZE);
                INFO("t.capacity() is " << t.capacity());
                INFO("MAX_INPUT_SIZE is " << MAX_INPUT_SIZE);
            }

            free(monster);
        }

        SECTION("MAX_INPUT_SIZE + 1") {
            // This is an invalid size, because the nonzero portion of the string is of length greater
            // than MAX_INPUT_SIZE
            char* monster = (char*)malloc((MAX_INPUT_SIZE + 2) * sizeof(*monster));
            for(int i = 0; i <= MAX_INPUT_SIZE; ++i)
            {
                monster[i] = (i % 94) + 32; // fill it with printable characters! Why? Who cares!
            }
            monster[MAX_INPUT_SIZE + 1] = 0;

            SECTION( "Direct assignment of a long string" ){
                REQUIRE_THROWS([&](){twine t = monster;}());
            }

            SECTION( "Assignment after construction of a long string" ){
                twine t;
                REQUIRE_THROWS(t = monster);
            }

            free(monster);
        }
    }

    SECTION("Randomized String")
    {
        srand(time(0));

        int length = rand();
        char* randStr = (char*)malloc((length + 1) * sizeof(*randStr));
        for(int i = 0; i < length; ++i)
        {
            randStr[i] = (rand() % (CHAR_MAX - CHAR_MIN + 1)) + CHAR_MIN;
        }
        randStr[length] = 0; // make sure we have at least one null char in the string

        SECTION("Intentionally failed to test teardown")
        {
            REQUIRE(false);
        }

        free(randStr);
    }

}

TEST_CASE( "Twine - Copy Constructor" )
{
    SECTION( "Copy Empty" ) {
        SECTION( "Calling constructor by name" ){
            twine orig;
            twine t = twine(orig);
            REQUIRE(t.empty());
            REQUIRE(t.size() == 0);
            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);

            REQUIRE(t.compare(orig) == 0);
            REQUIRE(&t != &orig);
        }

        SECTION("Implicitly calling constructor"){
            twine orig;
            twine t = orig;
            REQUIRE(t.empty());
            REQUIRE(t.size() == 0);
            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);

            REQUIRE(t.compare(orig) == 0);
            REQUIRE(&t != &orig);
        }

        SECTION("Calling constructor after initial creation"){
            twine orig;
            twine t; t = orig;
            REQUIRE(t.empty());
            REQUIRE(t.size() == 0);
            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);

            REQUIRE(t.compare(orig) == 0);
            REQUIRE(&t != &orig);
        }
    }

    SECTION( "Copy Short Twine" ) {
        twine orig = "I am a short string";

        SECTION( "Calling constructor by name" ){
            twine t = twine(orig);
            REQUIRE_FALSE(t.empty());
            REQUIRE(t.size() == 19);
            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);

            REQUIRE(t.compare(orig) == 0);
            REQUIRE(&t != &orig);
        }

        SECTION("Implicitly calling constructor"){
            twine t = orig;
            REQUIRE_FALSE(t.empty());
            REQUIRE(t.size() == 19);
            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);

            REQUIRE(t.compare(orig) == 0);
            REQUIRE(&t != &orig);
        }

        SECTION("Calling constructor after initial creation"){
            twine t; t = orig;
            REQUIRE_FALSE(t.empty());
            REQUIRE(t.size() == 19);
            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);

            REQUIRE(t.compare(orig) == 0);
            REQUIRE(&t != &orig);
        }
    }

    SECTION("Copy Long Twine") {
        twine orig = "I am a longer string that will not fit in optimized storage.";

        SECTION( "Calling constructor by name" ){
            twine t = twine(orig);
            REQUIRE_FALSE(t.empty());
            REQUIRE(t.size() == 60);
            REQUIRE(t.capacity() >= 60);

            REQUIRE(t.compare(orig) == 0);
            REQUIRE(&t != &orig);
        }

        SECTION("Implicitly calling constructor"){
            twine t = orig;
            REQUIRE_FALSE(t.empty());
            REQUIRE(t.size() == 60);
            REQUIRE(t.capacity() >= 60);

            REQUIRE(t.compare(orig) == 0);
            REQUIRE(&t != &orig);
        }

        SECTION("Calling constructor after initial creation"){
            twine t; t = orig;
            REQUIRE_FALSE(t.empty());
            REQUIRE(t.size() == 60);
            REQUIRE(t.capacity() >= 60);

            REQUIRE(t.compare(orig) == 0);
            REQUIRE(&t != &orig);
        }
    }
}
<|endoftext|>


<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2003 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vrj/vrjConfig.h>
#include <string>

#include <gmtl/Matrix.h>
#include <gmtl/MatrixOps.h>
#include <gmtl/Xforms.h>
#include <gmtl/Output.h>

#include <vrj/Display/Projection.h>

namespace vrj
{

float Projection::mNearDist = 0.1f;
float Projection::mFarDist = 10000.0f;

/**
 * Helper to the frustum apex and corners in model coordinates.
 * @note The normal frustum is in camera (clip) coordinates
 *       and the model is in model (eye) coordinates.
 *       The matrix viewMat transforms from eye to clip.
 */
void Projection::getFrustumApexAndCorners(gmtl::Vec3f& apex,
                                          gmtl::Vec3f& ur, gmtl::Vec3f& lr,
                                          gmtl::Vec3f& ul, gmtl::Vec3f& ll)
{
   gmtl::Matrix44f view_mat_inv;
   gmtl::invert(view_mat_inv, mViewMat);

   // vprDEBUG(vprDBG_ALL,0) << "GetApex:\nview mat:\n" << mViewMat << "\nviewMatInv:\n" << view_mat_inv << std::endl << vprDEBUG_FLUSH;

   //float near_dist = mFocusPlaneDist;
   // User like triangles to get the params for the focus surface
   float mult_factor = mFocusPlaneDist/mFrustum[Frustum::VJ_NEAR];
   float bot = mFrustum[Frustum::VJ_BOTTOM]*mult_factor;
   float left = mFrustum[Frustum::VJ_LEFT]*mult_factor;
   float top = mFrustum[Frustum::VJ_TOP]*mult_factor;
   float right = mFrustum[Frustum::VJ_RIGHT]*mult_factor;

   // Create points in clip space
   gmtl::Point3f apexClip(0.0f, 0.0f, 0.0f);
   gmtl::Point3f urClip(right, top, -mFocusPlaneDist);
   gmtl::Point3f lrClip(right, bot, -mFocusPlaneDist);
   gmtl::Point3f ulClip(left, top, -mFocusPlaneDist);
   gmtl::Point3f llClip(left, bot, -mFocusPlaneDist);

   apex = view_mat_inv * apexClip;
   ur = view_mat_inv * urClip;
   lr = view_mat_inv * lrClip;
   ul = view_mat_inv * ulClip;
   ll = view_mat_inv * llClip;
}

std::ostream& Projection::outStream(std::ostream& out,
                                    const unsigned int indentLevel)
{
   const int pad_width_dot(20 - indentLevel);
   out.setf(std::ios::left);

   const std::string indent_text(indentLevel, ' ');

   out << indent_text << std::setw(pad_width_dot) << "Eye " << " ";

   switch(mEye)
   {
   case Projection::LEFT:
      out << "Left";
      break;
   case Projection::RIGHT:
      out << "Right";
      break;
   }
   out << std::endl;
   out << indent_text << std::setw(pad_width_dot)
       << "Frustum " << " " << mFrustum;
   return out;
}

void Projection::setNearFar(float near_val, float far_val)
{
   vprDEBUG(vprDBG_ALL,vprDBG_STATE_LVL) << clrOutNORM(clrCYAN,"vjProjection::setNearFar:")
                           << "near: " << near_val << " far:" << far_val
                           << std::endl << vprDEBUG_FLUSH;
   mNearDist = near_val;
   mFarDist = far_val;
}

VJ_IMPLEMENT(std::ostream&) operator<<(std::ostream& out, Projection& proj)
{
   return proj.outStream(out);
}

};
<commit_msg>Fix spelling<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2003 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vrj/vrjConfig.h>
#include <string>

#include <gmtl/Matrix.h>
#include <gmtl/MatrixOps.h>
#include <gmtl/Xforms.h>
#include <gmtl/Output.h>

#include <vrj/Display/Projection.h>

namespace vrj
{

float Projection::mNearDist = 0.1f;
float Projection::mFarDist = 10000.0f;

/**
 * Helper to the frustum apex and corners in model coordinates.
 * @note The normal frustum is in camera (clip) coordinates
 *       and the model is in model (eye) coordinates.
 *       The matrix viewMat transforms from eye to clip.
 */
void Projection::getFrustumApexAndCorners(gmtl::Vec3f& apex,
                                          gmtl::Vec3f& ur, gmtl::Vec3f& lr,
                                          gmtl::Vec3f& ul, gmtl::Vec3f& ll)
{
   gmtl::Matrix44f view_mat_inv;
   gmtl::invert(view_mat_inv, mViewMat);

   // vprDEBUG(vprDBG_ALL,0) << "GetApex:\nview mat:\n" << mViewMat << "\nviewMatInv:\n" << view_mat_inv << std::endl << vprDEBUG_FLUSH;

   //float near_dist = mFocusPlaneDist;
   // Use like triangles to get the params for the focus surface
   float mult_factor = mFocusPlaneDist/mFrustum[Frustum::VJ_NEAR];
   float bot = mFrustum[Frustum::VJ_BOTTOM]*mult_factor;
   float left = mFrustum[Frustum::VJ_LEFT]*mult_factor;
   float top = mFrustum[Frustum::VJ_TOP]*mult_factor;
   float right = mFrustum[Frustum::VJ_RIGHT]*mult_factor;

   // Create points in clip space
   gmtl::Point3f apexClip(0.0f, 0.0f, 0.0f);
   gmtl::Point3f urClip(right, top, -mFocusPlaneDist);
   gmtl::Point3f lrClip(right, bot, -mFocusPlaneDist);
   gmtl::Point3f ulClip(left, top, -mFocusPlaneDist);
   gmtl::Point3f llClip(left, bot, -mFocusPlaneDist);

   apex = view_mat_inv * apexClip;
   ur = view_mat_inv * urClip;
   lr = view_mat_inv * lrClip;
   ul = view_mat_inv * ulClip;
   ll = view_mat_inv * llClip;
}

std::ostream& Projection::outStream(std::ostream& out,
                                    const unsigned int indentLevel)
{
   const int pad_width_dot(20 - indentLevel);
   out.setf(std::ios::left);

   const std::string indent_text(indentLevel, ' ');

   out << indent_text << std::setw(pad_width_dot) << "Eye " << " ";

   switch(mEye)
   {
   case Projection::LEFT:
      out << "Left";
      break;
   case Projection::RIGHT:
      out << "Right";
      break;
   }
   out << std::endl;
   out << indent_text << std::setw(pad_width_dot)
       << "Frustum " << " " << mFrustum;
   return out;
}

void Projection::setNearFar(float near_val, float far_val)
{
   vprDEBUG(vprDBG_ALL,vprDBG_STATE_LVL) << clrOutNORM(clrCYAN,"vjProjection::setNearFar:")
                           << "near: " << near_val << " far:" << far_val
                           << std::endl << vprDEBUG_FLUSH;
   mNearDist = near_val;
   mFarDist = far_val;
}

VJ_IMPLEMENT(std::ostream&) operator<<(std::ostream& out, Projection& proj)
{
   return proj.outStream(out);
}

};
<|endoftext|>


<commit_before>/* testlibsrsircpp.cpp - (C) 2014, Emir Marincic
 * libsrsircpp - C++ wrapper for libsrsirc
 * See README for contact-, COPYING for license information. */

#include <iostream>
#include <cstdlib>

#include <libsrsircpp/irc_oo.h>

int
main(int argc, char **argv)
{
	IRC handle;
	handle.Nick("Testircpp");
	handle.Uname("Testircpp");
	handle.ConFlags(0);
	handle.RegisterCallbackConRead(ConRead, 0);
	handle.Server("irc.quakenet.org", "6667");
	if(!handle.Connect(10*1000000UL)){
		cout<<"Failed to connect"<<endl;
		return -1;
	}
	if(!handle.Write("JOIN #Lea2")){
		cout<<"Couldn't join"<<endl;
		return -1;
	}
	if(!handle.Write("PRIVMSG #Lea2 :Teeeest")){
		cout<<"Couldn't Write"<<endl;
		return -1;
	}
	return EXIT_SUCCESS;
}
<commit_msg>Sloppier then expected. Namespace and Callback<commit_after>/* testlibsrsircpp.cpp - (C) 2014, Emir Marincic
 * libsrsircpp - C++ wrapper for libsrsirc
 * See README for contact-, COPYING for license information. */

#include <iostream>
#include <cstdlib>

#include <libsrsircpp/irc_oo.h>

using namespace std;

int
main(int argc, char **argv)
{
	IRC handle;
	handle.Nick("Testircpp");
	handle.Uname("Testircpp");
	handle.ConFlags(0);
	handle.Server("irc.quakenet.org", "6667");
	if(!handle.Connect(10*1000000UL)){
		cout<<"Failed to connect"<<endl;
		return -1;
	}
	if(!handle.Write("JOIN #Lea2")){
		cout<<"Couldn't join"<<endl;
		return -1;
	}
	if(!handle.Write("PRIVMSG #Lea2 :Teeeest")){
		cout<<"Couldn't Write"<<endl;
		return -1;
	}
	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "v3dViewTensorInteractor.h"

#include <dtkCore/dtkAbstractData.h>
#include <dtkCore/dtkAbstractDataFactory.h>
#include <dtkCore/dtkAbstractView.h>
#include <dtkCore/dtkAbstractViewFactory.h>

#include <vtkTensorManager.h>
#include <vtkStructuredPoints.h>

#include "v3dView.h"

#include <itkITKTensorsToVTKTensorsFilter.h>
#include <itkImage.h>
#include <itkTensor.h>

typedef itk::Tensor<float, 3>    TensorTypeFloat;
typedef itk::Image<TensorTypeFloat, 3> TensorImageTypeFloat;
typedef TensorImageTypeFloat::Pointer TensorImagePointerFloat;

typedef itk::Tensor<double, 3>    TensorTypeDouble;
typedef itk::Image<TensorTypeDouble, 3> TensorImageTypeDouble;
typedef TensorImageTypeDouble::Pointer TensorImagePointerDouble;

class v3dViewTensorInteractorPrivate
{
public:
    dtkAbstractData        *data;
    v3dView                *view;
    vtkTensorManager       *manager;

    // the filters will convert from itk tensor image format to vtkStructuredPoint (format handled by the tensor manager)
    itk::ITKTensorsToVTKTensorsFilter<TensorImageTypeFloat>::Pointer filterFloat;
    TensorImagePointerFloat      datasetFloat;

    itk::ITKTensorsToVTKTensorsFilter<TensorImageTypeDouble>::Pointer filterDouble;
    TensorImagePointerDouble      datasetDouble;
};

v3dViewTensorInteractor::v3dViewTensorInteractor(): dtkAbstractViewInteractor(), d(new v3dViewTensorInteractorPrivate)
{
    d->data    = 0;
    d->view    = 0;
    d->manager = vtkTensorManager::New();

    d->datasetFloat = 0;
    d->filterFloat = 0;

    d->datasetDouble = 0;
    d->filterDouble = 0;

    this->addProperty("GlyphShape", QStringList() << "Lines" << "Disks" << "Arrows" << "Cubes" << "Cylinders" << "Ellipsoids" << "Superquadrics");
    this->addProperty("FlipX", QStringList() << "true" << "false");
    this->addProperty("FlipY", QStringList() << "true" << "false");
    this->addProperty("FlipZ", QStringList() << "true" << "false");

    // set default properties
    d->manager->SetGlyphShapeToLine();
    this->setProperty("GlyphShape", "Lines");
}

v3dViewTensorInteractor::~v3dViewTensorInteractor()
{
    this->disable();
    d->manager->Delete();

    delete d;
    d = 0;
}

QString v3dViewTensorInteractor::description(void) const
{
    return "v3dViewTensorInteractor";
}

QStringList v3dViewTensorInteractor::handled(void) const
{
    return QStringList () << "v3dView";
}

bool v3dViewTensorInteractor::registered(void)
{
    return dtkAbstractViewFactory::instance()->registerViewInteractorType("v3dViewTensorInteractor", QStringList() << "v3dView", createV3dViewTensorInteractor);
}

void v3dViewTensorInteractor::setData(dtkAbstractData *data)
{
    if (!data)
        return;

    QString description = data->description();

    // up to the moment 2 itk tensor image formats are supported
    // we need to convert them to vtkStructuredPoints so it's understood by the tensor manager
    if (description.compare("itkDataTensorImageFloat3") == 0) {
        if (TensorImageTypeFloat *dataset = static_cast<TensorImageTypeFloat *>(data->data())) {

            d->datasetFloat = dataset;

            d->filterFloat = itk::ITKTensorsToVTKTensorsFilter<TensorImageTypeFloat>::New();

            d->filterFloat->SetInput(dataset);

            // this line generates the vtkTensors, otherwise is not generated, even if the next filter
            // in the pipeline is connected and Update() is called
            d->filterFloat->Update();

            // we need to call this function because GetOutput() just returns the input
            vtkStructuredPoints* tensors = d->filterFloat->GetVTKTensors();

            d->manager->SetInput(tensors);

            // TODO this should not be here once the toolbox is coded
            d->manager->ResetPosition();

            d->manager->Update();

            d->data = data;
        }
    } else if (description.compare("itkDataTensorImageDouble3") == 0) {
        if (TensorImageTypeDouble *dataset = static_cast<TensorImageTypeDouble *>(data->data())) {

            d->datasetDouble = dataset;

            d->filterDouble = itk::ITKTensorsToVTKTensorsFilter<TensorImageTypeDouble>::New();

            d->filterDouble->SetInput(dataset);

            // this line generates the vtkTensors, otherwise is not generated, even if the next filter
            // in the pipeline is connected and Update() is called
            d->filterDouble->Update();

            // we need to call this function because GetOutput() just returns the input
            vtkStructuredPoints* tensors = d->filterDouble->GetVTKTensors();

            d->manager->SetInput(tensors);

            // TODO this should not be here once the toolbox is coded
            d->manager->ResetPosition();

            d->manager->Update();

            d->data = data;
        }
    } else {
        qDebug() << "Unrecognized tensor data type: " << description;
    }
}

dtkAbstractData *v3dViewTensorInteractor::data (void)
{
    return d->data;
}

void v3dViewTensorInteractor::setView(dtkAbstractView *view)
{
    if (v3dView *v3dview = dynamic_cast<v3dView*>(view) ) {
        d->view = v3dview;
        // be careful not to forget setting the same renderer for the interactor and the view
        // otherwise a new renderer is created
        d->manager->SetRenderWindowInteractor( d->view->interactor(), d->view->renderer3d() );
    }
}

dtkAbstractView *v3dViewTensorInteractor::view (void)
{
    return d->view;
}

void v3dViewTensorInteractor::enable(void)
{
    if (this->enabled())
        return;

    dtkAbstractViewInteractor::enable();
}

void v3dViewTensorInteractor::disable(void)
{
    if (!this->enabled())
        return;

    dtkAbstractViewInteractor::disable();
}

void v3dViewTensorInteractor::onPropertySet(const QString& key, const QString& value)
{
    if (key=="GlyphShape")
    {
        this->onGlyphShapePropertySet (value);
    }
    else if (key=="FlipX")
    {
        this->onFlipXPropertySet (value);
    }
    else if (key=="FlipY")
    {
        this->onFlipYPropertySet (value);
    }
    else if (key=="FlipZ")
    {
        this->onFlipZPropertySet (value);
    }
}

void v3dViewTensorInteractor::onGlyphShapePropertySet (const QString& value)
{
    if (value == "Lines")
    {
        d->manager->SetGlyphShapeToLine();
    }
    else if (value == "Disks")
    {
        d->manager->SetGlyphShapeToDisk();
    }
    else if (value == "Arrows")
    {
        d->manager->SetGlyphShapeToArrow();
    }
    else if (value == "Cubes")
    {
        d->manager->SetGlyphShapeToCube();
    }
    else if (value == "Cylinders")
    {
        d->manager->SetGlyphShapeToCylinder();
    }
    else if (value == "Ellipsoids")
    {
        d->manager->SetGlyphShapeToSphere();
    }
    else if (value == "Superquadrics")
    {
        d->manager->SetGlyphShapeToSuperquadric();
    }
}

void v3dViewTensorInteractor::onSampleRatePropertySet (int sampleRate)
{
    d->manager->SetSampleRate(sampleRate, sampleRate, sampleRate);

    // TODO we need to move this after extending dtk for supporting int properties
    // as now the update of the view is being done in 2 different places (here and in the configuration)
    if (d->view)
        d->view->update();
}

void v3dViewTensorInteractor::onEigenVectorPropertySet (int eigenVector)
{
    // we need to substract 1 because the manager receives an index
    d->manager->SetColorModeToEigenvector(eigenVector-1);

    // TODO we need to move this after extending dtk for supporting int properties
    // as now the update of the view is being done in 2 different places (here and in the configuration)
    if (d->view)
        d->view->update();
}

void v3dViewTensorInteractor::onGlyphResolutionPropertySet (int glyphResolution)
{
    d->manager->SetGlyphResolution(glyphResolution);

    // TODO we need to move this after extending dtk for supporting int properties
    // as now the update of the view is being done in 2 different places (here and in the configuration)
    if (d->view)
        d->view->update();
}

void v3dViewTensorInteractor::onReverseBackgroundColorPropertySet (bool isWhite)
{
    if (!d->view)
        return;

    if(isWhite)
        d->view->setBackgroundColor(1.0,1.0,1.0);
    else
        d->view->setBackgroundColor(0.0,0.0,0.0);

    // TODO we need to move this after extending dtk for supporting int properties
    // as now the update of the view is being done in 2 different places (here and in the configuration)
    if (d->view)
        d->view->update();
}

void v3dViewTensorInteractor::onScalingPropertySet (double scale)
{
    d->manager->SetGlyphScale((float)scale);

    // TODO we need to move this after extending dtk for supporting int properties
    // as now the update of the view is being done in 2 different places (here and in the configuration)
    if (d->view)
        d->view->update();
}

void v3dViewTensorInteractor::onHideShowAxialPropertySet(bool show)
{
    if(show)
        d->manager->SetAxialSliceVisibility(1);
    else
        d->manager->SetAxialSliceVisibility(0);

    // TODO we need to move this after extending dtk for supporting int properties
    // as now the update of the view is being done in 2 different places (here and in the configuration)
    if (d->view)
        d->view->update();
}

void v3dViewTensorInteractor::onHideShowCoronalPropertySet(bool show)
{
    if(show)
        d->manager->SetCoronalSliceVisibility(1);
    else
        d->manager->SetCoronalSliceVisibility(0);

    // TODO we need to move this after extending dtk for supporting int properties
    // as now the update of the view is being done in 2 different places (here and in the configuration)
    if (d->view)
        d->view->update();
}

void v3dViewTensorInteractor::onHideShowSagittalPropertySet(bool show)
{
    if(show)
        d->manager->SetSagittalSliceVisibility(1);
    else
        d->manager->SetSagittalSliceVisibility(0);

    // TODO we need to move this after extending dtk for supporting int properties
    // as now the update of the view is being done in 2 different places (here and in the configuration)
    if (d->view)
        d->view->update();
}

void v3dViewTensorInteractor::onFlipXPropertySet (const QString& flipX)
{
    if (flipX == "true")
        d->manager->FlipX(true);
    else
        d->manager->FlipX(false);
}

void v3dViewTensorInteractor::onFlipYPropertySet (const QString& flipY)
{
    if (flipY == "true")
        d->manager->FlipY(true);
    else
        d->manager->FlipY(false);
}

void v3dViewTensorInteractor::onFlipZPropertySet (const QString& flipZ)
{
    if (flipZ == "true")
        d->manager->FlipZ(true);
    else
        d->manager->FlipZ(false);
}

void v3dViewTensorInteractor::onPositionChanged(const QVector3D& position)
{
    d->manager->SetCurrentPosition(position.x(), position.y(), position.z());
}

// /////////////////////////////////////////////////////////////////
// Type instantiation
// /////////////////////////////////////////////////////////////////

dtkAbstractViewInteractor *createV3dViewTensorInteractor(void)
{
    return new v3dViewTensorInteractor;
}
<commit_msg>Moved view->update() from the tensor interactor to the configuration.<commit_after>#include "v3dViewTensorInteractor.h"

#include <dtkCore/dtkAbstractData.h>
#include <dtkCore/dtkAbstractDataFactory.h>
#include <dtkCore/dtkAbstractView.h>
#include <dtkCore/dtkAbstractViewFactory.h>

#include <vtkTensorManager.h>
#include <vtkStructuredPoints.h>

#include "v3dView.h"

#include <itkITKTensorsToVTKTensorsFilter.h>
#include <itkImage.h>
#include <itkTensor.h>

typedef itk::Tensor<float, 3>    TensorTypeFloat;
typedef itk::Image<TensorTypeFloat, 3> TensorImageTypeFloat;
typedef TensorImageTypeFloat::Pointer TensorImagePointerFloat;

typedef itk::Tensor<double, 3>    TensorTypeDouble;
typedef itk::Image<TensorTypeDouble, 3> TensorImageTypeDouble;
typedef TensorImageTypeDouble::Pointer TensorImagePointerDouble;

class v3dViewTensorInteractorPrivate
{
public:
    dtkAbstractData        *data;
    v3dView                *view;
    vtkTensorManager       *manager;

    // the filters will convert from itk tensor image format to vtkStructuredPoint (format handled by the tensor manager)
    itk::ITKTensorsToVTKTensorsFilter<TensorImageTypeFloat>::Pointer filterFloat;
    TensorImagePointerFloat      datasetFloat;

    itk::ITKTensorsToVTKTensorsFilter<TensorImageTypeDouble>::Pointer filterDouble;
    TensorImagePointerDouble      datasetDouble;
};

v3dViewTensorInteractor::v3dViewTensorInteractor(): dtkAbstractViewInteractor(), d(new v3dViewTensorInteractorPrivate)
{
    d->data    = 0;
    d->view    = 0;
    d->manager = vtkTensorManager::New();

    d->datasetFloat = 0;
    d->filterFloat = 0;

    d->datasetDouble = 0;
    d->filterDouble = 0;

    this->addProperty("GlyphShape", QStringList() << "Lines" << "Disks" << "Arrows" << "Cubes" << "Cylinders" << "Ellipsoids" << "Superquadrics");
    this->addProperty("FlipX", QStringList() << "true" << "false");
    this->addProperty("FlipY", QStringList() << "true" << "false");
    this->addProperty("FlipZ", QStringList() << "true" << "false");

    // set default properties
    d->manager->SetGlyphShapeToLine();
    this->setProperty("GlyphShape", "Lines");
}

v3dViewTensorInteractor::~v3dViewTensorInteractor()
{
    this->disable();
    d->manager->Delete();

    delete d;
    d = 0;
}

QString v3dViewTensorInteractor::description(void) const
{
    return "v3dViewTensorInteractor";
}

QStringList v3dViewTensorInteractor::handled(void) const
{
    return QStringList () << "v3dView";
}

bool v3dViewTensorInteractor::registered(void)
{
    return dtkAbstractViewFactory::instance()->registerViewInteractorType("v3dViewTensorInteractor", QStringList() << "v3dView", createV3dViewTensorInteractor);
}

void v3dViewTensorInteractor::setData(dtkAbstractData *data)
{
    if (!data)
        return;

    QString description = data->description();

    // up to the moment 2 itk tensor image formats are supported
    // we need to convert them to vtkStructuredPoints so it's understood by the tensor manager
    if (description.compare("itkDataTensorImageFloat3") == 0) {
        if (TensorImageTypeFloat *dataset = static_cast<TensorImageTypeFloat *>(data->data())) {

            d->datasetFloat = dataset;

            d->filterFloat = itk::ITKTensorsToVTKTensorsFilter<TensorImageTypeFloat>::New();

            d->filterFloat->SetInput(dataset);

            // this line generates the vtkTensors, otherwise is not generated, even if the next filter
            // in the pipeline is connected and Update() is called
            d->filterFloat->Update();

            // we need to call this function because GetOutput() just returns the input
            vtkStructuredPoints* tensors = d->filterFloat->GetVTKTensors();

            d->manager->SetInput(tensors);

            // TODO this should not be here once the toolbox is coded
            d->manager->ResetPosition();

            d->manager->Update();

            d->data = data;
        }
    } else if (description.compare("itkDataTensorImageDouble3") == 0) {
        if (TensorImageTypeDouble *dataset = static_cast<TensorImageTypeDouble *>(data->data())) {

            d->datasetDouble = dataset;

            d->filterDouble = itk::ITKTensorsToVTKTensorsFilter<TensorImageTypeDouble>::New();

            d->filterDouble->SetInput(dataset);

            // this line generates the vtkTensors, otherwise is not generated, even if the next filter
            // in the pipeline is connected and Update() is called
            d->filterDouble->Update();

            // we need to call this function because GetOutput() just returns the input
            vtkStructuredPoints* tensors = d->filterDouble->GetVTKTensors();

            d->manager->SetInput(tensors);

            // TODO this should not be here once the toolbox is coded
            d->manager->ResetPosition();

            d->manager->Update();

            d->data = data;
        }
    } else {
        qDebug() << "Unrecognized tensor data type: " << description;
    }
}

dtkAbstractData *v3dViewTensorInteractor::data (void)
{
    return d->data;
}

void v3dViewTensorInteractor::setView(dtkAbstractView *view)
{
    if (v3dView *v3dview = dynamic_cast<v3dView*>(view) ) {
        d->view = v3dview;
        // be careful not to forget setting the same renderer for the interactor and the view
        // otherwise a new renderer is created
        d->manager->SetRenderWindowInteractor( d->view->interactor(), d->view->renderer3d() );
    }
}

dtkAbstractView *v3dViewTensorInteractor::view (void)
{
    return d->view;
}

void v3dViewTensorInteractor::enable(void)
{
    if (this->enabled())
        return;

    dtkAbstractViewInteractor::enable();
}

void v3dViewTensorInteractor::disable(void)
{
    if (!this->enabled())
        return;

    dtkAbstractViewInteractor::disable();
}

void v3dViewTensorInteractor::onPropertySet(const QString& key, const QString& value)
{
    if (key=="GlyphShape")
    {
        this->onGlyphShapePropertySet (value);
    }
    else if (key=="FlipX")
    {
        this->onFlipXPropertySet (value);
    }
    else if (key=="FlipY")
    {
        this->onFlipYPropertySet (value);
    }
    else if (key=="FlipZ")
    {
        this->onFlipZPropertySet (value);
    }
}

void v3dViewTensorInteractor::onGlyphShapePropertySet (const QString& value)
{
    if (value == "Lines")
    {
        d->manager->SetGlyphShapeToLine();
    }
    else if (value == "Disks")
    {
        d->manager->SetGlyphShapeToDisk();
    }
    else if (value == "Arrows")
    {
        d->manager->SetGlyphShapeToArrow();
    }
    else if (value == "Cubes")
    {
        d->manager->SetGlyphShapeToCube();
    }
    else if (value == "Cylinders")
    {
        d->manager->SetGlyphShapeToCylinder();
    }
    else if (value == "Ellipsoids")
    {
        d->manager->SetGlyphShapeToSphere();
    }
    else if (value == "Superquadrics")
    {
        d->manager->SetGlyphShapeToSuperquadric();
    }
}

void v3dViewTensorInteractor::onSampleRatePropertySet (int sampleRate)
{
    d->manager->SetSampleRate(sampleRate, sampleRate, sampleRate);
}

void v3dViewTensorInteractor::onEigenVectorPropertySet (int eigenVector)
{
    // we need to substract 1 because the manager receives an index
    d->manager->SetColorModeToEigenvector(eigenVector-1);
}

void v3dViewTensorInteractor::onGlyphResolutionPropertySet (int glyphResolution)
{
    d->manager->SetGlyphResolution(glyphResolution);
}

void v3dViewTensorInteractor::onReverseBackgroundColorPropertySet (bool isWhite)
{
    if (!d->view)
        return;

    if(isWhite)
        d->view->setBackgroundColor(1.0,1.0,1.0);
    else
        d->view->setBackgroundColor(0.0,0.0,0.0);
}

void v3dViewTensorInteractor::onScalingPropertySet (double scale)
{
    d->manager->SetGlyphScale((float)scale);
}

void v3dViewTensorInteractor::onHideShowAxialPropertySet(bool show)
{
    if(show)
        d->manager->SetAxialSliceVisibility(1);
    else
        d->manager->SetAxialSliceVisibility(0);
}

void v3dViewTensorInteractor::onHideShowCoronalPropertySet(bool show)
{
    if(show)
        d->manager->SetCoronalSliceVisibility(1);
    else
        d->manager->SetCoronalSliceVisibility(0);
}

void v3dViewTensorInteractor::onHideShowSagittalPropertySet(bool show)
{
    if(show)
        d->manager->SetSagittalSliceVisibility(1);
    else
        d->manager->SetSagittalSliceVisibility(0);
}

void v3dViewTensorInteractor::onFlipXPropertySet (const QString& flipX)
{
    if (flipX == "true")
        d->manager->FlipX(true);
    else
        d->manager->FlipX(false);
}

void v3dViewTensorInteractor::onFlipYPropertySet (const QString& flipY)
{
    if (flipY == "true")
        d->manager->FlipY(true);
    else
        d->manager->FlipY(false);
}

void v3dViewTensorInteractor::onFlipZPropertySet (const QString& flipZ)
{
    if (flipZ == "true")
        d->manager->FlipZ(true);
    else
        d->manager->FlipZ(false);
}

void v3dViewTensorInteractor::onPositionChanged(const QVector3D& position)
{
    d->manager->SetCurrentPosition(position.x(), position.y(), position.z());
}

// /////////////////////////////////////////////////////////////////
// Type instantiation
// /////////////////////////////////////////////////////////////////

dtkAbstractViewInteractor *createV3dViewTensorInteractor(void)
{
    return new v3dViewTensorInteractor;
}
<|endoftext|>