Friday, March 1, 2013

A Simple Attribute File


I was looking for a way to store object attribute data, and came up with this tiny class:

class cAttribFile
{
public:
    typedef std::string tID;
    typedef std::string tVal;
    typedef std::map<tID, tVal> tAttrib;
    typedef std::map<tID, cAttribFile> tNode;

    std::string &operator()(const std::string &s) { return mAttrib[s]; }
    cAttribFile &operator[](const std::string &s) { return mNode[s]; }

    tAttrib mAttrib;
    tNode mNode;
};


With the addition of a few simple parsing functions, this has actually been pretty useful.

In basic terms, each cAttribFile node has a set of named attributes (map from ID to Value), and a set of named nodes (map from ID to another cAttribFile).

This lets me parse a file like this, where an '=' defines a new attribute, and braces define a new node:

Name = Explosion
MaxParticles = 50

Smoke

{
    Duration = 1
    Loop = false
    InitialParticles = 5
    Color
    {
        Type = Lerp
        V0 = 1,0.5,0,1
        V1 = 1,0.5,0,0
    }
}
Then I can refer to this data like this:
duration = attr_file["Smoke"]("Duration");
color_interpolation = attr_file["Smoke"]["Color"]("Type");
where [] operations refer to nodes and () operations refer to attributes.

Adding some iterators over attributes/nodes makes this very flexible.

OK, so it's not ALL that exciting, but it's a very simple class and file format that can be used to hold all sorts of data, without the mind-numbing aesthetics of an XML file.

2 comments:

  1. Very cool Craig! I like the syntax for getting attributes; very clever use of operator overloading in C++.

    How do you handle types? Since everything comes in as a string, I assume the calling code does the casting manually?

    ReplyDelete
  2. Thanks! Yes - keeping everything as a string makes it really easy to work with, and it's pretty easy to convert to pretty much anything else with a simple library of functions - int, float, bool, vector, quaternion, color, etc.

    ReplyDelete