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

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

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

#include <queue>
#include <map>

static std::vector<std::string> split(std::string str, char splitter){
    std::vector<std::string> strings;
    size_t next = str.find(splitter);
    while (next != std::string::npos){
        strings.push_back(str.substr(0, next));
        str = str.substr(next+1);
        next = str.find(splitter);
    }
    if (str != ""){
        strings.push_back(str);
    }

    return strings;
}

static void setTrue(void * b){
    bool * what = (bool*) b;
    *what = true;
}

static void nextTab(void * i){
    ::Network::IRC::ChatInterface * interface = (::Network::IRC::ChatInterface *)i;
    interface->nextChannel();
}

static void previousTab(void * i){
    ::Network::IRC::ChatInterface * interface = (::Network::IRC::ChatInterface *)i;
    interface->previousChannel();
}

class Game{
public:
    Game(const std::string & name, bool host = true):
    name(name),
    host(host){
    }
    ~Game(){
    }

    void addClient(const std::string & name, const std::string & ip){
        clients[name] = ip;
    }

    std::string clientsAsString(){
        std::string clientlist;
        for (std::map<std::string, std::string>::iterator i = clients.begin(); i != clients.end(); i++){
            clientlist += (*i).first + ", ";
        }
        return clientlist.substr(0, clientlist.size() - 2);
    }

    void start(const std::string & ip, const std::string & hostip) {
        // TODO move to a thread, otherwise the server is going to hang...
        int port = 9991;
        if (isHost()){
            Global::debug(0) << "Game " << name << " is starting." << std::endl;
            Global::debug(0) << "Starting server on port " << port << "...." << std::endl;
            ::Network::Chat::Server server(port);
            server.start();
            // Wait for all clients to send a message
            unsigned int allReceived = 0;
            while (allReceived < clients.size()){
                server.poll();
                while (server.hasMessages()){
                    ::Network::Chat::Message message = server.nextMessage();
                    std::map<std::string, std::string>::iterator check = clients.find(message.getName());
                    if (check != clients.end()){
                        Global::debug(0) << "Message Received: " << message.getMessage() << std::endl;
                        allReceived++;
                    }
                }
            }
            Global::debug(0) << "Received all messages. Shutting down." << std::endl;
            server.shutdown();
        } else {
            Global::debug(0) << "Game " << name << " is starting." << std::endl;
            Global::debug(0) << "Connecting to " << hostip << "...." << std::endl;
            Network::Socket socket = Network::connectReliable(hostip, port);
            Global::debug(0) << "Connected" << std::endl;
            ::Network::Chat::Client client(0, socket);
            client.start();
            ::Network::Chat::Message ourMessage(::Network::Chat::Message::Chat, ip, "Hello from: " + ip);
            client.sendMessage(ourMessage);
            Global::debug(0) << "Message sent. Shutting down." << std::endl;
            client.shutdown();
        }
    }

    std::map<std::string, std::string> & getClients(){
        return clients;
    }

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

    bool isHost() const {
        return host;
    }

private:
    std::string name;
    bool host;
    std::map<std::string, std::string> clients;
};

class InputLogicDraw: public Util::Logic, public Util::Draw, public ::Network::IRC::Message::EventInterface {
public:
    InputLogicDraw(int port, const std::string & host, const std::string & username):
    chatInterface(host, port, username),
    escaped(false){
        ircClient = Util::ReferenceCount< ::Network::IRC::Client >(new ::Network::IRC::Client(host, port));
        chatInterface.getInputBox().addHook(Keyboard::Key_ESC, setTrue, &escaped);
        chatInterface.getInputBox().addHook(Keyboard::Key_TAB, nextTab, &chatInterface);
        chatInterface.subscribe(this);
        // Get IP
        chatInterface.getClient()->sendCommand(::Network::IRC::Command::Userhost, chatInterface.getClient()->getName());
    }

    ::Network::IRC::ChatInterface chatInterface;
    Util::ReferenceCount< ::Network::IRC::Client > ircClient;

    bool escaped;

    std::string ipAddress;
    Util::ReferenceCount<Game> game;
    std::map<std::string, std::string> hosts;

    void remoteCommand(const ::Network::IRC::Command & command){
        if (command.getType() == ::Network::IRC::Command::ReplyUserhost){
            const std::vector<std::string> & params = command.getParameters();
            const std::string & extract = params.at(1);
            for (unsigned int i = 0; i < extract.size(); i++){
                if (extract[i] == '@'){
                    ipAddress = extract.substr(++i, extract.size()-1);
                    Global::debug(0) << "Your IP Address is: " << ipAddress << std::endl;
                }
            }
        }
        if (command.hasCtcp()){
            const std::vector<std::string> & ctcp = command.getCtcp();
            if (command.getType() == ::Network::IRC::Command::PrivateMessage){
                try {
                    if (ctcp.at(0) == "game"){
                        const std::string & gameCommand = ctcp.at(1);
                        if (gameCommand == "invite"){
                            const std::string & gameName = ctcp.at(2);
                            const std::string & hostName = ctcp.at(3);
                            chatInterface.addMessageToTab("* " + hostName + " has invited you to join the game [" + gameName + "]. Type \"/game join " + gameName + "\".");
                            hosts[gameName] = hostName;
                        } else if (gameCommand == "join"){
                            if (game != NULL && game->isHost()){
                                const std::string & gameName = ctcp.at(2);
                                const std::string & clientName = ctcp.at(3);
                                const std::string & ip = ctcp.at(4);
                                chatInterface.addMessageToTab("* " + clientName + " has joined " + gameName + ".");
                                game->addClient(clientName, ip);
                            } else {
                                chatInterface.addMessageToTab("* received a join request with no game pending.");
                            }
                        } else if (gameCommand == "start"){
                            if (game != NULL && !game->isHost()){
                                const std::string & gameName = ctcp.at(2);
                                const std::string & serverIp = ctcp.at(3);
                                chatInterface.addMessageToTab("* Host has started game " + gameName);
                                game->start(ipAddress, serverIp);
                            }
                        }
                    } else {
                        Global::debug(0) << "Got ctcp: " << ctcp.at(0) << std::endl;
                    }
                } catch (const std::out_of_range & ex){
                }
            }
        }
    }

    void localCommand(const std::vector<std::string> & command){
        if (command.at(0) == "help"){
            chatInterface.addMessageToTab("* commands: lol, game");
        } else if (command.at(0) == "lol"){
            chatInterface.addMessageToTab("* You LOLOLOLOLLOLOLOL yourself.");
        } else if (command.at(0) == "game"){
            // Game
            if (command.size() > 1){
                if (command.at(1) == "help"){
                    chatInterface.addMessageToTab("* game commands: help, new, start, list-users, list-hosts, invite, join.");
                } else if (command.at(1) == "new"){
                    try{
                        game = Util::ReferenceCount<Game>(new Game(command.at(2)));
                        chatInterface.addMessageToTab("* game \"" + command.at(2) + "\" created.");
                    } catch (const std::out_of_range & ex){
                        chatInterface.addMessageToTab("* /game new [name]");
                    }
                } else if (command.at(1) == "start"){
                    if (game != NULL && game->isHost()){
                        chatInterface.addMessageToTab("* Starting game " + game->getName());
                        game->start(ipAddress, ipAddress);
                        for (std::map<std::string, std::string>::iterator i = game->getClients().begin(); i != game->getClients().end(); i++){
                            chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
                                                                    (*i).first,
                                                                    ":\001game start " + game->getName() + " " + ipAddress + "\001");
                        }
                    } else {
                        chatInterface.addMessageToTab("* Create a game first...");
                    }
                } else if (command.at(1) == "list-users"){
                    if (game != NULL){
                        chatInterface.addMessageToTab("* Users who accepted game request: " + game->clientsAsString());
                    } else {
                        chatInterface.addMessageToTab("* Create a game first...");
                    }
                } else if (command.at(1) == "list-hosts"){
                    if (!hosts.empty()){
                        std::string hostlist;
                        for (std::map<std::string, std::string>::iterator i = hosts.begin(); i != hosts.end(); i++){
                            hostlist += (*i).first + +" [" + (*i).second + "], ";
                        }
                        chatInterface.addMessageToTab("* Hosts and games you've been invited to: " + hostlist.substr(0, hostlist.size() - 2));
                    } else {
                        chatInterface.addMessageToTab("* You have no invites.");
                    }
                } else if (command.at(1) == "invite"){
                    if (game != NULL){
                        try {
                            chatInterface.addMessageToTab("* Sending request to " + command.at(2));
                            chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
                                                            command.at(2),
                                                            ":\001game invite " + game->getName() + " " + chatInterface.getClient()->getName() + "\001");
                        } catch (const std::out_of_range & ex){
                            chatInterface.addMessageToTab("* /game invite [username]");
                        }
                    } else {
                        chatInterface.addMessageToTab("* Create a game first...");
                    }
                } else if (command.at(1) == "join"){
                    if (!hosts.empty()){
                        try {
                            const std::string & gameName = command.at(2);
                            const std::string & hostName = hosts[gameName];
                            chatInterface.addMessageToTab("* Joining game at " + gameName);
                            chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
                                                            hostName,
                                                            ":\001game join " + gameName + " " + chatInterface.getClient()->getName() + " " + ipAddress + "\001");
                            game = Util::ReferenceCount<Game>(new Game(gameName, false));
                        } catch (const std::out_of_range & ex){
                            chatInterface.addMessageToTab("* /game join [name]");
                        }
                    } else {
                        chatInterface.addMessageToTab("* You must be invited to a game first...");
                    }
                }
            }
        } else {
            //chatInterface.addMessageToTab("* Uknown command.");
        }
    }

    double ticks(double system){
        return system;
    }

    void run(){
        try {
            chatInterface.act();
        } catch (const Exception::Return & ex){
            escaped = true;
            throw ex;
        }
    }

    bool done(){
        return escaped;
    }

    void draw(const Graphics::Bitmap & screen){
        chatInterface.draw(screen);
    }
};

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

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

int main(int argc, char ** argv){
    if (argc >= 2){
        int port = atoi(argv[1]);
        std::string hostname = argv[2];
        std::string username = "paintown-test";
        if (argc > 3){
            username = argv[3];
        }

        Screen::realInit(Configuration::getScreenWidth(), Configuration::getScreenHeight());
        atexit(Screen::realFinish);
        Common::startTimers();

        Sound::initialize();

        Global::setDebug(2);

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

        InputManager manager;

        Util::Parameter<Util::ReferenceCount<Path::RelativePath> >
            defaultFont(Font::defaultFont, Util::ReferenceCount<Path::RelativePath>(new Path::RelativePath("fonts/arial.ttf")));

        Network::init();

        try {
            doIrc(hostname, port, username);
        } 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>[util] Add extra handling for irc commands. Make SimpleList sorted.<commit_after>#include "../common/init.h"
#include "../common/timer.h"

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

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

#include <queue>
#include <map>

static std::vector<std::string> split(std::string str, char splitter){
    std::vector<std::string> strings;
    size_t next = str.find(splitter);
    while (next != std::string::npos){
        strings.push_back(str.substr(0, next));
        str = str.substr(next+1);
        next = str.find(splitter);
    }
    if (str != ""){
        strings.push_back(str);
    }

    return strings;
}

static void setTrue(void * b){
    bool * what = (bool*) b;
    *what = true;
}

static void nextTab(void * i){
    ::Network::IRC::ChatInterface * interface = (::Network::IRC::ChatInterface *)i;
    interface->nextChannel();
}

static void previousTab(void * i){
    ::Network::IRC::ChatInterface * interface = (::Network::IRC::ChatInterface *)i;
    interface->previousChannel();
}

class Game{
public:
    Game(const std::string & name, bool host = true):
    name(name),
    host(host){
    }
    ~Game(){
    }

    void addClient(const std::string & name, const std::string & ip){
        clients[name] = ip;
    }

    std::string clientsAsString(){
        std::string clientlist;
        for (std::map<std::string, std::string>::iterator i = clients.begin(); i != clients.end(); i++){
            clientlist += (*i).first + ", ";
        }
        return clientlist.substr(0, clientlist.size() - 2);
    }

    void start(const std::string & ip, const std::string & hostip) {
        // TODO move to a thread, otherwise the server is going to hang...
        int port = 9991;
        if (isHost()){
            Global::debug(0) << "Game " << name << " is starting." << std::endl;
            Global::debug(0) << "Starting server on port " << port << "...." << std::endl;
            Util::Thread::Id id;
            Util::Thread::createThread(&id, NULL, (::Util::Thread::ThreadFunction) runServer, this);
#if 0
            ::Network::Chat::Server server(port);
            server.start();
            // Wait for all clients to send a message
            unsigned int allReceived = 0;
            while (allReceived < clients.size()){
                server.poll();
                while (server.hasMessages()){
                    ::Network::Chat::Message message = server.nextMessage();
                    std::map<std::string, std::string>::iterator check = clients.find(message.getName());
                    if (check != clients.end()){
                        Global::debug(0) << "Message Received: " << message.getMessage() << std::endl;
                        allReceived++;
                    }
                }
            }
            Global::debug(0) << "Received all messages. Shutting down." << std::endl;
            server.shutdown();
#endif
        } else {
            Global::debug(0) << "Game " << name << " is starting." << std::endl;
            Global::debug(0) << "Connecting to " << hostip << "...." << std::endl;
            Network::Socket socket = Network::connectReliable(hostip, port);
            Global::debug(0) << "Connected" << std::endl;
            ::Network::Chat::Client client(0, socket);
            client.start();
            ::Network::Chat::Message ourMessage(::Network::Chat::Message::Chat, ip, "Hello from: " + ip);
            client.sendMessage(ourMessage);
            Global::debug(0) << "Message sent. Shutting down." << std::endl;
            client.shutdown();
        }
    }

    static void runServer(void * i){
        Game * game = (Game *)i;
        ::Network::Chat::Server server(9991);
        server.start();
        // Wait for all clients to send a message
        unsigned int allReceived = 0;
        std::map<std::string, std::string> & clients = game->getClients();
        while (allReceived < clients.size()){
            server.poll();
            while (server.hasMessages()){
                ::Network::Chat::Message message = server.nextMessage();
                std::map<std::string, std::string>::iterator check = clients.find(message.getName());
                if (check != clients.end()){
                    Global::debug(0) << "Message Received: " << message.getMessage() << std::endl;
                    allReceived++;
                }
            }
        }
        Global::debug(0) << "Received all messages. Shutting down." << std::endl;
        server.shutdown();
    }

    std::map<std::string, std::string> & getClients(){
        return clients;
    }

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

    bool isHost() const {
        return host;
    }

private:
    std::string name;
    bool host;
    std::map<std::string, std::string> clients;
};

class InputLogicDraw: public Util::Logic, public Util::Draw, public ::Network::IRC::Message::EventInterface {
public:
    InputLogicDraw(int port, const std::string & host, const std::string & username):
    chatInterface(host, port, username),
    escaped(false){
        ircClient = Util::ReferenceCount< ::Network::IRC::Client >(new ::Network::IRC::Client(host, port));
        chatInterface.getInputBox().addHook(Keyboard::Key_ESC, setTrue, &escaped);
        chatInterface.getInputBox().addHook(Keyboard::Key_TAB, nextTab, &chatInterface);
        chatInterface.subscribe(this);
        // Get IP
        chatInterface.getClient()->sendCommand(::Network::IRC::Command::Userhost, chatInterface.getClient()->getName());
    }

    ::Network::IRC::ChatInterface chatInterface;
    Util::ReferenceCount< ::Network::IRC::Client > ircClient;

    bool escaped;

    std::string ipAddress;
    Util::ReferenceCount<Game> game;
    std::map<std::string, std::string> hosts;

    void remoteCommand(const ::Network::IRC::Command & command){
        if (command.getType() == ::Network::IRC::Command::ReplyUserhost){
            const std::vector<std::string> & params = command.getParameters();
            const std::string & extract = params.at(1);
            for (unsigned int i = 0; i < extract.size(); i++){
                if (extract[i] == '@'){
                    ipAddress = extract.substr(++i, extract.size()-1);
                    Global::debug(0) << "Your IP Address is: " << ipAddress << std::endl;
                }
            }
        }
        if (command.hasCtcp()){
            const std::vector<std::string> & ctcp = command.getCtcp();
            if (command.getType() == ::Network::IRC::Command::PrivateMessage){
                try {
                    if (ctcp.at(0) == "game"){
                        const std::string & gameCommand = ctcp.at(1);
                        if (gameCommand == "invite"){
                            const std::string & gameName = ctcp.at(2);
                            const std::string & hostName = ctcp.at(3);
                            chatInterface.addMessageToTab("* " + hostName + " has invited you to join the game [" + gameName + "]. Type \"/game join " + gameName + "\".");
                            hosts[gameName] = hostName;
                        } else if (gameCommand == "join"){
                            if (game != NULL && game->isHost()){
                                const std::string & gameName = ctcp.at(2);
                                const std::string & clientName = ctcp.at(3);
                                const std::string & ip = ctcp.at(4);
                                chatInterface.addMessageToTab("* " + clientName + " has joined " + gameName + ".");
                                game->addClient(clientName, ip);
                            } else {
                                chatInterface.addMessageToTab("* received a join request with no game pending.");
                            }
                        } else if (gameCommand == "start"){
                            if (game != NULL && !game->isHost()){
                                const std::string & gameName = ctcp.at(2);
                                const std::string & serverIp = ctcp.at(3);
                                chatInterface.addMessageToTab("* Host has started game " + gameName);
                                game->start(ipAddress, serverIp);
                            }
                        }
                    } else {
                        Global::debug(0) << "Got ctcp: " << ctcp.at(0) << std::endl;
                    }
                } catch (const std::out_of_range & ex){
                }
            }
        }
    }

    void localCommand(const std::vector<std::string> & command){
        if (command.at(0) == "help"){
            chatInterface.addMessageToTab("* commands: lol, game");
        } else if (command.at(0) == "lol"){
            chatInterface.addMessageToTab("* You LOLOLOLOLLOLOLOL yourself.");
        } else if (command.at(0) == "game"){
            // Game
            if (command.size() > 1){
                if (command.at(1) == "help"){
                    chatInterface.addMessageToTab("* game commands: help, new, start, list-users, list-hosts, invite, join.");
                } else if (command.at(1) == "new"){
                    try{
                        game = Util::ReferenceCount<Game>(new Game(command.at(2)));
                        chatInterface.addMessageToTab("* game \"" + command.at(2) + "\" created.");
                    } catch (const std::out_of_range & ex){
                        chatInterface.addMessageToTab("* /game new [name]");
                    }
                } else if (command.at(1) == "start"){
                    if (game != NULL && game->isHost() && game->getClients().size() > 0){
                        chatInterface.addMessageToTab("* Starting game " + game->getName());
                        game->start(ipAddress, ipAddress);
                        for (std::map<std::string, std::string>::iterator i = game->getClients().begin(); i != game->getClients().end(); i++){
                            chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
                                                                    (*i).first,
                                                                    ":\001game start " + game->getName() + " " + ipAddress + "\001");
                        }
                    } else {
                        chatInterface.addMessageToTab("* Create a game first...");
                    }
                } else if (command.at(1) == "list-users"){
                    if (game != NULL){
                        chatInterface.addMessageToTab("* Users who accepted game request: " + game->clientsAsString());
                    } else {
                        chatInterface.addMessageToTab("* Create a game first or have people join your game...");
                    }
                } else if (command.at(1) == "list-hosts"){
                    if (!hosts.empty()){
                        std::string hostlist;
                        for (std::map<std::string, std::string>::iterator i = hosts.begin(); i != hosts.end(); i++){
                            hostlist += (*i).first + +" [" + (*i).second + "], ";
                        }
                        chatInterface.addMessageToTab("* Hosts and games you've been invited to: " + hostlist.substr(0, hostlist.size() - 2));
                    } else {
                        chatInterface.addMessageToTab("* You have no invites.");
                    }
                } else if (command.at(1) == "invite"){
                    if (game != NULL){
                        try {
                            chatInterface.addMessageToTab("* Sending request to " + command.at(2));
                            chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
                                                            command.at(2),
                                                            ":\001game invite " + game->getName() + " " + chatInterface.getClient()->getName() + "\001");
                        } catch (const std::out_of_range & ex){
                            chatInterface.addMessageToTab("* /game invite [username]");
                        }
                    } else {
                        chatInterface.addMessageToTab("* Create a game first...");
                    }
                } else if (command.at(1) == "join"){
                    if (!hosts.empty()){
                        try {
                            const std::string & gameName = command.at(2);
                            const std::string & hostName = hosts[gameName];
                            chatInterface.addMessageToTab("* Joining game at " + gameName);
                            chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
                                                            hostName,
                                                            ":\001game join " + gameName + " " + chatInterface.getClient()->getName() + " " + ipAddress + "\001");
                            game = Util::ReferenceCount<Game>(new Game(gameName, false));
                        } catch (const std::out_of_range & ex){
                            chatInterface.addMessageToTab("* /game join [name]");
                        }
                    } else {
                        chatInterface.addMessageToTab("* You must be invited to a game first...");
                    }
                }
            }
        } else {
            //chatInterface.addMessageToTab("* Uknown command.");
        }
    }

    double ticks(double system){
        return system;
    }

    void run(){
        try {
            chatInterface.act();
        } catch (const Exception::Return & ex){
            escaped = true;
            throw ex;
        }
    }

    bool done(){
        return escaped;
    }

    void draw(const Graphics::Bitmap & screen){
        chatInterface.draw(screen);
    }
};

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

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

int main(int argc, char ** argv){
    if (argc >= 2){
        int port = atoi(argv[1]);
        std::string hostname = argv[2];
        std::string username = "paintown-test";
        if (argc > 3){
            username = argv[3];
        }

        Screen::realInit(Configuration::getScreenWidth(), Configuration::getScreenHeight());
        atexit(Screen::realFinish);
        Common::startTimers();

        Sound::initialize();

        Global::setDebug(2);

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

        InputManager manager;

        Util::Parameter<Util::ReferenceCount<Path::RelativePath> >
            defaultFont(Font::defaultFont, Util::ReferenceCount<Path::RelativePath>(new Path::RelativePath("fonts/arial.ttf")));

        Network::init();

        try {
            doIrc(hostname, port, username);
        } 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>#include <numeric>
#include <ros/ros.h>
#include <algorithm>

#include <geometry_msgs/PointStamped.h>
#include <opencv/cv.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <image_transport/image_transport.h>
#include <image_geometry/pinhole_camera_model.h>
#include <image_geometry/pinhole_camera_model.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <std_srvs/Empty.h>

#ifdef HAVE_GTK
#include <gtk/gtk.h>
static void destroyNode(GtkWidget *widget, gpointer data) { exit(0); }
#endif

namespace hrl_clickable_world {

    class ClickableDisplay {
        public:
            ros::NodeHandle nh, nh_priv;
            image_transport::ImageTransport img_trans;
            image_transport::Subscriber camera_sub;
            ros::ServiceClient display_buttons_srv;
            ros::Publisher pt_pub;
            std::string img_frame;
            double last_time;

            ClickableDisplay();
            ~ClickableDisplay();
            void onInit();
            void imgCallback(const sensor_msgs::ImageConstPtr& img_msg);
            static void mouseClickCallback(int event, int x, int y, int flags, void* data);
            static void perceiveButtonCallback(int state, void* data);

    };

    ClickableDisplay::ClickableDisplay() : nh_priv("clickable_world"), img_trans(nh),
                                           last_time(0) {
    }

    void ClickableDisplay::onInit() {
        cv::namedWindow("Clickable World", 1);
        // Can't use: requires QT support
        //cv::createButton("Perceive Buttons", &ClickableDisplay::perceiveButtonCallback,
        //                 this, CV_PUSH_BUTTON, 0);
        cv::setMouseCallback("Clickable World", &ClickableDisplay::mouseClickCallback, this);

#ifdef HAVE_GTK
        GtkWidge *widget = GTK_WIDGET(cvGetWindowHandle("Clickable World"));
        g_signal_connect(widget, "destroy", G_CALLBACK(destroyNode), NULL);
#endif

        camera_sub = img_trans.subscribe<ClickableDisplay>
                                              ("image", 1,
                                               &ClickableDisplay::imgCallback, this);
        pt_pub = nh_priv.advertise<geometry_msgs::PointStamped>("mouse_click", 1);
        display_buttons_srv = nh_priv.serviceClient<std_srvs::Empty>("perceive_buttons", true);

        ROS_INFO("[clickable_display] ClickableDisplay loaded.");
        ros::Duration(1).sleep();
    }

    void ClickableDisplay::imgCallback(const sensor_msgs::ImageConstPtr& img_msg) {
        img_frame = img_msg->header.frame_id;
        cv_bridge::CvImagePtr cv_ptr;
        try {
            cv_ptr = cv_bridge::toCvCopy(img_msg, sensor_msgs::image_encodings::BGR8);
            cv::imshow("Clickable World", cv_ptr->image);
            cv::waitKey(3);
        }
        catch(cv_bridge::Exception& e) {
            ROS_ERROR("[clickable_display] cv_bridge exception: %s", e.what());
            return;
        }
    }

    void ClickableDisplay::mouseClickCallback(int event, int x, int y, int flags, void* param) {
        ClickableDisplay* this_ = reinterpret_cast<ClickableDisplay*>(param);
        if(event == CV_EVENT_LBUTTONDOWN) {
            geometry_msgs::PointStamped click_pt;
            click_pt.header.frame_id = this_->img_frame;
            click_pt.header.stamp = ros::Time::now();
            click_pt.point.x = x; click_pt.point.y = y;
            this_->pt_pub.publish(click_pt);
        }
        if(event == CV_EVENT_RBUTTONDOWN && ros::Time::now().toSec() - this_->last_time > 1) {
            this_->last_time = ros::Time::now().toSec();
            std_srvs::EmptyRequest req; std_srvs::EmptyResponse resp;
            this_->display_buttons_srv.call(req, resp);
        }
    }

    void ClickableDisplay::perceiveButtonCallback(int state, void* data) {
        ClickableDisplay* this_ = reinterpret_cast<ClickableDisplay*>(data);
        ROS_INFO("%d", state);
        return;
        std_srvs::EmptyRequest req; std_srvs::EmptyResponse resp;
        this_->display_buttons_srv.call(req, resp);
    }

    ClickableDisplay::~ClickableDisplay() {
        cv::destroyWindow("Clickable World");
    }

};

using namespace hrl_clickable_world;

int main(int argc, char **argv)
{
    ros::init(argc, argv, "clickable_display");
    ClickableDisplay cd;
    cd.onInit();
    ros::spin();
    return 0;
}
<commit_msg>Clickable display changes to support refactoring.<commit_after>#include <numeric>
#include <ros/ros.h>
#include <algorithm>

#include <geometry_msgs/PointStamped.h>
#include <opencv/cv.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <image_transport/image_transport.h>
#include <image_geometry/pinhole_camera_model.h>
#include <image_geometry/pinhole_camera_model.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <std_srvs/Empty.h>

namespace hrl_clickable_world {

    class ClickableDisplay {
        public:
            ros::NodeHandle nh, nh_priv;
            image_transport::ImageTransport img_trans;
            image_transport::Subscriber camera_sub;
            ros::Publisher l_click_pub, r_click_pub;
            std::string img_frame;
            cv_bridge::CvImagePtr img_ptr;
            bool have_img;

            ClickableDisplay();
            ~ClickableDisplay();
            void onInit();
            void imgCallback(const sensor_msgs::ImageConstPtr& img_msg);
            void showImg();
            static void mouseClickCallback(int event, int x, int y, int flags, void* data);

    };

    ClickableDisplay::ClickableDisplay() : nh_priv("clickable_world"),
                                           img_trans(nh),
                                           have_img(false) {
    }

    void ClickableDisplay::onInit() {
        cv::namedWindow("Clickable World", 1);
        cv::setMouseCallback("Clickable World", &ClickableDisplay::mouseClickCallback, this);

        camera_sub = img_trans.subscribe<ClickableDisplay>
                                              ("image", 1,
                                               &ClickableDisplay::imgCallback, this);
        l_click_pub = nh_priv.advertise<geometry_msgs::PointStamped>("l_mouse_click", 1);
        r_click_pub = nh_priv.advertise<geometry_msgs::PointStamped>("r_mouse_click", 1);

        ROS_INFO("[clickable_display] ClickableDisplay loaded.");
        ros::Duration(1).sleep();
    }

    void ClickableDisplay::imgCallback(const sensor_msgs::ImageConstPtr& img_msg) {
        img_frame = img_msg->header.frame_id;
        try {
            img_ptr = cv_bridge::toCvCopy(img_msg, sensor_msgs::image_encodings::BGR8);
            have_img = true;
        }
        catch(cv_bridge::Exception& e) {
            ROS_ERROR("[clickable_display] cv_bridge exception: %s", e.what());
            return;
        }
    }

    void ClickableDisplay::showImg() {
        ros::Rate r(30);
        while(ros::ok()) {
            ros::spinOnce();
            if(have_img) {
                cv::imshow("Clickable World", img_ptr->image);
                cv::waitKey(3);
            }
            r.sleep();
        }
    }

    void ClickableDisplay::mouseClickCallback(int event, int x, int y, int flags, void* param) {
        ClickableDisplay* this_ = reinterpret_cast<ClickableDisplay*>(param);
        if(event == CV_EVENT_LBUTTONDOWN) {
            geometry_msgs::PointStamped click_pt;
            click_pt.header.frame_id = this_->img_frame;
            click_pt.header.stamp = ros::Time::now();
            click_pt.point.x = x; click_pt.point.y = y;
            this_->l_click_pub.publish(click_pt);
        }
        if(event == CV_EVENT_RBUTTONDOWN) {
            geometry_msgs::PointStamped click_pt;
            click_pt.header.frame_id = this_->img_frame;
            click_pt.header.stamp = ros::Time::now();
            click_pt.point.x = x; click_pt.point.y = y;
            this_->r_click_pub.publish(click_pt);
        }
    }

    ClickableDisplay::~ClickableDisplay() {
        cv::destroyWindow("Clickable World");
    }

};

using namespace hrl_clickable_world;

int main(int argc, char **argv)
{
    ros::init(argc, argv, "clickable_display");
    ClickableDisplay cd;
    cd.onInit();
    cd.showImg();
    ros::spin();
    return 0;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/hwas/hostbootIstep.C $                                */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 2012,2014              */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 *  @file hostbootIstep.C
 *
 *  @brief hostboot istep-called functions
 */

#include <hwas/common/hwas.H>
#include <hwas/common/hwasCommon.H>
#include <hwas/common/hwas_reasoncodes.H>
#include <hwas/hwasPlat.H>

#include <hwas/hostbootIstep.H>
#include <hwas/common/deconfigGard.H>

#include <fsi/fsiif.H>
#include <initservice/taskargs.H>
#include <initservice/isteps_trace.H>
#include <hwpisteperror.H>

#include <targeting/attrsync.H>
#include <targeting/namedtarget.H>
#include <diag/prdf/prdfMain.H>
#include <intr/interrupt.H>
#include <ibscom/ibscomif.H>

#include <sbe/sbeif.H>
#include <sbe_update.H>

//  fapi support
#include  <fapi.H>
#include  <fapiPlatHwpInvoker.H>

//  targeting support.
#include  <targeting/common/utilFilter.H>
#include  <targeting/common/commontargeting.H>

#include  <errl/errludtarget.H>

#include <proc_enable_reconfig.H>

namespace HWAS
{

using namespace TARGETING;
using namespace fapi;
using namespace ISTEP;
using namespace ISTEP_ERROR;

// functions called from the istep dispatcher -- hostboot only

//******************************************************************************
// host_init_fsi function
//******************************************************************************
void* host_init_fsi( void *io_pArgs )
{
    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_init_fsi entry" );

    errlHndl_t errl = FSI::initializeHardware( );

    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_init_fsi exit" );

    return errl;
}

//******************************************************************************
// host_set_ipl_parms function
//******************************************************************************
void* host_set_ipl_parms( void *io_pArgs )
{
    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_set_ipl_parms entry" );
    errlHndl_t errl = NULL;

    // stub -- nothing here currently

    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_set_ipl_parms exit" );

    return errl;
}

//******************************************************************************
// host_discover_targets function
//******************************************************************************
void* host_discover_targets( void *io_pArgs )
{
    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "host_discover_targets entry" );

    errlHndl_t errl = NULL;

    // Check whether we're in MPIPL mode
    TARGETING::Target* l_pTopLevel = NULL;
    targetService().getTopLevelTarget( l_pTopLevel );
    HWAS_ASSERT(l_pTopLevel, "HWAS host_discover_targets: no TopLevelTarget");

    if (l_pTopLevel->getAttr<ATTR_IS_MPIPL_HB>())
    {
        TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "MPIPL mode");

        // Sync attributes from Fsp
        errl = syncAllAttributesFromFsp();
    }
    else
    {
        TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Normal IPL mode");

        errl = discoverTargets();

        // also if SP doesn't support change detection, call
        // function to do it here.
        if (!errl &&
            !l_pTopLevel->getAttr<ATTR_SP_FUNCTIONS>()
                .hardwareChangeDetection)
        {
            TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                "calling hwasChangeDetection");
            errl = hwasChangeDetection();
        }
    }

    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "host_discover_targets exit" );

    return errl;
}

//******************************************************************************
// host_gard function
//******************************************************************************
void* host_gard( void *io_pArgs )
{
    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_gard entry" );

    errlHndl_t errl;

    // Check whether we're in MPIPL mode
    TARGETING::Target* l_pTopLevel = NULL;
    targetService().getTopLevelTarget( l_pTopLevel );
    HWAS_ASSERT(l_pTopLevel, "HWAS host_gard: no TopLevelTarget");

    if (l_pTopLevel->getAttr<ATTR_IS_MPIPL_HB>())
    {
        TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "MPIPL mode");

        // we only want EX units to be processed
        TARGETING::PredicateCTM l_exFilter(TARGETING::CLASS_UNIT,
                                           TARGETING::TYPE_EX);
        errl = collectGard(&l_exFilter);
    }
    else
    {
        TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Normal IPL mode");

        errl = collectGard();

        if (errl == NULL)
        {
            //  check and see if we still have enough hardware to continue
            errl = checkMinimumHardware();
        }
        // If targets are deconfigured as a result of host_gard, they are
        // done so using the PLID as the reason for deconfiguration.  This
        // triggers the reconfigure loop attribute to be set, which causes
        // undesirable behavior, so we need to reset it here:

        // Read current value
        TARGETING::ATTR_RECONFIGURE_LOOP_type l_reconfigAttr =
            l_pTopLevel->getAttr<TARGETING::ATTR_RECONFIGURE_LOOP>();
        // Turn off deconfigure bit
        l_reconfigAttr &= ~TARGETING::RECONFIGURE_LOOP_DECONFIGURE;
        // Write back to attribute
        l_pTopLevel->setAttr<TARGETING::ATTR_RECONFIGURE_LOOP>(l_reconfigAttr);
    }

    // Send message to FSP sending HUID of EX chip associated with master core
    msg_t * core_msg = msg_allocate();
    core_msg->type = SBE::MSG_IPL_MASTER_CORE;
    const TARGETING::Target*  l_masterCore  = TARGETING::getMasterCore( );
    HWAS_ASSERT(l_masterCore, "HWAS host_gard: no masterCore found");
    // Get the EX chip associated with the master core as that is the chip that
    //   has the IS_MASTER_EX attribute associated with it
    TARGETING::TargetHandleList targetList;
    getParentAffinityTargets(targetList,
                             l_masterCore,
                             TARGETING::CLASS_UNIT,
                             TARGETING::TYPE_EX);
    HWAS_ASSERT(targetList.size() == 1,
             "HWAS host_gard: Incorrect EX chip(s) associated with masterCore");
    core_msg->data[0] = 0;
    core_msg->data[1] = TARGETING::get_huid( targetList[0] );
    core_msg->extra_data = NULL;
    TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
              "Sending MSG_MASTER_CORE message with HUID %08x",
              core_msg->data[1]);
    errl = MBOX::send(MBOX::IPL_SERVICE_QUEUE,core_msg);
    if (errl)
    {
        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                      ERR_MRK"MBOX::send failed sending Master Core message");
        msg_free(core_msg);

    }

    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_gard exit" );
    return errl;
}

//******************************************************************************
// host_cancontinue_clear function
//******************************************************************************
void* host_cancontinue_clear( void *io_pArgs )
{
    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "host_cancontinue_clear entry" );
    errlHndl_t errl = NULL;

    // stub -- nothing here currently

    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "host_cancontinue_clear exit" );

    return errl;
}

//******************************************************************************
// host_prd_hwreconfig function
//******************************************************************************
void* host_prd_hwreconfig( void *io_pArgs )
{
    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "host_prd_hwreconfig entry" );

    errlHndl_t errl = NULL;
    IStepError l_stepError;
    do
    {
        // Flip the scom path back to FSI in case we enabled IBSCOM previously
        IBSCOM::enableInbandScoms(IBSCOM_DISABLE);

        // Call PRDF to remove non-function chips from its system model
        errl = PRDF::refresh();

        if (errl)
        {
            TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                      "host_prd_hwreconfig ERROR 0x%.8X returned from"
                      "  call to PRDF::refresh", errl->reasonCode());

            // Create IStep error log and cross reference error that occurred
            l_stepError.addErrorDetails(errl);

            // Commit Error
            errlCommit(errl, HWPF_COMP_ID);

            break;
        }

        // Lists for present MCS/Centaurs
        TARGETING::TargetHandleList l_presMcsList;
        TARGETING::TargetHandleList l_presCentaurList;

        // find all present MCS chiplets of all procs
        getChipletResources(l_presMcsList, TYPE_MCS, UTIL_FILTER_PRESENT);

        for (TargetHandleList::const_iterator
             l_mcs_iter = l_presMcsList.begin();
             l_mcs_iter != l_presMcsList.end();
             ++l_mcs_iter)
        {
            // make a local copy of the MCS target
            const TARGETING::Target * l_pMcs = *l_mcs_iter;
            // Retrieve HUID of current MCS
            TARGETING::ATTR_HUID_type l_currMcsHuid =
                TARGETING::get_huid(l_pMcs);

            // Find all the present Centaurs that are associated with this MCS
            getChildAffinityTargetsByState(l_presCentaurList, l_pMcs,
                           CLASS_CHIP, TYPE_MEMBUF, UTIL_FILTER_PRESENT);

            // There will always be 1 Centaur associated with a MCS.
            if(1 != l_presCentaurList.size())
            {
                TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                        "No present Centaurs found for "
                        "MCS target HUID %.8X , skipping this MCS",
                        l_currMcsHuid);
                continue;
            }

            // Make a local copy
            const TARGETING::Target * l_pCentaur = l_presCentaurList[0];
            // Retrieve HUID of current Centaur
            TARGETING::ATTR_HUID_type l_currCentaurHuid =
                TARGETING::get_huid(l_pCentaur);

            // Dump current run on target
            TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                    "Running proc_enable_reconfig HWP on "
                    "MCS target HUID %.8X CENTAUR target HUID %.8X",
                    l_currMcsHuid, l_currCentaurHuid);

            // Create FAPI Targets.
            fapi::Target l_fapiMcsTarget(TARGET_TYPE_MCS_CHIPLET,
                    (const_cast<TARGETING::Target*>(l_pMcs)));
            fapi::Target l_fapiCentaurTarget(TARGET_TYPE_MEMBUF_CHIP,
                    (const_cast<TARGETING::Target*>(l_pCentaur)));

            // Call the HWP with each fapi::Target
            FAPI_INVOKE_HWP(errl, proc_enable_reconfig,
                            l_fapiMcsTarget, l_fapiCentaurTarget);

            if (errl)
            {
                TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                          "ERROR 0x%.8X: proc_enable_reconfig HWP returns error",
                          errl->reasonCode());

                // Capture the target data in the elog
                ERRORLOG::ErrlUserDetailsTarget(l_pMcs).addToLog( errl );

                // Create IStep error log and cross reference error that occurred
                l_stepError.addErrorDetails(errl);

                // Commit Error
                errlCommit(errl, HWPF_COMP_ID);
            }
            else
            {
                // Success
                TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                        "Successfully ran proc_enable_reconfig HWP on "
                        "MCS target HUID %.8X CENTAUR target HUID %.8X",
                        l_currMcsHuid,
                        l_currCentaurHuid);
            }
        }
    }
    while(0);
    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "host_prd_hwreconfig exit" );
    // end task, returning any errorlogs to IStepDisp
    return l_stepError.getErrorHandle();
}

//******************************************************************************
// host_stub function
//******************************************************************************
void* host_stub( void *io_pArgs )
{
    errlHndl_t errl = NULL;
    // no function required
    return errl;
}

} // namespace HWAS
<commit_msg>Change IPL behavior dealing from errors in proc_enable_reconfig<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/hwas/hostbootIstep.C $                                */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 2012,2014              */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 *  @file hostbootIstep.C
 *
 *  @brief hostboot istep-called functions
 */

#include <hwas/common/hwas.H>
#include <hwas/common/hwasCommon.H>
#include <hwas/common/hwas_reasoncodes.H>
#include <hwas/hwasPlat.H>

#include <hwas/hostbootIstep.H>
#include <hwas/common/deconfigGard.H>

#include <fsi/fsiif.H>
#include <initservice/taskargs.H>
#include <initservice/isteps_trace.H>
#include <hwpisteperror.H>

#include <targeting/attrsync.H>
#include <targeting/namedtarget.H>
#include <diag/prdf/prdfMain.H>
#include <intr/interrupt.H>
#include <ibscom/ibscomif.H>

#include <sbe/sbeif.H>
#include <sbe_update.H>

//  fapi support
#include  <fapi.H>
#include  <fapiPlatHwpInvoker.H>

//  targeting support.
#include  <targeting/common/utilFilter.H>
#include  <targeting/common/commontargeting.H>

#include  <errl/errludtarget.H>

#include <proc_enable_reconfig.H>

namespace HWAS
{

using namespace TARGETING;
using namespace fapi;
using namespace ISTEP;
using namespace ISTEP_ERROR;

// functions called from the istep dispatcher -- hostboot only

//******************************************************************************
// host_init_fsi function
//******************************************************************************
void* host_init_fsi( void *io_pArgs )
{
    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_init_fsi entry" );

    errlHndl_t errl = FSI::initializeHardware( );

    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_init_fsi exit" );

    return errl;
}

//******************************************************************************
// host_set_ipl_parms function
//******************************************************************************
void* host_set_ipl_parms( void *io_pArgs )
{
    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_set_ipl_parms entry" );
    errlHndl_t errl = NULL;

    // stub -- nothing here currently

    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_set_ipl_parms exit" );

    return errl;
}

//******************************************************************************
// host_discover_targets function
//******************************************************************************
void* host_discover_targets( void *io_pArgs )
{
    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "host_discover_targets entry" );

    errlHndl_t errl = NULL;

    // Check whether we're in MPIPL mode
    TARGETING::Target* l_pTopLevel = NULL;
    targetService().getTopLevelTarget( l_pTopLevel );
    HWAS_ASSERT(l_pTopLevel, "HWAS host_discover_targets: no TopLevelTarget");

    if (l_pTopLevel->getAttr<ATTR_IS_MPIPL_HB>())
    {
        TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "MPIPL mode");

        // Sync attributes from Fsp
        errl = syncAllAttributesFromFsp();
    }
    else
    {
        TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Normal IPL mode");

        errl = discoverTargets();

        // also if SP doesn't support change detection, call
        // function to do it here.
        if (!errl &&
            !l_pTopLevel->getAttr<ATTR_SP_FUNCTIONS>()
                .hardwareChangeDetection)
        {
            TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                "calling hwasChangeDetection");
            errl = hwasChangeDetection();
        }
    }

    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "host_discover_targets exit" );

    return errl;
}

//******************************************************************************
// host_gard function
//******************************************************************************
void* host_gard( void *io_pArgs )
{
    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_gard entry" );

    errlHndl_t errl;

    // Check whether we're in MPIPL mode
    TARGETING::Target* l_pTopLevel = NULL;
    targetService().getTopLevelTarget( l_pTopLevel );
    HWAS_ASSERT(l_pTopLevel, "HWAS host_gard: no TopLevelTarget");

    if (l_pTopLevel->getAttr<ATTR_IS_MPIPL_HB>())
    {
        TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "MPIPL mode");

        // we only want EX units to be processed
        TARGETING::PredicateCTM l_exFilter(TARGETING::CLASS_UNIT,
                                           TARGETING::TYPE_EX);
        errl = collectGard(&l_exFilter);
    }
    else
    {
        TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Normal IPL mode");

        errl = collectGard();

        if (errl == NULL)
        {
            //  check and see if we still have enough hardware to continue
            errl = checkMinimumHardware();
        }
        // If targets are deconfigured as a result of host_gard, they are
        // done so using the PLID as the reason for deconfiguration.  This
        // triggers the reconfigure loop attribute to be set, which causes
        // undesirable behavior, so we need to reset it here:

        // Read current value
        TARGETING::ATTR_RECONFIGURE_LOOP_type l_reconfigAttr =
            l_pTopLevel->getAttr<TARGETING::ATTR_RECONFIGURE_LOOP>();
        // Turn off deconfigure bit
        l_reconfigAttr &= ~TARGETING::RECONFIGURE_LOOP_DECONFIGURE;
        // Write back to attribute
        l_pTopLevel->setAttr<TARGETING::ATTR_RECONFIGURE_LOOP>(l_reconfigAttr);
    }

    // Send message to FSP sending HUID of EX chip associated with master core
    msg_t * core_msg = msg_allocate();
    core_msg->type = SBE::MSG_IPL_MASTER_CORE;
    const TARGETING::Target*  l_masterCore  = TARGETING::getMasterCore( );
    HWAS_ASSERT(l_masterCore, "HWAS host_gard: no masterCore found");
    // Get the EX chip associated with the master core as that is the chip that
    //   has the IS_MASTER_EX attribute associated with it
    TARGETING::TargetHandleList targetList;
    getParentAffinityTargets(targetList,
                             l_masterCore,
                             TARGETING::CLASS_UNIT,
                             TARGETING::TYPE_EX);
    HWAS_ASSERT(targetList.size() == 1,
             "HWAS host_gard: Incorrect EX chip(s) associated with masterCore");
    core_msg->data[0] = 0;
    core_msg->data[1] = TARGETING::get_huid( targetList[0] );
    core_msg->extra_data = NULL;
    TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
              "Sending MSG_MASTER_CORE message with HUID %08x",
              core_msg->data[1]);
    errl = MBOX::send(MBOX::IPL_SERVICE_QUEUE,core_msg);
    if (errl)
    {
        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                      ERR_MRK"MBOX::send failed sending Master Core message");
        msg_free(core_msg);

    }

    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_gard exit" );
    return errl;
}

//******************************************************************************
// host_cancontinue_clear function
//******************************************************************************
void* host_cancontinue_clear( void *io_pArgs )
{
    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "host_cancontinue_clear entry" );
    errlHndl_t errl = NULL;

    // stub -- nothing here currently

    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "host_cancontinue_clear exit" );

    return errl;
}

//******************************************************************************
// host_prd_hwreconfig function
//******************************************************************************
void* host_prd_hwreconfig( void *io_pArgs )
{
    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "host_prd_hwreconfig entry" );

    errlHndl_t errl = NULL;
    IStepError l_stepError;
    do
    {
        // Flip the scom path back to FSI in case we enabled IBSCOM previously
        IBSCOM::enableInbandScoms(IBSCOM_DISABLE);

        // Call PRDF to remove non-function chips from its system model
        errl = PRDF::refresh();

        if (errl)
        {
            TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                      "host_prd_hwreconfig ERROR 0x%.8X returned from"
                      "  call to PRDF::refresh", errl->reasonCode());

            // Create IStep error log and cross reference error that occurred
            l_stepError.addErrorDetails(errl);

            // Commit Error
            errlCommit(errl, HWPF_COMP_ID);

            break;
        }

        // Lists for present MCS/Centaurs
        TARGETING::TargetHandleList l_presMcsList;
        TARGETING::TargetHandleList l_presCentaurList;

        // find all present MCS chiplets of all procs
        getChipletResources(l_presMcsList, TYPE_MCS, UTIL_FILTER_PRESENT);

        for (TargetHandleList::const_iterator
             l_mcs_iter = l_presMcsList.begin();
             l_mcs_iter != l_presMcsList.end();
             ++l_mcs_iter)
        {
            // make a local copy of the MCS target
            const TARGETING::Target * l_pMcs = *l_mcs_iter;
            // Retrieve HUID of current MCS
            TARGETING::ATTR_HUID_type l_currMcsHuid =
                TARGETING::get_huid(l_pMcs);

            // Find all the present Centaurs that are associated with this MCS
            getChildAffinityTargetsByState(l_presCentaurList, l_pMcs,
                           CLASS_CHIP, TYPE_MEMBUF, UTIL_FILTER_PRESENT);

            // There will always be 1 Centaur associated with a MCS.
            if(1 != l_presCentaurList.size())
            {
                TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                        "No present Centaurs found for "
                        "MCS target HUID %.8X , skipping this MCS",
                        l_currMcsHuid);
                continue;
            }

            // Make a local copy
            const TARGETING::Target * l_pCentaur = l_presCentaurList[0];
            // Retrieve HUID of current Centaur
            TARGETING::ATTR_HUID_type l_currCentaurHuid =
                TARGETING::get_huid(l_pCentaur);

            // Dump current run on target
            TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                    "Running proc_enable_reconfig HWP on "
                    "MCS target HUID %.8X CENTAUR target HUID %.8X",
                    l_currMcsHuid, l_currCentaurHuid);

            // Create FAPI Targets.
            fapi::Target l_fapiMcsTarget(TARGET_TYPE_MCS_CHIPLET,
                    (const_cast<TARGETING::Target*>(l_pMcs)));
            fapi::Target l_fapiCentaurTarget(TARGET_TYPE_MEMBUF_CHIP,
                    (const_cast<TARGETING::Target*>(l_pCentaur)));

            // Call the HWP with each fapi::Target
            FAPI_INVOKE_HWP(errl, proc_enable_reconfig,
                            l_fapiMcsTarget, l_fapiCentaurTarget);

            if (errl)
            {
                TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                         "ERROR 0x%.8X: proc_enable_reconfig HWP returns error",
                          errl->reasonCode());

                // Capture the target data in the elog
                ERRORLOG::ErrlUserDetailsTarget(l_pMcs).addToLog( errl );

                //Create IStep error log and cross reference error that occurred
                l_stepError.addErrorDetails(errl);

                // Commit Error
                errlCommit(errl, HWPF_COMP_ID);

                // Don't keep calling proc_enable_reconfig. Treat as a fatal
                // unexpected unrecoverable error and terminate the IPL.
                break ; // break with error
            }
            // Success
            TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                    "Successfully ran proc_enable_reconfig HWP on "
                    "MCS target HUID %.8X CENTAUR target HUID %.8X",
                    l_currMcsHuid,
                    l_currCentaurHuid);
        }
    }
    while(0);
    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "host_prd_hwreconfig exit" );
    // end task, returning any errorlogs to IStepDisp
    return l_stepError.getErrorHandle();
}

//******************************************************************************
// host_stub function
//******************************************************************************
void* host_stub( void *io_pArgs )
{
    errlHndl_t errl = NULL;
    // no function required
    return errl;
}

} // namespace HWAS
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <string.h>
#include <iostream>

extern "C"
{
#include "SlimList.h"
#include "SlimListDeserializer.h"
#include "SlimListSerializer.h"
}

#include "CppUTest/TestHarness.h"
#include "CppUTest/TestHarness_c.h"

TEST_GROUP(SlimListDeserializer)
{
    SlimList* slimList;
	SlimList* deserializedList;
	char* serializedList;

    void setup()
    {
		slimList  = SlimList_Create();
		serializedList = 0;
		deserializedList = 0;
    }

    void teardown()
    {
		SlimList_Destroy(slimList);

		if (deserializedList)
			SlimList_Destroy(deserializedList);

		if (serializedList != 0)
			SlimList_Release(serializedList);
    }

	void check_lists_equal(SlimList* expected, SlimList* actual) {
		CHECK(SlimList_Equals(expected, actual));
	}

};

TEST(SlimListDeserializer, deserializeEmptyList)
{
	deserializedList = SlimList_Deserialize("[000000:]");
	CHECK(deserializedList != 0);
	LONGS_EQUAL(0, SlimList_GetLength(deserializedList));
}

TEST(SlimListDeserializer, deserializeNull)
{
	SlimList* list = SlimList_Deserialize(0);
	POINTERS_EQUAL(0, list);
}

TEST(SlimListDeserializer, deserializeEmptyString)
{
	SlimList* list = SlimList_Deserialize("");
	POINTERS_EQUAL(0, list);
}

TEST(SlimListDeserializer, MissingOpenBracketReturnsNull)
{
	SlimList* list = SlimList_Deserialize("hello");
	POINTERS_EQUAL(0, list);
}

TEST(SlimListDeserializer, MissingClosingBracketReturnsNull)
{
	SlimList* list = SlimList_Deserialize("[000000:");
	POINTERS_EQUAL(0, list);
}

TEST(SlimListDeserializer, canDeserializeCanonicalListWithOneElement)
{
	char const* canonicalList = "[000001:000008:Hi doug.:]";
	SlimList* deserializedList = SlimList_Deserialize(canonicalList);
	CHECK(deserializedList != NULL);
	LONGS_EQUAL(1, SlimList_GetLength(deserializedList));
	STRCMP_EQUAL("Hi doug.", SlimList_GetStringAt(deserializedList, 0));
	SlimList_Destroy(deserializedList);
}

TEST(SlimListDeserializer, canDeSerializeListWithOneElement)
{
	SlimList_AddString(slimList, "hello");
	serializedList = SlimList_Serialize(slimList);
	deserializedList = SlimList_Deserialize(serializedList);
	CHECK(deserializedList != 0);
	check_lists_equal(slimList, deserializedList);
}

TEST(SlimListDeserializer, canDeSerializeListWithTwoElements)
{
	SlimList_AddString(slimList, "hello");
	SlimList_AddString(slimList, "bob");
	serializedList = SlimList_Serialize(slimList);
	deserializedList = SlimList_Deserialize(serializedList);
	CHECK(deserializedList != 0);
	check_lists_equal(slimList, deserializedList);
}

TEST(SlimListDeserializer, canAddSubList)
{
	SlimList* embeddedList;
	embeddedList = SlimList_Create();
	SlimList_AddString(embeddedList, "element");
	SlimList_AddList(slimList, embeddedList);
	serializedList = SlimList_Serialize(slimList);
	deserializedList = SlimList_Deserialize(serializedList);
	SlimList * subList = SlimList_GetListAt(deserializedList, 0);
	subList = SlimList_GetListAt(deserializedList, 0);
	check_lists_equal(embeddedList, subList);

	SlimList_Destroy(embeddedList);
}

TEST(SlimListDeserializer, getStringWhereThereIsAList)
{
	SlimList* embeddedList;
	embeddedList = SlimList_Create();
	SlimList_AddString(embeddedList, "element");
	SlimList_AddList(slimList, embeddedList);
	serializedList = SlimList_Serialize(slimList);
	deserializedList = SlimList_Deserialize(serializedList);
	char * string = SlimList_GetStringAt(deserializedList, 0);

	STRCMP_EQUAL("[000001:000007:element:]", string);
	// POINTERS_EQUAL(0, string); ?????????????????????????????????????

	SlimList_Destroy(embeddedList);
}
<commit_msg>Update tests/CSlim/SlimListDeserializerTest.cpp<commit_after>#include <stdlib.h>
#include <string.h>
#include <iostream>

extern "C"
{
#include "SlimList.h"
#include "SlimListDeserializer.h"
#include "SlimListSerializer.h"
}

#include "CppUTest/TestHarness.h"
#include "CppUTest/TestHarness_c.h"

TEST_GROUP(SlimListDeserializer)
{
    SlimList* slimList;
	SlimList* deserializedList;
	char* serializedList;

    void setup()
    {
		slimList  = SlimList_Create();
		serializedList = 0;
		deserializedList = 0;
    }

    void teardown()
    {
		SlimList_Destroy(slimList);

		if (deserializedList)
			SlimList_Destroy(deserializedList);

		if (serializedList != 0)
			SlimList_Release(serializedList);
    }

	void check_lists_equal(SlimList* expected, SlimList* actual) {
		CHECK(SlimList_Equals(expected, actual));
	}

};

TEST(SlimListDeserializer, deserializeEmptyList)
{
	deserializedList = SlimList_Deserialize("[000000:]");
	CHECK(deserializedList != 0);
	LONGS_EQUAL(0, SlimList_GetLength(deserializedList));
}

TEST(SlimListDeserializer, deserializeNull)
{
	SlimList* list = SlimList_Deserialize(0);
	POINTERS_EQUAL(0, list);
}

TEST(SlimListDeserializer, deserializeEmptyString)
{
	SlimList* list = SlimList_Deserialize("");
	POINTERS_EQUAL(0, list);
}

TEST(SlimListDeserializer, MissingOpenBracketReturnsNull)
{
	SlimList* list = SlimList_Deserialize("hello");
	POINTERS_EQUAL(0, list);
}

TEST(SlimListDeserializer, MissingClosingBracketReturnsNull)
{
	SlimList* list = SlimList_Deserialize("[000000:");
	POINTERS_EQUAL(0, list);
}

TEST(SlimListDeserializer, canDeserializeCanonicalListWithOneElement)
{
	char const* canonicalList = "[000001:000008:Hi doug.:]";
	SlimList* deserializedList = SlimList_Deserialize(canonicalList);
	CHECK(deserializedList != NULL);
	LONGS_EQUAL(1, SlimList_GetLength(deserializedList));
	STRCMP_EQUAL("Hi doug.", SlimList_GetStringAt(deserializedList, 0));
	SlimList_Destroy(deserializedList);
}

TEST(SlimListDeserializer, canDeSerializeListWithOneElement)
{
	SlimList_AddString(slimList, "hello");
	serializedList = SlimList_Serialize(slimList);
	deserializedList = SlimList_Deserialize(serializedList);
	CHECK(deserializedList != 0);
	check_lists_equal(slimList, deserializedList);
}

TEST(SlimListDeserializer, canDeSerializeListWithTwoElements)
{
	SlimList_AddString(slimList, "hello");
	SlimList_AddString(slimList, "bob");
	serializedList = SlimList_Serialize(slimList);
	deserializedList = SlimList_Deserialize(serializedList);
	CHECK(deserializedList != 0);
	check_lists_equal(slimList, deserializedList);
}

TEST(SlimListDeserializer, canAddSubList)
{
	SlimList* embeddedList;
	embeddedList = SlimList_Create();
	SlimList_AddString(embeddedList, "element");
	SlimList_AddList(slimList, embeddedList);
	serializedList = SlimList_Serialize(slimList);
	deserializedList = SlimList_Deserialize(serializedList);
	SlimList * subList = SlimList_GetListAt(deserializedList, 0);
	subList = SlimList_GetListAt(deserializedList, 0);
	check_lists_equal(embeddedList, subList);

	SlimList_Destroy(embeddedList);
}

TEST(SlimListDeserializer, getStringWhereThereIsAList)
{
	SlimList* embeddedList;
	embeddedList = SlimList_Create();
	SlimList_AddString(embeddedList, "element");
	SlimList_AddList(slimList, embeddedList);
	serializedList = SlimList_Serialize(slimList);
	deserializedList = SlimList_Deserialize(serializedList);
	char * string = SlimList_GetStringAt(deserializedList, 0);

	STRCMP_EQUAL("[000001:000007:element:]", string);
	// POINTERS_EQUAL(0, string); ?????????????????????????????????????

	SlimList_Destroy(embeddedList);
}
//JPR Addition
TEST(SlimListSerializer, serializeMultibyteCharacters)
{
  SlimList_AddString(slimList, "Ü€©phewÜ€©");
  serializedList = SlimList_Serialize(slimList);
  STRCMP_EQUAL("[000001:000010:Ü€©phewÜ€©:]", serializedList);
}
// JPR End Addition<|endoftext|>


<commit_before>#include <string>
#include <cstring>
#include "math3d/math3d.h"

#include "pbge/pbge.h"

#include "Ellipsoids.h"

Ellipsoids::Ellipsoids(pbge::GraphicAPI * _gfx) {
    this->sphere = pbge::Geometrics::createSphere(1.0f, 3, _gfx);
    this->gfx = _gfx;
}

pbge::ModelCollection * Ellipsoids::createEllipsoids(unsigned number_of_ellipsoids, math3d::matrix44 * transforms) {
    pbge::TextureBuffer * tex = gfx->getFactory()->createTextureBuffer(number_of_ellipsoids * sizeof(math3d::matrix44));
    void * texData = tex->getBuffer()->map(pbge::Buffer::WRITE_ONLY);
    memcpy(texData, transforms, number_of_ellipsoids * sizeof(math3d::matrix44));
    tex->getBuffer()->unmap();
    texData = NULL;
    tex->setInternalFormat(pbge::Texture::FLOAT, pbge::Texture::RGBA);
    pbge::ModelCollection * ellipsoids = new pbge::ModelCollection(sphere);
    ellipsoids->setNumberOfInstances(number_of_ellipsoids);

    pbge::UniformBufferSampler * uniform = ellipsoids->getUniformSet()->getBufferSampler("transforms");
    uniform->setValue(tex);

	ellipsoids->setRenderPassProgram(gfx->getFactory()->createProgramFromString(
        "#version 150\n"
		"uniform samplerBuffer transforms;\n"
        "uniform mat4 pbge_ModelViewMatrix;\n"
        "uniform mat4 pbge_ProjectionMatrix;\n"
		"out vec4 position;\n"
		"out vec3 normal;\n"
		"out vec4 lightPosition;\n"
        "in  vec4 pbge_Vertex;\n"
		"void main() {\n"
		"   const vec4 light_position = vec4(16,16,16,1);\n"
		"   int index = gl_InstanceID * 4;\n"
		"   vec4 col1 = texelFetch(transforms, index);\n"
		"   vec4 col2 = texelFetch(transforms, index + 1);\n"
		"   vec4 col3 = texelFetch(transforms, index + 2);\n"
		"   vec4 col4 = texelFetch(transforms, index + 3);\n"
		"   vec3 color = vec3(col1.w,col2.w,col3.w);\n"
		"   col1 = vec4(col1.xyz, 0);\n"
		"   col2 = vec4(col2.xyz, 0);\n"
		"   col3 = vec4(col3.xyz, 0);\n"
		"   col4 = vec4(col4.xyz, 1);\n"
		"   mat4 transformation = mat4(col1, col2, col3, col4);\n"
		"   mat4 t = pbge_ModelViewMatrix * transformation;\n"
		"   vec4 _normal = inverse(transpose(t)) * pbge_Vertex;\n"
		"   normal = normalize(_normal.xyz);\n"
		"   position = t * pbge_Vertex;\n"
		"   lightPosition = t * light_position;\n"
		"   gl_Position = pbge_ProjectionMatrix * position;\n"
		"   gl_FrontColor = vec4(color, 1.0);\n"
		"}",
        "in vec4 position;\n"
		"in vec3 normal;\n"
		"in vec4 lightPosition;\n"
		"void main() {\n"
		"   vec4 diffuseColor = gl_Color;\n"
		"   vec4 lightDiffuseColor = vec4(1.0,1.0,1,1);\n"
		"   vec3 lightDir = normalize((lightPosition - position).xyz);\n"
		"   float intensity = max(0.0, dot(lightDir, normal));\n"
		"   gl_FragData[0] = vec4(diffuseColor.rgb * lightDiffuseColor.rgb * intensity, gl_Color.a);\n"
		"}"
        ));
    ellipsoids->setDepthPassProgram(gfx->getFactory()->createProgramFromString(
        "#version 140\n"
		"#extension GL_EXT_gpu_shader4: enable\n"
        "#extension GL_ARB_draw_instanced: enable\n"
        "uniform samplerBuffer transforms;\n"
        "uniform mat4 pbge_ModelViewProjectionMatrix;\n"
        "in  vec4 pbge_Vertex;\n"
        "void main() {\n"
        "   int index = gl_InstanceIDARB * 4;\n"
        "   vec4 col1 = texelFetch(transforms, index);\n"
        "   vec4 col2 = texelFetch(transforms, index + 1);\n"
        "   vec4 col3 = texelFetch(transforms, index + 2);\n"
        "   vec4 col4 = texelFetch(transforms, index + 3);\n"
		"   col1 = vec4(col1.xyz, 0);\n"
		"   col2 = vec4(col2.xyz, 0);\n"
		"   col3 = vec4(col3.xyz, 0);\n"
		"   col4 = vec4(col4.xyz, 1);\n"
        "   mat4 transformation = mat4(col1, col2, col3, col4);\n"
        "   gl_Position = pbge_ModelViewProjectionMatrix * transformation * pbge_Vertex;\n"
        "}", ""));
    return ellipsoids;
}
<commit_msg>Making colors brighter<commit_after>#include <string>
#include <cstring>
#include "math3d/math3d.h"

#include "pbge/pbge.h"

#include "Ellipsoids.h"

Ellipsoids::Ellipsoids(pbge::GraphicAPI * _gfx) {
    this->sphere = pbge::Geometrics::createSphere(1.0f, 3, _gfx);
    this->gfx = _gfx;
}

pbge::ModelCollection * Ellipsoids::createEllipsoids(unsigned number_of_ellipsoids, math3d::matrix44 * transforms) {
    pbge::TextureBuffer * tex = gfx->getFactory()->createTextureBuffer(number_of_ellipsoids * sizeof(math3d::matrix44));
    void * texData = tex->getBuffer()->map(pbge::Buffer::WRITE_ONLY);
    memcpy(texData, transforms, number_of_ellipsoids * sizeof(math3d::matrix44));
    tex->getBuffer()->unmap();
    texData = NULL;
    tex->setInternalFormat(pbge::Texture::FLOAT, pbge::Texture::RGBA);
    pbge::ModelCollection * ellipsoids = new pbge::ModelCollection(sphere);
    ellipsoids->setNumberOfInstances(number_of_ellipsoids);

    pbge::UniformBufferSampler * uniform = ellipsoids->getUniformSet()->getBufferSampler("transforms");
    uniform->setValue(tex);

	ellipsoids->setRenderPassProgram(gfx->getFactory()->createProgramFromString(
        "#version 150\n"
		"uniform samplerBuffer transforms;\n"
        "uniform mat4 pbge_ModelViewMatrix;\n"
        "uniform mat4 pbge_ProjectionMatrix;\n"
		"out vec4 position;\n"
		"out vec3 normal;\n"
		"out vec4 lightPosition;\n"
        "in  vec4 pbge_Vertex;\n"
		"void main() {\n"
		"   const vec4 light_position = vec4(16,16,16,1);\n"
		"   int index = gl_InstanceID * 4;\n"
		"   vec4 col1 = texelFetch(transforms, index);\n"
		"   vec4 col2 = texelFetch(transforms, index + 1);\n"
		"   vec4 col3 = texelFetch(transforms, index + 2);\n"
		"   vec4 col4 = texelFetch(transforms, index + 3);\n"
		"   vec3 color = vec3(col1.w,col2.w,col3.w);\n"
		"   col1 = vec4(col1.xyz, 0);\n"
		"   col2 = vec4(col2.xyz, 0);\n"
		"   col3 = vec4(col3.xyz, 0);\n"
		"   col4 = vec4(col4.xyz, 1);\n"
		"   mat4 transformation = mat4(col1, col2, col3, col4);\n"
		"   mat4 t = pbge_ModelViewMatrix * transformation;\n"
		"   vec4 _normal = inverse(transpose(t)) * pbge_Vertex;\n"
		"   normal = normalize(_normal.xyz);\n"
		"   position = t * pbge_Vertex;\n"
		"   lightPosition = t * light_position;\n"
		"   gl_Position = pbge_ProjectionMatrix * position;\n"
		"   gl_FrontColor = vec4(color, 1.0);\n"
		"}",
        "in vec4 position;\n"
		"in vec3 normal;\n"
		"in vec4 lightPosition;\n"
		"void main() {\n"
		"   vec4 diffuseColor = gl_Color;\n"
		"   vec4 lightDiffuseColor = vec4(1.0,1.0,1,1);\n"
		"   vec3 lightDir = normalize((lightPosition - position).xyz);\n"
		"   float intensity = max(0.0, dot(lightDir, normal));\n"
		"   gl_FragData[0] = vec4(diffuseColor.rgb * lightDiffuseColor.rgb * intensity + 0.2, gl_Color.a);\n"
		"}"
        ));
    ellipsoids->setDepthPassProgram(gfx->getFactory()->createProgramFromString(
        "#version 140\n"
		"#extension GL_EXT_gpu_shader4: enable\n"
        "#extension GL_ARB_draw_instanced: enable\n"
        "uniform samplerBuffer transforms;\n"
        "uniform mat4 pbge_ModelViewProjectionMatrix;\n"
        "in  vec4 pbge_Vertex;\n"
        "void main() {\n"
        "   int index = gl_InstanceIDARB * 4;\n"
        "   vec4 col1 = texelFetch(transforms, index);\n"
        "   vec4 col2 = texelFetch(transforms, index + 1);\n"
        "   vec4 col3 = texelFetch(transforms, index + 2);\n"
        "   vec4 col4 = texelFetch(transforms, index + 3);\n"
		"   col1 = vec4(col1.xyz, 0);\n"
		"   col2 = vec4(col2.xyz, 0);\n"
		"   col3 = vec4(col3.xyz, 0);\n"
		"   col4 = vec4(col4.xyz, 1);\n"
        "   mat4 transformation = mat4(col1, col2, col3, col4);\n"
        "   gl_Position = pbge_ModelViewProjectionMatrix * transformation * pbge_Vertex;\n"
        "}", ""));
    return ellipsoids;
}
<|endoftext|>


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

#include <stdafx.h>
#include "DialogOverlay.h"
#include "Colors.h"
#include "Screen.h"
#include "Text.h"

using namespace cursespp;

#define HORIZONTAL_PADDING 4
#define VERTICAL_PADDING 2

DialogOverlay::DialogOverlay() {
    this->SetFrameVisible(true);
    this->SetFrameColor(CURSESPP_OVERLAY_FRAME);
    this->SetContentColor(CURSESPP_OVERLAY_BACKGROUND);

    this->width = this->height = 0;
    this->autoDismiss = true;

    this->shortcuts.reset(new ShortcutsWindow());
    this->shortcuts->SetAlignment(text::AlignRight);
    this->AddWindow(this->shortcuts);
}

DialogOverlay::~DialogOverlay() {
}

void DialogOverlay::Layout() {
    this->RecalculateSize();

    if (this->width > 0 && this->height > 0) {
        this->MoveAndResize(
            HORIZONTAL_PADDING,
            VERTICAL_PADDING,
            this->width,
            this->height + 2);

        this->shortcuts->MoveAndResize(
            HORIZONTAL_PADDING + 1,
            VERTICAL_PADDING + this->height,
            this->GetContentWidth(),
            1);

        this->Redraw();
    }
}

DialogOverlay& DialogOverlay::SetTitle(const std::string& title) {
    this->title = title;
    this->RecalculateSize();
    this->Layout();
    this->Repaint();
    return *this;
}

DialogOverlay& DialogOverlay::SetMessage(const std::string& message) {
    this->message = message;
    this->width = 0; /* implicitly triggers a new BreakLines() */
    this->RecalculateSize();
    this->Layout();
    this->Repaint();
    return *this;
}

DialogOverlay& DialogOverlay::SetAutoDismiss(bool dismiss) {
    this->autoDismiss = dismiss;
    return *this;
}

DialogOverlay& DialogOverlay::AddButton(
    const std::string& rawKey,
    const std::string& key,
    const std::string& caption,
    ButtonCallback callback)
{
    this->shortcuts->AddShortcut(key, caption);
    this->buttons[rawKey] = callback;
    this->Layout();
    this->Repaint();
    return *this;
}

bool DialogOverlay::KeyPress(const std::string& key) {
    auto it = this->buttons.find(key);

    if (it != this->buttons.end()) {
        ButtonCallback cb = it->second;

        if (cb) {
            cb(key);
        }

        if (this->autoDismiss) {
            OverlayStack* overlays = this->GetOverlayStack();
            if (overlays) {
                overlays->Remove(this);
            }
        }

        return true;
    }

    return LayoutBase::KeyPress(key);
}

void DialogOverlay::OnVisibilityChanged(bool visible) {
    if (visible) {
        this->Redraw();
    }
}

void DialogOverlay::RecalculateSize() {
    int lastWidth = this->width;

    this->width = std::max(0, Screen::GetWidth() - (HORIZONTAL_PADDING * 2));

    if (lastWidth != this->width) {
        /* the "-2" is for left and right padding */
        messageLines = text::BreakLines(this->message, this->width - 2);
    }

    this->height = 0; /* top padding */
    this->height += (this->title.size()) ? 2 : 0;
    this->height += (this->messageLines.size()) ? messageLines.size() + 1 : 0;
    this->height += 1; /* shortcuts */
}

void DialogOverlay::Redraw() {
    if (this->width <= 0 || this->height <= 0) {
        return;
    }

    WINDOW* c = this->GetContent();

    const int currentX = 1;
    int currentY = 0;

    if (this->title.size()) {
        wmove(c, currentY, currentX);
        wattron(c, A_BOLD);
        wprintw(c, text::Ellipsize(this->title, this->width - 2).c_str());
        wattroff(c, A_BOLD);
        currentY += 2;
    }

    if (this->message.size()) {
        for (size_t i = 0; i < messageLines.size(); i++) {
            wmove(c, currentY, currentX);
            wprintw(c, this->messageLines.at(i).c_str());
            ++currentY;
        }
    }
}<commit_msg>Small correction to padding calculation when breaking lines in DialogOverlay.<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//    * Neither the name of the author nor the names of other contributors may
//      be used to endorse or promote products derived from this software
//      without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////

#include <stdafx.h>
#include "DialogOverlay.h"
#include "Colors.h"
#include "Screen.h"
#include "Text.h"

using namespace cursespp;

#define HORIZONTAL_PADDING 4
#define VERTICAL_PADDING 2

DialogOverlay::DialogOverlay() {
    this->SetFrameVisible(true);
    this->SetFrameColor(CURSESPP_OVERLAY_FRAME);
    this->SetContentColor(CURSESPP_OVERLAY_BACKGROUND);

    this->width = this->height = 0;
    this->autoDismiss = true;

    this->shortcuts.reset(new ShortcutsWindow());
    this->shortcuts->SetAlignment(text::AlignRight);
    this->AddWindow(this->shortcuts);
}

DialogOverlay::~DialogOverlay() {
}

void DialogOverlay::Layout() {
    this->RecalculateSize();

    if (this->width > 0 && this->height > 0) {
        this->MoveAndResize(
            HORIZONTAL_PADDING,
            VERTICAL_PADDING,
            this->width,
            this->height + 2);

        this->shortcuts->MoveAndResize(
            HORIZONTAL_PADDING + 1,
            VERTICAL_PADDING + this->height,
            this->GetContentWidth(),
            1);

        this->Redraw();
    }
}

DialogOverlay& DialogOverlay::SetTitle(const std::string& title) {
    this->title = title;
    this->RecalculateSize();
    this->Layout();
    this->Repaint();
    return *this;
}

DialogOverlay& DialogOverlay::SetMessage(const std::string& message) {
    this->message = message;
    this->width = 0; /* implicitly triggers a new BreakLines() */
    this->RecalculateSize();
    this->Layout();
    this->Repaint();
    return *this;
}

DialogOverlay& DialogOverlay::SetAutoDismiss(bool dismiss) {
    this->autoDismiss = dismiss;
    return *this;
}

DialogOverlay& DialogOverlay::AddButton(
    const std::string& rawKey,
    const std::string& key,
    const std::string& caption,
    ButtonCallback callback)
{
    this->shortcuts->AddShortcut(key, caption);
    this->buttons[rawKey] = callback;
    this->Layout();
    this->Repaint();
    return *this;
}

bool DialogOverlay::KeyPress(const std::string& key) {
    auto it = this->buttons.find(key);

    if (it != this->buttons.end()) {
        ButtonCallback cb = it->second;

        if (cb) {
            cb(key);
        }

        if (this->autoDismiss) {
            OverlayStack* overlays = this->GetOverlayStack();
            if (overlays) {
                overlays->Remove(this);
            }
        }

        return true;
    }

    return LayoutBase::KeyPress(key);
}

void DialogOverlay::OnVisibilityChanged(bool visible) {
    if (visible) {
        this->Redraw();
    }
}

void DialogOverlay::RecalculateSize() {
    int lastWidth = this->width;

    this->width = std::max(0, Screen::GetWidth() - (HORIZONTAL_PADDING * 2));

    if (lastWidth != this->width) {
        messageLines = text::BreakLines(this->message, this->width - 3);
    }

    this->height = 0; /* top padding */
    this->height += (this->title.size()) ? 2 : 0;
    this->height += (this->messageLines.size()) ? messageLines.size() + 1 : 0;
    this->height += 1; /* shortcuts */
}

void DialogOverlay::Redraw() {
    if (this->width <= 0 || this->height <= 0) {
        return;
    }

    WINDOW* c = this->GetContent();

    const int currentX = 1;
    int currentY = 0;

    if (this->title.size()) {
        wmove(c, currentY, currentX);
        wattron(c, A_BOLD);
        wprintw(c, text::Ellipsize(this->title, this->width - 2).c_str());
        wattroff(c, A_BOLD);
        currentY += 2;
    }

    if (this->message.size()) {
        for (size_t i = 0; i < messageLines.size(); i++) {
            wmove(c, currentY, currentX);
            wprintw(c, this->messageLines.at(i).c_str());
            ++currentY;
        }
    }
}<|endoftext|>


<commit_before>// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "wfa/virtual_people/core/model/utils/update_matrix_helper.h"

#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "src/main/proto/wfa/virtual_people/common/model.pb.h"
#include "wfa/virtual_people/core/model/utils/constants.h"
#include "wfa/virtual_people/core/model/utils/distributed_consistent_hashing.h"
#include "wfa/virtual_people/core/model/utils/field_filters_matcher.h"
#include "wfa/virtual_people/core/model/utils/hash_field_mask_matcher.h"

namespace wfa_virtual_people {

absl::StatusOr<MatrixIndexes> SelectFromMatrix(
    const HashFieldMaskMatcher* hash_matcher,
    const FieldFiltersMatcher* filters_matcher,
    const std::vector<std::unique_ptr<DistributedConsistentHashing>>&
        row_hashings,
    absl::string_view random_seed,
    const LabelerEvent& event) {
  int column_index = kNoMatchingIndex;
  if (hash_matcher) {
    column_index = hash_matcher->GetMatch(event);
  } else if (filters_matcher) {
    column_index = filters_matcher->GetFirstMatch(event);
  } else {
    return absl::InternalError("No column matcher is set.");
  }
  if (column_index == kNoMatchingIndex) {
    return MatrixIndexes({kNoMatchingIndex, kNoMatchingIndex});
  }
  int row_index = row_hashings[column_index]->Hash(
      absl::StrCat(random_seed, event.acting_fingerprint()));
  return MatrixIndexes({column_index, row_index});
}

}  // namespace wfa_virtual_people
<commit_msg>Add defensive check for vector index.<commit_after>// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "wfa/virtual_people/core/model/utils/update_matrix_helper.h"

#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "src/main/proto/wfa/virtual_people/common/model.pb.h"
#include "wfa/virtual_people/core/model/utils/constants.h"
#include "wfa/virtual_people/core/model/utils/distributed_consistent_hashing.h"
#include "wfa/virtual_people/core/model/utils/field_filters_matcher.h"
#include "wfa/virtual_people/core/model/utils/hash_field_mask_matcher.h"

namespace wfa_virtual_people {

absl::StatusOr<MatrixIndexes> SelectFromMatrix(
    const HashFieldMaskMatcher* hash_matcher,
    const FieldFiltersMatcher* filters_matcher,
    const std::vector<std::unique_ptr<DistributedConsistentHashing>>&
        row_hashings,
    absl::string_view random_seed,
    const LabelerEvent& event) {
  int column_index = kNoMatchingIndex;
  if (hash_matcher) {
    column_index = hash_matcher->GetMatch(event);
  } else if (filters_matcher) {
    column_index = filters_matcher->GetFirstMatch(event);
  } else {
    return absl::InternalError("No column matcher is set.");
  }
  if (column_index == kNoMatchingIndex) {
    return MatrixIndexes({kNoMatchingIndex, kNoMatchingIndex});
  }
  if (column_index < 0 || column_index >= row_hashings.size()) {
    return absl::InternalError("The returned index is out of range.");
  }
  int row_index = row_hashings[column_index]->Hash(
      absl::StrCat(random_seed, event.acting_fingerprint()));
  return MatrixIndexes({column_index, row_index});
}

}  // namespace wfa_virtual_people
<|endoftext|>