
#include "PhyObj.h"
#include <vector>
#include <string>
#include <sstream>
using namespace std;

#define WHITESPACE " \t\r\n\f"

/********** static utility functions **********/
static string trim(const string & orig)
{
    string result = orig;
    size_t pos = result.find_first_not_of(WHITESPACE);
    if (pos == string::npos)
    {
        result = "";
    }
    else
    {
        if (pos > 0)
            result = result.substr(pos, result.length() - pos);
        pos = result.find_last_not_of(WHITESPACE);
        if (pos < result.length() - 1)
            result = result.substr(0, pos + 1);
    }
    return result;
}

/********** PhyObj::Geom functions **********/
PhyObj::Geom::Geom()
{
    m_type = NONE;
}

PhyObj::Geom::Geom(PhyObj::GeomType type, refptr< vector<float> > args)
{
    m_type = type;
    m_args = args;
}


/********** PhyObj functions **********/
void PhyObj::load(const unsigned char *data, unsigned int size)
{
    string str((char *) data, size);
    stringstream istr(str, ios_base::in);
    while (!istr.eof())
    {
        string line;
        getline(istr, line);
        line = trim(line);
        if (line == "" || line[0] == '#')
            continue;
        size_t pos = line.find_first_of(WHITESPACE);
        if (pos == string::npos)
            continue;
        string type = line.substr(0, pos);
        pos = line.find("\"", pos);
        if (pos == string::npos)
            continue;
        size_t pos2 = line.find("\"", pos + 1);
        if (pos2 == string::npos)
            continue;
        string name = line.substr(pos + 1, pos2 - pos - 1);
        pos = pos2 + 1;
        refptr< vector<float> > args = new vector<float>();
        for (;;)
        {
            pos = line.find_first_not_of(WHITESPACE, pos);
            if (pos == string::npos)
                break;
            pos2 = line.find_first_of(WHITESPACE, pos);
            string n = line.substr(pos, pos2 - pos);
            float f = atof(n.c_str());
            args->push_back(f);
            if (pos2 == string::npos)
                break;
            pos = pos2 + 1;
        }
        GeomType geom_type = NONE;
        if      (type == "cube")
        {
            geom_type = BOX;
        }
        else if (type == "sphere")
        {
            geom_type = SPHERE;
        }
        else if (type == "capsule")
        {
            geom_type = CAPSULE;
        }
        else if (type == "plane")
        {
            geom_type = PLANE;
        }
        if (geom_type != NONE)
        {
            m_geoms.push_back(new Geom(geom_type, args));
        }
    }
}
