Friday, June 21, 2013

Setting Settings of Arbitrary Types in C++

It's been a while, but things are still slowly moving along. Working a 40-hour week doing web development leaves me with little time or energy to make game development progress!

I've begun a new iteration of my rendering engine, IronClad, now dubbed Zenderer. Over the past few weeks I've slowly been adding various modules and utilities to it, such as audio, file parsing, and asset management. Nothing is being rendered on the screen just yet, but that's next!

This post is primarily dedicated to creating a settings module that will accept arbitrary types, such as ints, floats, std::strings, and even bools. The final result will allow something like this:

// Optional file to parse immediately
CSettings Settings("SettingsFile.dat");
Settings.Init();

// Set settings
Settings["WINDOW_WIDTH"]    = 800;
Settings["WINDOW_HEIGHT"]   = 600;
Settings["WINDOW_NAME"]     = "Zenderer Window";
Settings["WINDOW_FS"]       = false;
Settings["SCROLL_SPEED"]    = 5.2;
Settings["FRAME_RATE"]      = 60;

// Retrieve settings
if((size_t)Settings["FRAME_RATE"] < 20)
{
    std::cerr << "[FATAL] Frame rate is too low for adequate gameplay.\n";
    exit(1);
}

// Change settings, regardless of type
Settings["WINDOW_FS"] = true;
Settings["WINDOW_NAME"] = 42.335f;

We will do this by creating an extremely dynamic COption class that accepts all different types for values and turns them into strings behind the scenes.