ConsoleCode         Creating a Scalable Console

This code is based on the article on GameDev.net "Creating a Scalable Console System with STL" with some minor changes and feature enhancements. I have also included a sample that uses this console system. Both the console code and the sample code have been tested, but I can't guarantee that they are totally bug free so if you find one please update this page with the fix!

Table of contents

Base Class

Console.h

#ifndef _CONSOLE_H_
#define _CONSOLE_H_

// Disable signed/unsigned mismatch warning
#pragma warning(disable : 4018)
// Disable conversion from 'size_t' to 'int', possible loss of data warning
#pragma warning(disable : 4267)

#include <vector>
#include <list>
#include <sstream>
#include <assert.h>

enum ConsoleItemType
{
    CTYPE_UCHAR,
    CTYPE_CHAR,
    CTYPE_UINT,
    CTYPE_INT,
    CTYPE_FLOAT,
    CTYPE_STRING,
    CTYPE_FUNCTION
};

typedef void (*ConsoleFunction)(const std::vector<std::string> &);

typedef struct {
    std::string name;
    ConsoleItemType type;
    union
    {
        ConsoleFunction function;
        void *variablePointer;
    };
} ConsoleItem;

typedef std::list<ConsoleItem> ItemList;

class Console
{
public:
    Console(int commandHistory, int textHistory, bool echo, ConsoleFunction defaultFunction, int lineIndex);
    virtual ~Console();

    void addItem(const std::string &strName, void *pointer, ConsoleItemType type);
    void deleteItem(const std::string &strName);
    void print(const std::string &strText);
    void setCommandBufferSize(int size);
    int getCommandBufferSize() { return commandBufferSize; }
    void clearCommandBuffer() { commandBuffer.clear(); }
    void setOutputBufferSize(int size);
    int getOutputBufferSize() { return textBufferSize; }
    void clearOutputBuffer() { textBuffer.clear(); }
    std::string getPrevCommand(int index);
    void setDefaultCommand(ConsoleFunction def) { defaultCommand = def; }
    void parseCommandQueue();
    void sendMessage(std::string command);
    void sendImmediateMessage(std::string command) { parseCommandLine(command); }

    virtual void render() = 0;

protected:
    std::list<std::string> textBuffer;
    std::vector<std::string> commandBuffer;

private:
    bool parseCommandLine(std::string commandLine);

    bool commandEcho;
    int lineIndex;
    int commandBufferSize;
    int textBufferSize;
    ConsoleFunction defaultCommand;
    ItemList itemList;
    std::list<std::string> commandQueue;
};
#endif

Console.cpp

#include "Console.h"

Console::Console(int commandHistory, int textHistory, bool echo, ConsoleFunction defaultFunction, int commandlineIndex)
{
    commandBufferSize = commandHistory;
    textBufferSize = textHistory;
    commandEcho = echo;
    defaultCommand = defaultFunction;
    lineIndex = commandlineIndex;
}

Console::~Console()
{}

void Console::print(const std::string & strTxt)
{
    // push it
    textBuffer.push_back(strTxt);

    // if we are out of bounds
    if(textBuffer.size() > textBufferSize)
    textBuffer.pop_front();
}

bool Console::parseCommandLine(std::string commandLine)
{
    std::ostringstream out;
    std::string::size_type index = 0;
    std::vector<std::string> arguments;
    std::list<ConsoleItem>::const_iterator iter;

    // add to text buffer
    if(commandEcho)
    {
        print(commandLine);
    }

    // add to commandline buffer
    commandBuffer.push_back(commandLine);
    if(commandBuffer.size() > commandBufferSize) commandBuffer.erase(commandBuffer.begin());

    // tokenize
    while(index != std::string::npos)
    {
        // push word
        std::string::size_type nextSpace = commandLine.find(' ', index);
        arguments.push_back(commandLine.substr(index, nextSpace));

        // increment index
        if(nextSpace != std::string::npos) index = nextSpace + 1;
        else break;
    }

    // execute
    for(iter = itemList.begin(); iter != itemList.end(); ++iter)
    {
        if(iter->name == arguments[0])
        {
            switch(iter->type)
            {
            case CTYPE_UCHAR:
                if(arguments.size() > 2)
                {
                    return true;
                }
                else if(arguments.size() == 1)
                {
                    out.str("");
                    out << (*iter).name << " = " << *((unsigned char *)(*iter).variablePointer);
                    print(out.str());
                    return true;
                }
                else if(arguments.size() == 2)
                {
                    *((unsigned char *)(*iter).variablePointer) = (unsigned char) atoi(arguments[1].c_str());
                    return true;
                }
                break;

            case CTYPE_CHAR:
                if(arguments.size() > 2)
                {
                    return true;
                }
                else if(arguments.size() == 1)
                {
                    out.str("");
                    out << (*iter).name << " = " << *((char *)(*iter).variablePointer);
                    print(out.str());
                    return true;
                }
                else if(arguments.size() == 2)
                {
                    *((char *)(*iter).variablePointer) = (char) atoi(arguments[1].c_str());
                    return true;
                }
                break;

            case CTYPE_UINT:
                if(arguments.size() > 2)
                {
                    return true;
                }
                else if(arguments.size() == 1)
                {
                    out.str("");
                    out << (*iter).name << " = " << *((unsigned int *)(*iter).variablePointer);
                    print(out.str());
                    return true;
                }
                if(arguments.size() == 2)
                {
                    *((unsigned int *)(*iter).variablePointer) = (unsigned int) atoi(arguments[1].c_str());
                    return true;
                }
                break;

            case CTYPE_INT:
                if(arguments.size() > 2)
                {
                    return true;
                }
                else if(arguments.size() == 1)
                {
                    out.str("");
                    out << (*iter).name << " = " << *((int *)(*iter).variablePointer);
                    print(out.str());
                    return true;
                }
                if(arguments.size() == 2)
                {
                    *((int *)(*iter).variablePointer) = (int) atoi(arguments[1].c_str());
                    return true;
                }
                break;

            case CTYPE_FLOAT:
                if(arguments.size() > 2)
                {
                    return true;
                }
                else if(arguments.size() == 1)
                {
                    out.str("");
                    out << (*iter).name << " = " << *((float *)(*iter).variablePointer);
                    print(out.str());
                    return true;
                }
                if(arguments.size() == 2)
                {
                    *((float *)(*iter).variablePointer) = (float)atof(arguments[1].c_str());
                    return true;
                }
                break;

            case CTYPE_STRING:
                if(arguments.size() == 1)
                {
                    out.str("");
                    out << (*iter).name << " = " << *(std::string *)(*iter).variablePointer;
                    print(out.str());
                    return false;
                }
                else if(arguments.size() > 1)
                {
                    // reset variable
                    *((std::string *)(*iter).variablePointer) = "";

                    // add new string
                    for(int i = 1; i < arguments.size(); ++i)
                    {
                        *((std::string *)(*iter).variablePointer) += arguments[i];
                    }
                    return true;
                }
                break;

            case CTYPE_FUNCTION:
                (*iter).function(arguments);
                return true;
                break;

            default:
                defaultCommand(arguments);
                return false;
                break;
            }
        }
    }

    // Couldn't match the command
    defaultCommand(arguments);
    return false;
}

void Console::sendMessage(std::string command)
{
    // If you are using multiple threads this is where you 
    // should grab the semaphore to prevent data corruption.
    commandQueue.push_back(command);
    // Release the semaphore here.
}

void Console::addItem(const std::string & strName, void *pointer, ConsoleItemType type)
{
    ConsoleItem it;

    // fill item properties
    it.name = strName;
    it.type = type;

    // address
    if(type != CTYPE_FUNCTION)
    {
        it.variablePointer = pointer;
    }
    else
    {
        it.function = (ConsoleFunction) pointer;
    }

    // add item
    itemList.push_back(it);
}

void Console::deleteItem(const std::string & strName)
{
    ItemList::iterator iter;
    
    // find item
    for (iter = itemList.begin(); iter != itemList.end(); ++iter)
    {
        if (iter->name == strName)
        {
            itemList.erase(iter);
            break;
        }
    }
}

void Console::parseCommandQueue()
{
    std::list<std::string>::iterator it;

    for(it = commandQueue.begin(); it != commandQueue.end(); ++it)
    {
        parseCommandLine(*it);
    }
    commandQueue.clear();
}

void Console::setOutputBufferSize(int size)
{
    textBufferSize = size;

    // remove any extra line
    if(textBuffer.size() > textBufferSize)
    {
        std::list<std::string>::iterator it;
        int diff = textBuffer.size() - textBufferSize;
        for(int i = 0; i < diff; i++)
        {
            textBuffer.erase(textBuffer.begin());
        }
    }
}

void Console::setCommandBufferSize(int size)
{
    commandBufferSize = size;

    // remove any extra line
    if(commandBuffer.size() > commandBufferSize)
    {
        std::vector<std::string>::iterator it;
        it = commandBuffer.end() - commandBufferSize;
        commandBuffer.erase(commandBuffer.begin(), it);
    }
}

std::string Console::getPrevCommand(int i)
{
    // increment line index
    lineIndex += i;

    // error correct line index
    if(lineIndex < 0)
    {
        lineIndex = 0;
    }
    else if(lineIndex >= textBuffer.size())
    {
        lineIndex = textBuffer.size() - 1;
    }

    // set command line
    if(!commandBuffer.empty()) return commandBuffer[lineIndex];
    else return "";
}

Sub-Class

Now we will start with the sample code. The idea is that you use the previous code as a base class and inherit from it in order to override the render() method so that you can draw the console in whatever way is appropriate for your application. In this sample I have just created a "Windows Console Application" and I use stdin and stdout for the input and output. Soon I hope to add a sample that uses CEGUI to render the console.

OgreConsole.h

#ifndef _OGRE_CONSOLE_H_
#define _OGRE_CONSOLE_H_

#include "Console.h"
#include <OgreSingleton.h>
#include <iostream>

class OgreConsole : public Console, public Ogre::Singleton
{
public:
    OgreConsole(int commandHistory = 20, int textHistory = 50, bool echo = false, 
        ConsoleFunction defaultFunction = NULL, int commandlineIndex = 0);
    ~OgreConsole();

    static OgreConsole* getSingletonPtr(void);
    static OgreConsole& getSingleton(void);

    void render();
};

#endif

OgreConsole.cpp

#include "OgreConsole.h"

OgreConsole::OgreConsole(int commandHistory, int textHistory, bool echo, 
        ConsoleFunction defaultFunction, int commandlineIndex)
        :Console(commandHistory, textHistory, echo, defaultFunction, commandlineIndex)
{
}

OgreConsole::~OgreConsole()
{
}

template<> OgreConsole* Ogre::Singleton<OgreConsole>::ms_Singleton = 0;

OgreConsole* OgreConsole::getSingletonPtr(void)
{
    return ms_Singleton;
}

OgreConsole& OgreConsole::getSingleton(void)
{  
    assert(ms_Singleton);
    return (*ms_Singleton);  
}

void OgreConsole::render()
{
    for(std::list<std::string>::const_iterator iter = textBuffer.begin(); iter != textBuffer.end(); ++iter)
    {
        std::cout << *iter << "\n";
    }
}

Usage

Now here is where we actually set up and use the console. As you can see it's a really clean design! You can add variables or commands by using the addItem() method and passing it the string that the user needs to enter to access that variable or method, a pointer to the variable or method and the type. You can see in the code below that I add two variable one is a string and the other is a float, and three commands. When a variable is accessed if there are no arguments then it prints out the current value of the variable, if there is one argument then it sets the variable equal to that argument if there are two or more then it quietly ignores that command. When a command is entered it determines the appropriate function to call and then passes anything else that was entered at the prompt as a std::vector<std::string>. You are required to set a "default command" which is the method that will be called if it fails to recognise the command. In th case of this example the default command just informs the user that the command was not recognised.

main.cpp

#include "OgreConsole.h"
#include <iostream>

void errorFunction(const std::vector<std::string> & args)
{
    OgreConsole::getSingleton().print("Unknown command " + args[0]);
}

void quit(const std::vector<std::string> & args)
{
    exit(0);
}

void setHistory(const std::vector<std::string> & args)
{
    OgreConsole::getSingleton().setOutputBufferSize(atoi(args[1].c_str()));
}

void removeCommand(const std::vector<std::string> & args)
{
    OgreConsole::getSingleton().deleteItem(args[1]);
}

void main()
{
    OgreConsole *console = new OgreConsole();
    std::string command;

    static std::string username;
    static float health;
    console->addItem("username", &username, CTYPE_STRING);
    console->addItem("health", &health, CTYPE_FLOAT);
    console->addItem("/quit", quit, CTYPE_FUNCTION);
    console->addItem("/history", setHistory, CTYPE_FUNCTION);
    console->addItem("/remove", removeCommand, CTYPE_FUNCTION);
    console->setDefaultCommand(errorFunction);

    while(1)
    {
        std::getline(std::cin, command);
        console->sendImmediateMessage(command);
        console->render();
    }
}