/* Proto.C */

#include "Proto.H"
#include "error.H"

SFNode *Proto::instantiate(Proto *master)
{
  Proto *instance = new Proto(*this);
  instance->instantiate_interface(master);

  if (sceneGraph) {
    instance->master = instance;

    instance->namedNodes = namedNodes;
    for (int i=0; i<instance->namedNodes.size; i++) {
      // temporarly let namedNodes[i] behave as a "normal" unnamed node,
      // because otherwise, instantiate() would just return the SFNode *
      // stored in instance->namedNodes[i] (no instancing would be done).
      int j = namedNodes[i]->nameIndex;
      namedNodes[i]->nameIndex = -1;
      instance->namedNodes[i] = namedNodes[i]->instantiate(instance);
      namedNodes[i]->nameIndex = j;

      instance->namedNodes[i]->nameId = namedNodes[i]->nameId;
      instance->namedNodes[i]->nameIndex = namedNodes[i]->nameIndex;
    }

    instance->sceneGraph = sceneGraph->instantiate(instance);
  }

  return instance;
}

ostream& Proto::print(ostream& s)
{
  SFNode::print(s) << '\n';
  if (sceneGraph)
    s << *sceneGraph << " # end " << typeId << '\n';
  else 
    s << "# no proto scene graph\n";
  return s;
}

void Proto::render(void)
{
  if (sceneGraph) {
    sceneGraph->render();
  }
}

void Proto::synchronize(void)
{
  SFNode::synchronize();
  if (sceneGraph) {
    sceneGraph->synchronize();
  }
}
