#include <stdio.h>
#include <GL/glut.h>
#include <Inventor/SoInteraction.h>
#include <Inventor/SoDB.h>
#include <Inventor/nodes/SoNodes.h>
#include <Inventor/actions/SoGLRenderAction.h>
#include "InventorModel.h"

namespace dms
{

bool InventorModel::inventorInitialized_ = false;

void InventorModel::initialize(void)
    {
    SoInteraction::init();
    inventorInitialized_ = true;
    }


InventorModel::InventorModel(char *filename)
    {
    if (!inventorInitialized_)
        initialize();
    ivRoot_ = new SoSeparator;
    ivRoot_->ref();
    if (filename)
        loadFile(filename);
    }


void InventorModel::loadFile(char *filename)
    {
    ivViewport_ = new SbViewportRegion(glutGet(GLUT_WINDOW_WIDTH),
                                       glutGet(GLUT_WINDOW_HEIGHT));
    ivRender_ = new SoGLRenderAction(*ivViewport_);

    SoInput in;
    if (!in.openFile(filename))
        return;
    while (1)
        {
        SoNode *node;
        if (!SoDB::read(&in, node))
            break;
        if (node)
            ivRoot_->addChild(node);
        else
            break;
        }
    in.closeFile();
    }


InventorModel::~InventorModel(void)
    {
    ivRoot_->unref();
    delete ivViewport_;
    delete ivRender_;
    }


void InventorModel::draw(void)
    {
    Object::draw();
    ivRender_->apply(ivRoot_);
    }

}
