Example #1
0
void
Tree::search_recursive(const ResourceName &resName,
		       const NodeRefPtr node,
		       std::vector<PDRefCntPtr> &results,
		       bool usePatterns) const {

    am_resource_match_t compRes;
    compRes = compare(node->getPolicyDecision()->getName(),
		      resName,
		      usePatterns);

    std::list<NodeRefPtr>::const_iterator iter;
    switch(compRes) {
    case AM_EXACT_MATCH:
	results.push_back(node->getPolicyDecision());
	break;
    case AM_EXACT_PATTERN_MATCH:
	results.push_back(node->getPolicyDecision());
	// fall through to the following
    case AM_SUB_RESOURCE_MATCH:
    case AM_NO_MATCH:
	for(iter = node->begin(); iter != node->end(); iter++) {
	    search_recursive(resName, *iter, results, usePatterns);
	}
	break;
    default:
	break;
    }
    return;
}
Example #2
0
static
NodeRefPtr MakeChain(size_t n) {
    if (n == 0)
        return TfNullPtr;
    else {
        NodeRefPtr root = Node::New();
        root->SetChild(MakeChain(n-1));
        return root;
    }
}
Example #3
0
bool
Tree::markStale(const ResourceName & resName, bool recursive) {
    SearchResult result = find(rootNode, resName, false);

    if(result.first == AM_EXACT_MATCH) {
	NodeRefPtr delNode = result.second;
	delNode->markNodeStale(recursive);
	return true;
    }
    return false;
}
Example #4
0
void
Tree::outdatePolicyDecisions(const std::string &resName) {
    SearchResult result = find(rootNode, resName, false);
    NodeRefPtr delNode = result.second;
    if(result.first == AM_EXACT_MATCH) {
	NodeRefPtr parent = delNode->getParent();
	delNode->markNodeStale(true);
	if(parent != NULL) {
	    parent->removeChildOnly(delNode);
	}
    }
    return;
}
void SceneGraphTreeModel::removeNode(NodeUnrecPtr nodeToBeRemoved)
{

    NodeRefPtr parent = nodeToBeRemoved->getParent();

    TreePath pathOfNode = createPath(nodeToBeRemoved);
    if(parent!=NULL)
    {
        UInt32 ChildIndex(parent->findChild(nodeToBeRemoved));


        produceTreeNodesWillBeRemoved(pathOfNode.getParentPath(),std::vector<UInt32>(1, ChildIndex),std::vector<boost::any>(1, nodeToBeRemoved));
        parent->subChild(nodeToBeRemoved);
        produceTreeNodesRemoved(pathOfNode.getParentPath(),std::vector<UInt32>(1, ChildIndex),std::vector<boost::any>(1, nodeToBeRemoved));

        if(parent->getNChildren() == 0)
        {
            if(parent->getParent() != NULL)
            {
                std::vector<UInt32> childIndices;
                childIndices.push_back(parent->getParent()->findChild(parent));
                std::vector<boost::any> ChildUserObjects;
                for(UInt32 i(0) ; i< childIndices.size() ; ++i)
                {
                    ChildUserObjects.push_back(boost::any(NodeUnrecPtr(parent->getParent()->getChild(childIndices[i]))));
                }
                produceTreeNodesChanged(createPath(parent->getParent()), childIndices, ChildUserObjects);
            }
        }
    }
}
void showAll(PerspectiveCameraRefPtr TheCamera, NodeRefPtr Scene, Vec3f Up)
{
    //Make sure the volume is up to date for the Scene
    Scene->updateVolume();

    //Get the Minimum and Maximum bounds of the volume
    Vec3f min,max;
    Scene->getVolume().getBounds( min, max );
    Vec3f d = max - min;

    if(d.length() < Eps) //The volume is 0
    {
        //Default to a 1x1x1 box volume
        min.setValues(-0.5f,-0.5f,-0.5f);
        max.setValues( 0.5f, 0.5f, 0.5f);
        d = max - min;
    }

    Real32 dist = osgMax(d[0],d[1]) / (2 * osgTan(TheCamera->getFov() / 2.f));

    Pnt3f at((min[0] + max[0]) * .5f,(min[1] + max[1]) * .5f,(min[2] + max[2]) * .5f);
    Pnt3f from=at;
    from[2]+=(dist+fabs(max[2]-min[2])*0.5f); 

    //If the Camera Beacon is a node with a transfrom core
    if(TheCamera->getBeacon() != NULL &&
       TheCamera->getBeacon()->getCore() != NULL &&
       TheCamera->getBeacon()->getCore()->getType().isDerivedFrom(Transform::getClassType()))
    {
        Matrix m;

        if(!MatrixLookAt(m, from, at, Up))
        {
            dynamic_cast<Transform*>(TheCamera->getBeacon()->getCore())->setMatrix(m);
        }
    }

    //Set the camera to go from 1% of the object to 10 times its size
    Real32 diag = osgMax(osgMax(d[0], d[1]), d[2]);
    TheCamera->setNear (diag / 100.f);
    TheCamera->setFar  (10 * diag);
}
Example #7
0
/**
 * This function removes a node from a tree.
 * The function will fail if root node is being removed.
 */
bool
Tree::remove(const ResourceName &elem, bool recursive) {
    SearchResult result = find(rootNode, elem, false);


    if(result.first == AM_EXACT_MATCH) {
	NodeRefPtr delNode = result.second;
	// First get the parent.
	if(recursive) {
	    if(delNode->hasSubNodes()) {
		delNode->removeAllChildren();
	    }
	} else {
	    NodeRefPtr parent = delNode->getParent();

	    // Transfer all children of the node to be deleted
	    // to the parent.
	    if(parent != NULL) {
		parent->removeChildOnly(delNode);
	    } else {
		// if this is the root node we are trying to remove
		// the operation must fail.
		return false;
	    }
	}
    }
    rootNode->removeAllChildren();
    return true;
}
//////////////////////////////////////////////////////////////////////////
//! build a box
//////////////////////////////////////////////////////////////////////////
void buildBox(void)
{
    Vec3f Lengths((Real32)(rand()%2)+1.0, (Real32)(rand()%2)+1.0, (Real32)(rand()%2)+1.0);
    Matrix m;
    //create OpenSG mesh
    GeometryRefPtr box;
    NodeRefPtr boxNode = makeBox(Lengths.x(), Lengths.y(), Lengths.z(), 1, 1, 1);
    box = dynamic_cast<Geometry*>(boxNode->getCore());
    SimpleMaterialRefPtr box_mat = SimpleMaterial::create();
    box_mat->setAmbient(Color3f(0.0,0.0,0.0));
    box_mat->setDiffuse(Color3f(0.0,1.0 ,0.0));

    box->setMaterial(box_mat);

    TransformRefPtr boxTrans;
    NodeRefPtr boxTransNode = makeCoredNode<Transform>(&boxTrans);
    m.setIdentity();
    Real32 randX = (Real32)(rand()%10)-5.0;
    Real32 randY = (Real32)(rand()%10)-5.0;
    m.setTranslate(randX, randY, 10.0);
    boxTrans->setMatrix(m);


    //create ODE data
    PhysicsBodyRefPtr boxBody = PhysicsBody::create(physicsWorld);
    boxBody->setPosition(Vec3f(randX, randY, 10.0));

    boxBody->setBoxMass(1.0, Lengths.x(), Lengths.y(), Lengths.z());
    //std::cout << "mass: "                << boxBody->getMass()                    << std::endl
    //<< "massCenterOfGravity: " << boxBody->getMassCenterOfGravity().x() << ", "      << boxBody->getMassCenterOfGravity().y() << ", " << boxBody->getMassCenterOfGravity().z() << std::endl
    //<< "massInertiaTensor: "   << std::endl
    //<< boxBody->getMassInertiaTensor()[0][0] << " "<< boxBody->getMassInertiaTensor()[0][1] << " "<< boxBody->getMassInertiaTensor()[0][2] << " "   << boxBody->getMassInertiaTensor()[0][3] << std::endl
    //<< boxBody->getMassInertiaTensor()[1][0] << " "<< boxBody->getMassInertiaTensor()[1][1] << " "<< boxBody->getMassInertiaTensor()[1][2] << " "   << boxBody->getMassInertiaTensor()[1][3] << std::endl
    //<< boxBody->getMassInertiaTensor()[2][0] << " "<< boxBody->getMassInertiaTensor()[2][1] << " "<< boxBody->getMassInertiaTensor()[2][2] << " "   << boxBody->getMassInertiaTensor()[2][3] << std::endl
    //<< boxBody->getMassInertiaTensor()[3][0] << " "<< boxBody->getMassInertiaTensor()[3][1] << " "<< boxBody->getMassInertiaTensor()[3][2] << " "   << boxBody->getMassInertiaTensor()[3][3] << std::endl
    //<< std::endl;

    PhysicsBoxGeomRefPtr boxGeom = PhysicsBoxGeom::create();
    boxGeom->setBody(boxBody);
    boxGeom->setSpace(physicsSpace);
    boxGeom->setLengths(Lengths);


    //add attachments
    boxNode->addAttachment(boxGeom);
    boxTransNode->addAttachment(boxBody);
    boxTransNode->addChild(boxNode);


    //add to SceneGraph
    spaceGroupNode->addChild(boxTransNode);

    commitChanges();

}
//////////////////////////////////////////////////////////////////////////
//! trimesh defined by filenode will be loaded
//////////////////////////////////////////////////////////////////////////
void buildTriMesh(void)
{
    NodeRefPtr tri = cloneTree(TriGeometryBase);
    if(tri!=NULL)
    {
        GeometryRefPtr triGeo = dynamic_cast<Geometry*>(tri->getCore()); 
        Matrix m;
        SimpleMaterialRefPtr tri_mat = SimpleMaterial::create();
        tri_mat->setAmbient(Color3f(0.1,0.1,0.2));
        tri_mat->setDiffuse(Color3f(1.0,0.1,0.7));

        triGeo->setMaterial(tri_mat);
        TransformRefPtr triTrans;
        NodeRefPtr triTransNode = makeCoredNode<Transform>(&triTrans);
        m.setIdentity();
        Real32 randX = (Real32)(rand()%10)-5.0;
        Real32 randY = (Real32)(rand()%10)-5.0;
        m.setTranslate(randX, randY, 18.0);
        triTrans->setMatrix(m);

        //create ODE data
        Vec3f GeometryBounds(calcMinGeometryBounds(triGeo));
        PhysicsBodyRefPtr triBody = PhysicsBody::create(physicsWorld);
        triBody->setPosition(Vec3f(randX, randY, 18.0));
        triBody->setLinearDamping(0.0001);
        triBody->setAngularDamping(0.0001);

        triBody->setBoxMass(1.0,GeometryBounds.x(), GeometryBounds.y(), GeometryBounds.z());
        PhysicsGeomRefPtr triGeom;
        if(true)
        {
            triGeom = PhysicsTriMeshGeom::create();
            triGeom->setBody(triBody);
            //add geom to space for collision
            triGeom->setSpace(physicsSpace);
            //set the geometryNode to fill the ode-triMesh
            NodeRefPtr TorusGeometryNode(makeTorus(0.55, 1.05, 6, 6));
            dynamic_pointer_cast<PhysicsTriMeshGeom>(triGeom)->setGeometryNode(TorusGeometryNode);
        }

        //add attachments
        tri->addAttachment(triGeom);
        triTransNode->addAttachment(triBody);
        //add to SceneGraph
        triTransNode->addChild(tri);
        spaceGroupNode->addChild(triTransNode);
    }
    else
    {
        SLOG << "Could not read MeshData!" << endLog;
    }

    commitChanges();
}
Example #10
0
SearchResult
Tree::find(NodeRefPtr startNode, const ResourceName &policyRes,
	   bool usePatterns = true) {
    am_resource_match_t compRes;
    std::list<NodeRefPtr>::const_iterator iter;

    const ResourceName& resName = startNode->getPolicyDecision()->getName();
    compRes = compare(resName, policyRes, usePatterns);

    if(compRes != AM_SUB_RESOURCE_MATCH && compRes != AM_EXACT_PATTERN_MATCH) {
	if(compRes == AM_EXACT_MATCH)
	    return SearchResult(AM_EXACT_MATCH, startNode);
	return SearchResult(compRes, Node::NULL_NODE);
    }

    for(iter = startNode->begin(); iter != startNode->end(); ++iter) {
	NodeRefPtr node = *iter;
	const PDRefCntPtr &element = node->getPolicyDecision();
	switch((compare(element->getName(), policyRes, usePatterns))) {
	case AM_EXACT_MATCH:
	    return SearchResult(AM_EXACT_MATCH, node);
	    break;
	case AM_NO_MATCH:
	    continue;
	    break;
	case AM_SUPER_RESOURCE_MATCH:
	    return SearchResult(AM_SUB_RESOURCE_MATCH, startNode);
	case AM_SUB_RESOURCE_MATCH:
	case AM_EXACT_PATTERN_MATCH:
	    {
		SearchResult result = find(node, policyRes, usePatterns);
		switch(result.first) {
		    // In case of the node below returns SUB_RESOURCE_MATCH,
		    // EXACT_PATTERN_MATCH or EXACT_MATCH,
		    // we just need to pass on the result upwards.
		case AM_SUB_RESOURCE_MATCH:
		case AM_EXACT_PATTERN_MATCH:
		case AM_EXACT_MATCH:
		    // Bingo! got a match.
		    return result;
		case AM_SUPER_RESOURCE_MATCH:
		case AM_NO_MATCH:
		    return SearchResult(AM_SUB_RESOURCE_MATCH, startNode);
		}
	    }
	    break;
	}
    }

    // This is the level we have to add the node.
    if(iter == startNode->end()) {
	if(compRes == AM_SUB_RESOURCE_MATCH || compRes == AM_EXACT_PATTERN_MATCH)
	    return SearchResult(compRes, startNode);
	else
	    return SearchResult(compRes, Node::NULL_NODE);
    }
    return SearchResult(AM_NO_MATCH, Node::NULL_NODE);
}
//////////////////////////////////////////////////////////////////////////
//! build a ship
//////////////////////////////////////////////////////////////////////////
PhysicsBodyRefPtr buildShip(Vec3f Dimensions, Pnt3f Position)
{
    Real32 Radius(osgMax(Dimensions.x(), Dimensions.y())/2.0f);
    Real32 Length(Dimensions.z() - 2.0f*Radius);

    Matrix m;
    //create OpenSG mesh
    GeometryRefPtr box;
    NodeRefPtr boxNode = makeBox(Dimensions.x(), Dimensions.y(), Dimensions.z(), 1, 1, 1);
    box = dynamic_cast<Geometry*>(boxNode->getCore());
    SimpleMaterialRefPtr box_mat = SimpleMaterial::create();
        box_mat->setAmbient(Color3f(0.0,0.0,0.0));
        box_mat->setDiffuse(Color3f(1.0,1.0 ,0.0));
        box->setMaterial(box_mat);
    TransformRefPtr boxTrans;
    NodeRefPtr boxTransNode = makeCoredNode<Transform>(&boxTrans);
    m.setIdentity();
    m.setTranslate(Position - Vec3f(0.0f,0.0f,0.5f*Dimensions.z()));
        boxTrans->setMatrix(m);

        for(UInt32 i(0) ; i<box->getPositions()->size() ; ++i)
        {
            box->getPositions()->setValue<Pnt3f>(box->getPositions()->getValue<Pnt3f>(i) + Vec3f(0.0,0.0,Dimensions.z()/2.0f),i);
        }


    //create ODE data

    PhysicsBodyRefPtr CapsuleBody = PhysicsBody::create(physicsWorld);
        CapsuleBody->setPosition(Vec3f(Position - Vec3f(0.0f,0.0f,0.5f*Dimensions.z())));
        CapsuleBody->setLinearDamping(0.01);
        CapsuleBody->setMaxAngularSpeed(0.0);
    CapsuleBody->setCapsuleMass(1.0,3,Radius, Length);

    PhysicsCapsuleGeomRefPtr CapsuleGeom = PhysicsCapsuleGeom::create();
        CapsuleGeom->setBody(CapsuleBody);
        CapsuleGeom->setOffsetPosition(Vec3f(0.0f,0.0f,0.5f*Dimensions.z()));
        CapsuleGeom->setSpace(hashSpace);
        CapsuleGeom->setRadius(Radius);
        CapsuleGeom->setLength(Length);

    //add attachments
        boxNode->addAttachment(CapsuleGeom);
        boxTransNode->addAttachment(CapsuleBody);
        boxTransNode->addChild(boxNode);

    //add to SceneGraph
        spaceGroupNode->addChild(boxTransNode);

    commitChanges();

    return CapsuleBody;
}
 virtual void keyPressed(const KeyEventUnrecPtr e)
 {
     if(e->getKey() == KeyEvent::KEY_Q && e->getModifiers() & KeyEvent::KEY_MODIFIER_COMMAND)
     {
         TutorialWindow->closeWindow();
     }
     switch(e->getKey())
     {
         case KeyEvent::KEY_S:
             {
                 buildSphere();
             }
             break;
         case KeyEvent::KEY_B:
             {
                 buildBox();
             }
             break;
         case KeyEvent::KEY_T:
             {
                 buildTriMesh();
             }
             break;
         case KeyEvent::KEY_D:
             {
                 if(PhysDrawableNode->getTravMask())
                 {
                     PhysDrawableNode->setTravMask(TypeTraits<UInt32>::getMin());
                 }
                 else
                 {
                     PhysDrawableNode->setTravMask(TypeTraits<UInt32>::getMax());
                 }
             }
             break;
     }
 }
//////////////////////////////////////////////////////////////////////////
//! build a sphere
//////////////////////////////////////////////////////////////////////////
void buildSphere(void)
{
    Real32 Radius((Real32)(rand()%2)*0.5+0.5);
    Matrix m;
    //create OpenSG mesh
    GeometryRefPtr sphere;
    NodeRefPtr sphereNode = makeSphere(2, Radius);
    sphere = dynamic_cast<Geometry*>(sphereNode->getCore());
    SimpleMaterialRefPtr sphere_mat = SimpleMaterial::create();
    sphere_mat->setAmbient(Color3f(0.0,0.0,0.0));
    sphere_mat->setDiffuse(Color3f(0.0,0.0,1.0));

    sphere->setMaterial(sphere_mat);

    TransformRefPtr sphereTrans;
    NodeRefPtr sphereTransNode = makeCoredNode<Transform>(&sphereTrans);
    m.setIdentity();
    Real32 randX = (Real32)(rand()%10)-5.0;
    Real32 randY = (Real32)(rand()%10)-5.0;
    m.setTranslate(randX, randY, 10.0);
    sphereTrans->setMatrix(m);

    //create ODE data
    PhysicsBodyRefPtr sphereBody = PhysicsBody::create(physicsWorld);
    sphereBody->setPosition(Vec3f(randX, randY, 10.0));
    sphereBody->setAngularDamping(0.0001);

    sphereBody->setSphereMass(1.0,Radius);

    PhysicsSphereGeomRefPtr sphereGeom = PhysicsSphereGeom::create();
    sphereGeom->setBody(sphereBody);
    sphereGeom->setSpace(physicsSpace);
    sphereGeom->setRadius(Radius);


    //add attachments
    sphereNode->addAttachment(sphereGeom);

    sphereTransNode->addAttachment(sphereBody);
    sphereTransNode->addChild(sphereNode);

    //add to SceneGraph
    spaceGroupNode->addChild(sphereTransNode);

    commitChanges();
}
//////////////////////////////////////////////////////////////////////////
//! build a character
//////////////////////////////////////////////////////////////////////////
PhysicsBodyRefPtr buildCharacter(Vec3f Dimensions,
                                 Pnt3f Position,
                                 Node* const spaceGroupNode,
                                 PhysicsWorld* const physicsWorld,
                                 PhysicsHashSpace* const physicsSpace
                                 )
{
    Real32 Radius(osgMax(Dimensions.x(), Dimensions.y())/2.0f);
    Real32 Length(Dimensions.z() - 2.0f*Radius);

    Matrix m;
    //create OpenSG mesh
    GeometryRefPtr box;
    //NodeRefPtr characterNode = makeBox(Dimensions.x(), Dimensions.y(), Dimensions.z(), 1, 1, 1);
    NodeRefPtr characterNode = SceneFileHandler::the()->read("Data/Jack.osb");
    if(characterNode == NULL)
    {
        characterNode = makeBox(Dimensions.x(), Dimensions.y(), Dimensions.z(), 1, 1, 1);
    }
    box = dynamic_cast<Geometry*>(characterNode->getCore());
    TransformRefPtr boxTrans;
    NodeRefPtr boxTransNode = makeCoredNode<Transform>(&boxTrans);
    m.setIdentity();
    m.setTranslate(Position);
    boxTrans->setMatrix(m);

    //create ODE data
    PhysicsBodyRefPtr boxBody = PhysicsBody::create(physicsWorld);
    boxBody->setPosition(Vec3f(Position));
    //boxBody->setLinearDamping(0.001);
    //boxBody->setAngularDamping(0.001);
    boxBody->setMaxAngularSpeed(0.0);
    boxBody->setCapsuleMass(1.0,3,Radius, Length);

    PhysicsCapsuleGeomRefPtr CapsuleGeom = PhysicsCapsuleGeom::create();
    CapsuleGeom->setBody(boxBody);
    CapsuleGeom->setSpace(physicsSpace);
    CapsuleGeom->setRadius(Radius);
    CapsuleGeom->setLength(Length);

    //add attachments
    characterNode->addAttachment(CapsuleGeom);
    boxTransNode->addAttachment(boxBody);
    boxTransNode->addChild(characterNode);

    //add to SceneGraph
    spaceGroupNode->addChild(boxTransNode);
    commitChanges();

    return boxBody;
}
Example #15
0
/* Throws std::invalid_argument if any argument is invalid */
void
Tree::addSubNodes(NodeRefPtr parent, XMLElement &thisNode,
		  KVMRefCntPtr env)
{
    string resName;
    if(thisNode.isNamed(RESOURCE_RESULT) &&
       thisNode.getAttributeValue(NAME, resName)) {
	XMLElement decn;
	NodeRefPtr newNode;
	if(thisNode.getSubElement(POLICY_DECISION, decn)) {
	    PDRefCntPtr decision =
		PolicyDecision::construct_policy_decision(resName, decn,
							  env);

	    newNode = new Node(parent, decision);

	    // If the parent is NULL, then this is the root Node.
	    if(parent != NULL) {
		parent->addNode(newNode);
	    } else {
		rootNode = newNode;
	    }

	} else {
	    throw std::invalid_argument("Tree:addSubNodes(...) Cannot find "
					"Policy Decision node under resource "
					"result.");
	}

	XMLElement subElems;
	if(thisNode.getSubElement(RESOURCE_RESULT, subElems)) {
	    for(;subElems.isValid(); subElems.nextSibling(RESOURCE_RESULT)) {
		addSubNodes(newNode, subElems, env);
	    }
	}
    } else {
      throw std::invalid_argument("Tree::addSubNodes(...) has an invalid XML as input.");
    }
}
//////////////////////////////////////////////////////////////////////////
//! build a box
//////////////////////////////////////////////////////////////////////////
PhysicsBodyRefPtr buildBox(Vec3f Dimensions, Pnt3f Position)
{
    Matrix m;
    //create OpenSG mesh
    GeometryRefPtr box;
    NodeRefPtr boxNode = makeBox(Dimensions.x(), Dimensions.y(), Dimensions.z(), 1, 1, 1);
    box = dynamic_cast<Geometry*>(boxNode->getCore());
    SimpleMaterialRefPtr box_mat = SimpleMaterial::create();
        box_mat->setAmbient(Color3f(0.0,0.0,0.0));
        box_mat->setDiffuse(Color3f(0.0,1.0 ,1.0));
        box->setMaterial(box_mat);
    TransformRefPtr boxTrans;
    NodeRefPtr boxTransNode = makeCoredNode<Transform>(&boxTrans);
    m.setIdentity();
    m.setTranslate(Position);
        boxTrans->setMatrix(m);

    //create ODE data
    PhysicsBodyRefPtr boxBody = PhysicsBody::create(physicsWorld);
        boxBody->setPosition(Vec3f(Position));
        boxBody->setLinearDamping(0.001);
        boxBody->setAngularDamping(0.001);
    boxBody->setBoxMass(1.0,Dimensions.x(), Dimensions.y(), Dimensions.z());

    PhysicsBoxGeomRefPtr boxGeom = PhysicsBoxGeom::create();
        boxGeom->setBody(boxBody);
        boxGeom->setSpace(hashSpace);
        boxGeom->setLengths(Dimensions);

    //add attachments
        boxNode->addAttachment(boxGeom);
        boxTransNode->addAttachment(boxBody);
        boxTransNode->addChild(boxNode);

    //add to SceneGraph
        spaceGroupNode->addChild(boxTransNode);

    commitChanges();

    return boxBody;
}
Example #17
0
bool
Tree::insertBelow(NodeRefPtr parent, PDRefCntPtr &elem) {
    std::list<NodeRefPtr>::iterator iter;
    NodeRefPtr newNode(new Node(parent, elem));

    // add the subordinate nodes of newNode under
    // new node.  In the next loop, we iterate nodes
    // under new node and remove them from parent.
    // Reason: if we remove nodes under parent in this
    // loop, iterator becomes invalid.
    ScopeLock myLock(treeLock);
    for(iter = parent->begin(); iter != parent->end(); iter++) {
	NodeRefPtr node = *iter;
	PDRefCntPtr data = node->getPolicyDecision();
	switch(compare(data->getName(), elem->getName(), false)) {
	case AM_EXACT_MATCH:
	case AM_SUB_RESOURCE_MATCH:
	    return false;

	case AM_NO_MATCH:
	    break;
	case AM_SUPER_RESOURCE_MATCH:
	    newNode->addNode(node);
	    break;
	}
    }

    for(iter = newNode->begin(); iter != newNode->end(); iter++) {
	NodeRefPtr node = *iter;
	parent->remove(node);
    }

    parent->addNode(newNode);

    return true;
}
// Initialize GLUT & OpenSG and set up the rootNode
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindow = createNativeWindow();
    TutorialWindow->initWindow();

    TutorialWindow->setDisplayCallback(display);
    TutorialWindow->setReshapeCallback(reshape);

    TutorialKeyListener TheKeyListener;
    TutorialWindow->addKeyListener(&TheKeyListener);
    TutorialMouseListener TheTutorialMouseListener;
    TutorialMouseMotionListener TheTutorialMouseMotionListener;
    TutorialWindow->addMouseListener(&TheTutorialMouseListener);
    TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener);
	TutorialUpdateListener TheTutorialUpdateListener;
    TutorialWindow->addUpdateListener(&TheTutorialUpdateListener);


    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

	
    // Tell the Manager what to manage
    mgr->setWindow(TutorialWindow);

    //Make Main Scene Node
	NodeRefPtr scene = makeCoredNode<Group>();
    setName(scene, "scene");
    rootNode = Node::create();
    setName(rootNode, "rootNode");
    ComponentTransformRefPtr Trans;
    Trans = ComponentTransform::create();
    {
        rootNode->setCore(Trans);
 
        // add the torus as a child
        rootNode->addChild(scene);
    }

    //Make The Physics Characteristics Node
    PhysicsCharacteristicsDrawableUnrecPtr PhysDrawable = PhysicsCharacteristicsDrawable::create();
        PhysDrawable->setRoot(rootNode);

	PhysDrawableNode = Node::create();
    PhysDrawableNode->setCore(PhysDrawable);
    PhysDrawableNode->setTravMask(TypeTraits<UInt32>::getMin());

    rootNode->addChild(PhysDrawableNode);

    //Light Beacon
    NodeRefPtr TutorialLightBeacon = makeCoredNode<Transform>();

    //Light Node
    DirectionalLightRefPtr TutorialLight = DirectionalLight::create();
    TutorialLight->setDirection(0.0,0.0,-1.0);
    TutorialLight->setBeacon(TutorialLightBeacon);

    NodeRefPtr TutorialLightNode = Node::create();
    TutorialLightNode->setCore(TutorialLight);

    scene->addChild(TutorialLightNode);
    scene->addChild(TutorialLightBeacon);


    //Setup Physics Scene
    physicsWorld = PhysicsWorld::create();
        physicsWorld->setWorldContactSurfaceLayer(0.01);
        physicsWorld->setAutoDisableFlag(1);
        physicsWorld->setAutoDisableTime(0.75);
        physicsWorld->setWorldContactMaxCorrectingVel(1.0);
        //physicsWorld->setGravity(Vec3f(0.0, 0.0, -9.81));
        //physicsWorld->setCfm(0.001);
        //physicsWorld->setErp(0.2);

    hashSpace = PhysicsHashSpace::create();

    physHandler = PhysicsHandler::create();
        physHandler->setWorld(physicsWorld);
        physHandler->pushToSpaces(hashSpace);
        physHandler->setUpdateNode(rootNode);
    physHandler->attachUpdateProducer(TutorialWindow->editEventProducer());
    

        rootNode->addAttachment(physHandler);    
        rootNode->addAttachment(physicsWorld);
        rootNode->addAttachment(hashSpace);


	/************************************************************************/
	/* create spaces, geoms and bodys                                                                     */
	/************************************************************************/
    //create a group for our space
    GroupRefPtr spaceGroup;
	spaceGroupNode = makeCoredNode<Group>(&spaceGroup);
	//add Attachments to nodes...
	    spaceGroupNode->addAttachment(hashSpace);

	    TutorialLightNode->addChild(spaceGroupNode);

    //Create Character
    ShipBody = buildShip(Vec3f(3.0,3.0,10.0), Pnt3f((Real32)(rand()%100)-50.0,(Real32)(rand()%100)-50.0,25.0));
    ShipMotor = buildMotor(ShipBody);

    for(UInt32 i(0) ; i<5 ; ++i)
    {
        buildBox(Vec3f(10.0,10.0,10.0), Pnt3f((Real32)(rand()%100)-50.0,(Real32)(rand()%100)-50.0,25.0));
    }

    // tell the manager what to manage
    mgr->setRoot  (rootNode);

    // show the whole rootNode
    mgr->showAll();
    
    Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
    TutorialWindow->openWindow(WinPos,
            WinSize,
            "04ZeroGravityShip");

    //Enter main Loop
    TutorialWindow->mainLoop();

    osgExit();

    return 0;
}
Example #19
0
OSG_USING_NAMESPACE

void renderSceneToTexture(Scene* const TheScene,
                          TextureObjChunk* const ColorTexture,
                          Window* const TheWindow,
                          RenderAction* TheRenderAction)
{
    //Create an FBO to render the Scene's Viewport(s) into

    FrameBufferObjectRecPtr SceneFBO         = FrameBufferObject::create();
    TextureBufferRecPtr     FBOTextureBuffer = TextureBuffer    ::create();
    RenderBufferRecPtr      FBODepthBuffer   = RenderBuffer     ::create();


    //Attache the Texture to the TexureBuffer
    FBOTextureBuffer->setTexture(ColorTexture);

    // add a depth attachment, otherwise there is no depth buffer when
    // rendering to the FBO
    FBODepthBuffer->setInternalFormat(GL_DEPTH_COMPONENT24);

    // make the fbo render to the texture
    SceneFBO->setColorAttachment(FBOTextureBuffer,   0);
    SceneFBO->setDepthAttachment(FBODepthBuffer   );
    SceneFBO->editMFDrawBuffers()->push_back(GL_COLOR_ATTACHMENT0_EXT);
    SceneFBO->setWidth (FBOTextureBuffer->getTexture()->getImage()->getWidth() );
    SceneFBO->setHeight(FBOTextureBuffer->getTexture()->getImage()->getHeight());


    /*
        Next we set up a Stage, which renders the subtree below it to its
        render target (the FBO from above).
    */

    SimpleStageRefPtr SceneStage     = SimpleStage::create();
    NodeRefPtr        SceneStageNode = makeNodeFor(SceneStage);

    ViewportRecPtr SceneViewport(TheScene->getPrimaryViewport());
    SceneStage->setRenderTarget(SceneFBO);
    SceneStage->setLeft(SceneViewport->getLeft());
    SceneStage->setRight(SceneViewport->getRight());
    SceneStage->setTop(SceneViewport->getTop());
    SceneStage->setBottom(SceneViewport->getBottom());
    SceneStage->setCamera(SceneViewport->getCamera());
    SceneStage->setBackground(SceneViewport->getBackground());

    for(UInt32 i(0) ; i<SceneViewport->getMFForegrounds()->size() ; ++i)
    {
        SceneStage->pushToForegrounds(SceneViewport->getForegrounds(i));
    }

    SceneStageNode->addChild(SceneViewport->getRoot());

    NodeRecPtr ThumbRootNode = makeCoredNode<Group>();
    ThumbRootNode->addChild(SceneStageNode);

    CameraRecPtr ThumbCamera = MatrixCamera::create();
    ThumbCamera->setBeacon(ThumbRootNode);

    BackgroundRecPtr ThumbBackground = PassiveBackground::create();

    //Create a dummy Viewport for attaching to the window
    ViewportRecPtr ThumbViewport = Viewport::create();
    ThumbViewport->setBackground(ThumbBackground);
    ThumbViewport->setRoot(ThumbRootNode);
    ThumbViewport->setCamera(ThumbCamera);

    //Get all of the original TravMasks of the Viewports on the window
    //Set all of the TravMasks of the Viewports on the window to 0
    std::vector<UInt32> OrigTravMasks;
    OrigTravMasks.reserve(TheWindow->getMFPort()->size());
    for(UInt32 i(0) ; i<TheWindow->getMFPort()->size() ; ++i)
    {
        OrigTravMasks.push_back(TheWindow->getPort(i)->getTravMask());

        TheWindow->getPort(i)->setTravMask(0);
    }

    //Attach the Viewport to the Window
    TheWindow->addPort(ThumbViewport);

    //Draw the window
    TheWindow->render(TheRenderAction);

    //Detach the Viewport from the Window
    TheWindow->subPortByObj(ThumbViewport);

    //Reset all of the original TravMasks of the Viewports on the window
    for(UInt32 i(0) ; i<TheWindow->getMFPort()->size() ; ++i)
    {
        TheWindow->getPort(i)->setTravMask(OrigTravMasks[i]);
    }
}
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    {
        // Set up Window
        WindowEventProducerRecPtr TutorialWindow = createNativeWindow();
        TutorialWindow->initWindow();

        // Create the SimpleSceneManager helper
        SimpleSceneManager sceneManager;
        TutorialWindow->setDisplayCallback(boost::bind(display, &sceneManager));
        TutorialWindow->setReshapeCallback(boost::bind(reshape, _1, &sceneManager));

        // Tell the Manager what to manage
        sceneManager.setWindow(TutorialWindow);

        //Attach to events
        TutorialWindow->connectMousePressed(boost::bind(mousePressed, _1, &sceneManager));
        TutorialWindow->connectMouseReleased(boost::bind(mouseReleased, _1, &sceneManager));
        TutorialWindow->connectMouseMoved(boost::bind(mouseMoved, _1, &sceneManager));
        TutorialWindow->connectMouseDragged(boost::bind(mouseDragged, _1, &sceneManager));
        TutorialWindow->connectMouseWheelMoved(boost::bind(mouseWheelMoved, _1, &sceneManager));
        TutorialWindow->connectKeyTyped(boost::bind(keyTyped, _1, &sceneManager));

        //Particle System Material
        PointChunkRefPtr PSPointChunk = PointChunk::create();
        PSPointChunk->setSize(5.0f);
        PSPointChunk->setSmooth(true);
        BlendChunkRefPtr PSBlendChunk = BlendChunk::create();
        PSBlendChunk->setSrcFactor(GL_SRC_ALPHA);
        PSBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);

        MaterialChunkRefPtr PSMaterialChunkChunk = MaterialChunk::create();
        PSMaterialChunkChunk->setAmbient(Color4f(0.3f,0.3f,0.3f,1.0f));
        PSMaterialChunkChunk->setDiffuse(Color4f(0.7f,0.7f,0.7f,1.0f));
        PSMaterialChunkChunk->setSpecular(Color4f(0.9f,0.9f,0.9f,1.0f));
        PSMaterialChunkChunk->setColorMaterial(GL_AMBIENT_AND_DIFFUSE);

        ChunkMaterialRefPtr PSMaterial = ChunkMaterial::create();
        PSMaterial->addChunk(PSPointChunk);
        PSMaterial->addChunk(PSMaterialChunkChunk);
        PSMaterial->addChunk(PSBlendChunk);

        Distribution3DRefPtr PositionDistribution = createPositionDistribution();

        Pnt3f PositionReturnValue;

        //Particle System
        ParticleSystemRefPtr ExampleParticleSystem = ParticleSystem::create();
        for(UInt32 i(0) ; i<500 ; ++i)//controls how many particles are created
        {
            if(PositionDistribution != NULL)
            {
                PositionReturnValue = Pnt3f(PositionDistribution->generate());
            }

            ExampleParticleSystem->addParticle(
                                               PositionReturnValue,
                                               Vec3f(0.0f,0.0f,1.0f),
                                               Color4f(1.0,0.0,0.0,1.0), 
                                               Vec3f(1.0,1.0,1.0), 
                                               -1, 
                                               Vec3f(0.0f,0.0f,0.0f), //Velocity
                                               Vec3f(0.0f,0.0f,0.0f)	//acceleration
                                              );
        }
        ExampleParticleSystem->attachUpdateProducer(TutorialWindow);

        //Particle System Drawer
        PointParticleSystemDrawerRefPtr ExampleParticleSystemDrawer = PointParticleSystemDrawer::create();



        //Particle System Node
        ParticleSystemCoreRefPtr ParticleNodeCore = ParticleSystemCore::create();
        ParticleNodeCore->setSystem(ExampleParticleSystem);
        ParticleNodeCore->setDrawer(ExampleParticleSystemDrawer);
        ParticleNodeCore->setMaterial(PSMaterial);

        NodeRefPtr ParticleNode = Node::create();
        ParticleNode->setCore(ParticleNodeCore);


        // Make Main Scene Node and add the Torus
        NodeRefPtr scene = Node::create();
        scene->setCore(Group::create());
        scene->addChild(ParticleNode);

        sceneManager.setRoot(scene);

        // Show the whole Scene
        sceneManager.showAll();

        //Create an DistanceKill
        DistanceKillParticleAffectorRefPtr ExampleDistanceKillParticleAffector = DistanceKillParticleAffector::create();
        ExampleDistanceKillParticleAffector->setKillDistance(1000.0f);
        ExampleDistanceKillParticleAffector->setParticleSystemNode(ParticleNode);
        ExampleDistanceKillParticleAffector->setDistanceFromSource(DistanceKillParticleAffector::DISTANCE_FROM_CAMERA);
        ExampleDistanceKillParticleAffector->setDistanceFromCamera(sceneManager.getCamera());

        ExampleParticleSystem->pushToAffectors(ExampleDistanceKillParticleAffector);

        //Open Window
        Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
        Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
        TutorialWindow->openWindow(WinPos,
                                   WinSize,
                                   "09DistanceKillParticleAffector");

        //Enter main Loop
        TutorialWindow->mainLoop();

    }
    osgExit();

    return 0;
}
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindow = createNativeWindow();
    TutorialWindow->initWindow();

    TutorialWindow->setDisplayCallback(display);
    TutorialWindow->setReshapeCallback(reshape);

    TutorialKeyListener TheKeyListener;
    TutorialWindow->addKeyListener(&TheKeyListener);
    TutorialMouseListener TheTutorialMouseListener;
    TutorialMouseMotionListener TheTutorialMouseMotionListener;
    TutorialWindow->addMouseListener(&TheTutorialMouseListener);
    TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener);

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // Tell the Manager what to manage
    mgr->setWindow(TutorialWindow);

    //Particle System Material
    TextureObjChunkRefPtr QuadTextureObjChunk = TextureObjChunk::create();
    ImageRefPtr LoadedImage = ImageFileHandler::the()->read("Data/Cloud.png");    
    QuadTextureObjChunk->setImage(LoadedImage);

    TextureEnvChunkRefPtr QuadTextureEnvChunk = TextureEnvChunk::create();
    QuadTextureEnvChunk->setEnvMode(GL_MODULATE);

    BlendChunkRefPtr PSBlendChunk = BlendChunk::create();
    PSBlendChunk->setSrcFactor(GL_SRC_ALPHA);
    PSBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);

    MaterialChunkRefPtr PSMaterialChunk = MaterialChunk::create();
    PSMaterialChunk->setAmbient(Color4f(0.3f,0.3f,0.3f,1.0f));
    PSMaterialChunk->setDiffuse(Color4f(0.7f,0.7f,0.7f,1.0f));
    PSMaterialChunk->setSpecular(Color4f(0.9f,0.9f,0.9f,1.0f));
    PSMaterialChunk->setColorMaterial(GL_AMBIENT_AND_DIFFUSE);

    ChunkMaterialRefPtr PSMaterial = ChunkMaterial::create();
    PSMaterial->addChunk(QuadTextureObjChunk);
    PSMaterial->addChunk(QuadTextureEnvChunk);
    PSMaterial->addChunk(PSMaterialChunk);
    PSMaterial->addChunk(PSBlendChunk);



    //Affector
    ExampleAgeSizeParticleAffector = OSG::AgeSizeParticleAffector::create();
    //ages
    ExampleAgeSizeParticleAffector->editMFAges()->push_back(0.0);
    ExampleAgeSizeParticleAffector->editMFAges()->push_back(0.05);
    ExampleAgeSizeParticleAffector->editMFAges()->push_back(0.2);
    ExampleAgeSizeParticleAffector->editMFAges()->push_back(0.36);
    ExampleAgeSizeParticleAffector->editMFAges()->push_back(0.7);
    ExampleAgeSizeParticleAffector->editMFAges()->push_back(0.8);
    ExampleAgeSizeParticleAffector->editMFAges()->push_back(1.0);

    //sizes
    ExampleAgeSizeParticleAffector->editMFSizes()->push_back(Vec3f(1.0,0.5,1.0));
    ExampleAgeSizeParticleAffector->editMFSizes()->push_back(Vec3f(1.0,0.5,1.0));
    ExampleAgeSizeParticleAffector->editMFSizes()->push_back(Vec3f(20.0,0.5,30.0));
    ExampleAgeSizeParticleAffector->editMFSizes()->push_back(Vec3f(3.0,3.0,3.0));
    ExampleAgeSizeParticleAffector->editMFSizes()->push_back(Vec3f(6.0,60.0,6.0));
    ExampleAgeSizeParticleAffector->editMFSizes()->push_back(Vec3f(2.0,3.0,1.0));
    ExampleAgeSizeParticleAffector->editMFSizes()->push_back(Vec3f(10.0,1.0,10.0));

    //Particle System
    ExampleParticleSystem = OSG::ParticleSystem::create();
    ExampleParticleSystem->attachUpdateListener(TutorialWindow);
    ExampleParticleSystem->pushToAffectors(ExampleAgeSizeParticleAffector);

    //Particle System Drawer
    ExampleParticleSystemDrawer = OSG::QuadParticleSystemDrawer::create();


    ExampleBurstGenerator = OSG::BurstParticleGenerator::create();
    //Attach the function objects to the Generator
    ExampleBurstGenerator->setPositionDistribution(createPositionDistribution());
    ExampleBurstGenerator->setLifespanDistribution(createLifespanDistribution());
    ExampleBurstGenerator->setBurstAmount(10.0);
    ExampleBurstGenerator->setVelocityDistribution(createVelocityDistribution());
    //ExampleBurstGenerator->setAccelerationDistribution(createAccelerationDistribution());
    ExampleBurstGenerator->setSizeDistribution(createSizeDistribution());

    //Particle System Node
    ParticleSystemCoreRefPtr ParticleNodeCore = OSG::ParticleSystemCore::create();
    ParticleNodeCore->setSystem(ExampleParticleSystem);
    ParticleNodeCore->setDrawer(ExampleParticleSystemDrawer);
    ParticleNodeCore->setMaterial(PSMaterial);

    NodeRefPtr ParticleNode = OSG::Node::create();
    ParticleNode->setCore(ParticleNodeCore);

    //Ground Node
    NodeRefPtr GoundNode = makePlane(30.0,30.0,10,10);

    Matrix GroundTransformation;
    GroundTransformation.setRotate(Quaternion(Vec3f(1.0f,0.0,0.0), -3.14195f));
    TransformRefPtr GroundTransformCore = Transform::create();
    GroundTransformCore->setMatrix(GroundTransformation);

    NodeRefPtr GroundTransformNode = Node::create();
    GroundTransformNode->setCore(GroundTransformCore);
    GroundTransformNode->addChild(GoundNode);


    // Make Main Scene Node and add the Torus
    NodeRefPtr scene = OSG::Node::create();
    scene->setCore(OSG::Group::create());
    scene->addChild(ParticleNode);
    scene->addChild(GroundTransformNode);

    mgr->setRoot(scene);

    // Show the whole Scene
    mgr->showAll();


    //Open Window
    Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
    TutorialWindow->openWindow(WinPos,
                               WinSize,
                               "07AgeSizeParticleAffector");

    //Enter main Loop
    TutorialWindow->mainLoop();

    osgExit();

    return 0;
}
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindow = createNativeWindow();
    TutorialWindow->initWindow();

    TutorialWindow->setDisplayCallback(display);
    TutorialWindow->setReshapeCallback(reshape);

    //Add Key Listener
    TutorialKeyListener TheKeyListener;
    TutorialWindow->addKeyListener(&TheKeyListener);
    //Add Mouse Listeners
    TutorialMouseListener TheTutorialMouseListener;
    TutorialMouseMotionListener TheTutorialMouseMotionListener;
    TutorialWindow->addMouseListener(&TheTutorialMouseListener);
    TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener);

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // Tell the Manager what to manage
    mgr->setWindow(TutorialWindow);

    //Particle System Material
    PointChunkRefPtr PSPointChunk = PointChunk::create();
    PSPointChunk->setSize(5.0f);
    PSPointChunk->setSmooth(true);

    BlendChunkRefPtr PSBlendChunk = BlendChunk::create();
    PSBlendChunk->setSrcFactor(GL_SRC_ALPHA);
    PSBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);

    MaterialChunkRefPtr PSMaterialChunkChunk = MaterialChunk::create();
    PSMaterialChunkChunk->setAmbient(Color4f(0.5f,0.5f,0.5f,0.3f));
    PSMaterialChunkChunk->setDiffuse(Color4f(0.8f,0.8f,0.8f,0.3f));
    PSMaterialChunkChunk->setSpecular(Color4f(1.0f,1.0f,1.0f,0.3f));
    PSMaterialChunkChunk->setColorMaterial(GL_AMBIENT_AND_DIFFUSE);

    ChunkMaterialRefPtr PSMaterial = ChunkMaterial::create();
    PSMaterial->addChunk(PSPointChunk);
    PSMaterial->addChunk(PSMaterialChunkChunk);
    PSMaterial->addChunk(PSBlendChunk);


    //Particle System
    ParticleSystemRefPtr ExampleParticleSystem = ParticleSystem::create();
    for(UInt32 i(0) ; i<10 ; ++i)
    {
        ExampleParticleSystem->addParticle(Pnt3f(i,i,i),
                                           Vec3f(0.0,0.0f,1.0f),
                                           Color4f(1.0,0.0,0.0,0.5), 
                                           Vec3f(1.0,1.0,1.0), 
                                           -1.0, 
                                           Vec3f(0.0f,0.0f,0.0f), //Velocity
                                           Vec3f(0.0f,0.0f,0.0f)
                                          );
    }
    ExampleParticleSystem->attachUpdateListener(TutorialWindow);

    //Particle System Drawer
    //Point
    ExamplePointParticleSystemDrawer = PointParticleSystemDrawer::create();
    //ExamplePointParticleSystemDrawer->setForcePerParticleSizing(true);

    //Line
    ExampleLineParticleSystemDrawer = LineParticleSystemDrawer::create();
    ExampleLineParticleSystemDrawer->setLineDirectionSource(LineParticleSystemDrawer::DIRECTION_NORMAL);//DIRECTION_VELOCITY_CHANGE);
    ExampleLineParticleSystemDrawer->setLineLengthSource(LineParticleSystemDrawer::LENGTH_SIZE_X);
    //Quad
    ExampleQuadParticleSystemDrawer = QuadParticleSystemDrawer::create();

    //Disc
    ExampleDiscParticleSystemDrawer = DiscParticleSystemDrawer::create();
    ExampleDiscParticleSystemDrawer->setSegments(16);
    ExampleDiscParticleSystemDrawer->setCenterAlpha(1.0);
    ExampleDiscParticleSystemDrawer->setEdgeAlpha(0.0);

    //Particle System Node
    ParticleNodeCore = ParticleSystemCore::create();
    ParticleNodeCore->setSystem(ExampleParticleSystem);
    ParticleNodeCore->setDrawer(ExampleLineParticleSystemDrawer);
    ParticleNodeCore->setMaterial(PSMaterial);

    NodeRefPtr ParticleNode = Node::create();
    ParticleNode->setCore(ParticleNodeCore);


    // Make Main Scene Node
    NodeRefPtr scene = Node::create();
    scene->setCore(Group::create());
    scene->addChild(ParticleNode);

    mgr->setRoot(scene);

    // Show the whole Scene
    mgr->showAll();


    //Open Window
    Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
    TutorialWindow->openWindow(WinPos,
                               WinSize,
                               "01ParticleSystemDrawers");

    commitChanges();

    //Enter main Loop
    TutorialWindow->mainLoop();

    osgExit();

    return 0;
}
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindow = createNativeWindow();
    TutorialWindow->initWindow();

    TutorialWindow->setDisplayCallback(display);
    TutorialWindow->setReshapeCallback(reshape);

    TutorialKeyListener TheKeyListener;
    TutorialWindow->addKeyListener(&TheKeyListener);
    TutorialMouseListener TheTutorialMouseListener;
    TutorialMouseMotionListener TheTutorialMouseMotionListener;
    TutorialWindow->addMouseListener(&TheTutorialMouseListener);
    TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener);

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // Tell the Manager what to manage
    mgr->setWindow(TutorialWindow);

    //Particle System Material
    PointChunkRefPtr PSPointChunk = PointChunk::create();
    PSPointChunk->setSize(5.0f);
    PSPointChunk->setSmooth(true);

    BlendChunkRefPtr PSBlendChunk = BlendChunk::create();
    PSBlendChunk->setSrcFactor(GL_SRC_ALPHA);
    PSBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);

    MaterialChunkRefPtr PSMaterialChunkChunk = MaterialChunk::create();
    PSMaterialChunkChunk->setAmbient(Color4f(1.0f,1.0f,1.0f,1.0f));
    PSMaterialChunkChunk->setDiffuse(Color4f(0.7f,0.7f,0.7f,1.0f));
    PSMaterialChunkChunk->setSpecular(Color4f(0.9f,0.9f,0.9f,1.0f));
    PSMaterialChunkChunk->setColorMaterial(GL_AMBIENT_AND_DIFFUSE);

    ChunkMaterialRefPtr PSMaterial = ChunkMaterial::create();
    PSMaterial->addChunk(PSPointChunk);
    PSMaterial->addChunk(PSMaterialChunkChunk);
    PSMaterial->addChunk(PSBlendChunk);

    //Particle System
    ParticleSystemRefPtr ExampleParticleSystem = OSG::ParticleSystem::create();
    ExampleParticleSystem->addParticle(Pnt3f(0,0,0),
                                       Vec3f(0.0,0.0f,1.0f),
                                       Color4f(1.0,1.0,1.0,1.0), 
                                       Vec3f(1.0,1.0,1.0), 
                                       0.1, 
                                       Vec3f(0.0f,0.0f,0.0f), //Velocity
                                       Vec3f(0.0f,0.0f,0.0f)
                                      );
    ExampleParticleSystem->addParticle(Pnt3f(50,0,0),
                                       Vec3f(0.0,0.0f,1.0f),
                                       Color4f(1.0,1.0,1.0,1.0), 
                                       Vec3f(1.0,1.0,1.0), 
                                       0.1, 
                                       Vec3f(0.0f,0.0f,0.0f), //Velocity
                                       Vec3f(0.0f,0.0f,0.0f)
                                      );
    ExampleParticleSystem->attachUpdateListener(TutorialWindow);

    //Particle System Drawer (Point)
    ExamplePointParticleSystemDrawer = OSG::PointParticleSystemDrawer::create();

    //Particle System Drawer (line)
    ExampleLineParticleSystemDrawer = OSG::LineParticleSystemDrawer::create();
    ExampleLineParticleSystemDrawer->setLineDirectionSource(LineParticleSystemDrawer::DIRECTION_VELOCITY);
    ExampleLineParticleSystemDrawer->setLineLengthSource(LineParticleSystemDrawer::LENGTH_SIZE_X);
    ExampleLineParticleSystemDrawer->setLineLength(0.5f);
    ExampleLineParticleSystemDrawer->setEndPointFading(Vec2f(1.0f,0.0f));

    //Create a Rate Particle Generator
    RateParticleGeneratorRefPtr ExampleGenerator = OSG::RateParticleGenerator::create();

    //Attach the function objects to the Generator
    ExampleGenerator->setPositionDistribution(createPositionDistribution());
    ExampleGenerator->setLifespanDistribution(createLifespanDistribution());
    ExampleGenerator->setVelocityDistribution(createVelocityDistribution());
    ExampleGenerator->setGenerationRate(2.0);

    ExampleConserveVelocityAffector = OSG::ConserveVelocityParticleAffector::create();
    ExampleConserveVelocityAffector->setConserve(0.0); // all velocity conserved initially.  Use keys 3 and 4 to change this value while running.



    //Attach the Generator and Affector to the Particle System
    ExampleParticleSystem->pushToGenerators(ExampleGenerator);
    ExampleParticleSystem->pushToAffectors(ExampleConserveVelocityAffector);
    ExampleParticleSystem->setMaxParticles(500);


    //Particle System Node
    ParticleNodeCore = OSG::ParticleSystemCore::create();
    ParticleNodeCore->setSystem(ExampleParticleSystem);
    ParticleNodeCore->setDrawer(ExamplePointParticleSystemDrawer);
    ParticleNodeCore->setMaterial(PSMaterial);

    NodeRefPtr ParticleNode = OSG::Node::create();
    ParticleNode->setCore(ParticleNodeCore);


    // Make Main Scene Node and add the Torus
    NodeRefPtr scene = OSG::Node::create();
    scene->setCore(OSG::Group::create());
    scene->addChild(ParticleNode);

    mgr->setRoot(scene);

    // Show the whole Scene
    mgr->showAll();

    mgr->getCamera()->setFar(1000.0);

    std::cout << "Conserve Velocity Particle Affector Tutorial Controls:\n"
        << "1: Use point drawer\n"
        << "2: Use line drawer\n"
        << "3: Decrease velocity conserved.\n"
        << "4: Increase velocity conserved.\n"
        << "Ctrl + Q: Exit Tutorial";

    //Open Window
    Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
    TutorialWindow->openWindow(WinPos,
                               WinSize,
                               "28ConserveVelocityParticleAffector");

    //Enter main Loop
    TutorialWindow->mainLoop();

    osgExit();

    return 0;
}
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindow = createNativeWindow();
    TutorialWindow->initWindow();

    TutorialWindow->setDisplayCallback(display);
    TutorialWindow->setReshapeCallback(reshape);

    //Add Key Listener
    TutorialKeyListener TheKeyListener;
    TutorialWindow->addKeyListener(&TheKeyListener);
    //Add Mouse Listeners
    TutorialMouseListener TheTutorialMouseListener;
    TutorialMouseMotionListener TheTutorialMouseMotionListener;
    TutorialWindow->addMouseListener(&TheTutorialMouseListener);
    TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener);

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // Tell the Manager what to manage
    mgr->setWindow(TutorialWindow);

    //Particle System Material
    PointChunkRefPtr PSPointChunk = PointChunk::create();
    PSPointChunk->setSize(6.0f);
    PSPointChunk->setSmooth(true);

    BlendChunkRefPtr PSBlendChunk = BlendChunk::create();
    PSBlendChunk->setSrcFactor(GL_SRC_ALPHA);
    PSBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);

    MaterialChunkRefPtr PSMaterialChunkChunk = MaterialChunk::create();
    PSMaterialChunkChunk->setAmbient(Color4f(0.2f,0.6f,0.5f,0.3f));
    PSMaterialChunkChunk->setDiffuse(Color4f(0.2f,0.9f,0.1f,0.3f));
    PSMaterialChunkChunk->setSpecular(Color4f(0.5f,0.4f,0.2f,0.6f));
    PSMaterialChunkChunk->setEmission(Color4f(0.2f,0.6f,0.5f,0.3f));
    PSMaterialChunkChunk->setColorMaterial(GL_NONE);

    //enable depth test
    DepthChunkRefPtr PSDepthChunk = DepthChunk::create();

    ChunkMaterialRefPtr PSMaterial = ChunkMaterial::create();
    PSMaterial->addChunk(PSPointChunk);
    PSMaterial->addChunk(PSMaterialChunkChunk);
    PSMaterial->addChunk(PSBlendChunk);
    PSMaterial->addChunk(PSDepthChunk);

    //Particle System
    ParticleSystemRefPtr ExampleParticleSystem = OSG::ParticleSystem::create();
    ExampleParticleSystem->attachUpdateListener(TutorialWindow);

    //Particle System Drawer
    //Point
    ExamplePointParticleSystemDrawer = OSG::PointParticleSystemDrawer::create();
    //ExamplePointParticleSystemDrawer->setForcePerParticleSizing(true);

    //Line
    ExampleLineParticleSystemDrawer = OSG::LineParticleSystemDrawer::create();
    ExampleLineParticleSystemDrawer->setLineDirectionSource(LineParticleSystemDrawer::DIRECTION_NORMAL);//DIRECTION_VELOCITY_CHANGE);
    ExampleLineParticleSystemDrawer->setLineLengthSource(LineParticleSystemDrawer::LENGTH_SIZE_X);
    ExampleLineParticleSystemDrawer->setEndPointFading(Vec2f(1.0,0.0));
    //Quad
    ExampleQuadParticleSystemDrawer = OSG::QuadParticleSystemDrawer::create();
    ExampleQuadParticleSystemDrawer->setQuadSizeScaling(Vec2f(0.1,0.1));
    ExampleQuadParticleSystemDrawer->setNormalAndUpSource(QuadParticleSystemDrawer::NORMAL_PARTICLE_NORMAL,QuadParticleSystemDrawer::UP_STATIC);

    RateParticleGeneratorRefPtr ExampleGeneratorTheSequel = OSG::RateParticleGenerator::create();

    //Attach the function objects to the Generator
    ExampleGeneratorTheSequel->setPositionDistribution(createPositionDistribution());
    ExampleGeneratorTheSequel->setLifespanDistribution(createLifespanDistribution());
    ExampleGeneratorTheSequel->setGenerationRate(300.0);
    ExampleGeneratorTheSequel->setVelocityDistribution(createVelocityDistribution());


    //Attach the Generator to the Particle System
    //ExampleParticleSystem->pushToGenerators(ExampleGenerator);
    ExampleParticleSystem->setMaxParticles(500);
    ExampleParticleSystem->pushToGenerators(ExampleGeneratorTheSequel);

    //Particle System Node
    ParticleNodeCore = OSG::ParticleSystemCore::create();
    ParticleNodeCore->setSystem(ExampleParticleSystem);
    ParticleNodeCore->setDrawer(ExamplePointParticleSystemDrawer);
    ParticleNodeCore->setMaterial(PSMaterial);

    NodeRefPtr ParticleNode = OSG::Node::create();
    ParticleNode->setCore(ParticleNodeCore);


    // Make Main Scene Node and add the Torus
    NodeRefPtr scene = OSG::Node::create();
    scene->setCore(OSG::Group::create());
    scene->addChild(ParticleNode);

    mgr->setRoot(scene);

    // Show the whole Scene
    mgr->showAll();

    mgr->getCamera()->setFar(500.0);

    //Open Window
    Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
    TutorialWindow->openWindow(WinPos,
                               WinSize,
                               "14ParticleSorting");

    //Enter main Loop
    TutorialWindow->mainLoop();

    osgExit();

    return 0;
}
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    TutorialWindow = createNativeWindow();
    TutorialWindow->initWindow();

    TutorialWindow->setDisplayCallback(display);
    TutorialWindow->setReshapeCallback(reshape);

    TutorialKeyListener TheKeyListener;
    TutorialWindow->addKeyListener(&TheKeyListener);

    // Make Torus Node (creates Torus in background of scene)
    NodeRefPtr TorusGeometryNode = makeTorus(.5, 2, 16, 16);

    // Make Main Scene Node and add the Torus
    NodeRefPtr scene = OSG::Node::create();
        scene->setCore(OSG::Group::create());
        scene->addChild(TorusGeometryNode);

    // Create the Graphics
    GraphicsRefPtr TutorialGraphics = OSG::Graphics2D::create();

    // Initialize the LookAndFeelManager to enable default settings
    LookAndFeelManager::the()->getLookAndFeel()->init();

    GradientBackgroundRefPtr TheBackground = GradientBackground::create();
    TheBackground->addLine(Color3f(1.0,0.0,0.0), 0.0);
    TheBackground->addLine(Color3f(0.0,1.0,0.0), 0.2);
    TheBackground->addLine(Color3f(0.0,0.0,1.0), 0.4);
    TheBackground->addLine(Color3f(0.0,1.0,1.0), 0.6);
    TheBackground->addLine(Color3f(1.0,1.0,0.0), 0.8);
    TheBackground->addLine(Color3f(1.0,1.0,1.0), 1.0);

    /******************************************************

            Create a List.  A List has several 
			parts to it:
			-ListModel: Contains the data which is to be
			    displayed in the List.  Data is added
				as shown below
			-ListCellRenderer: Creates the Components to
				be used within the List (the default
				setting is to create Labels using 
				the desired text).
			-ListSelectionModel: Determines how
				the List may be selected.

			To add values to the list:
            
            First, create SFStrings and use the 
            .setValue("Value") function to set their
            values.  Then, use the .pushBack(&SFStringName)
            to add them to the List.

            Next, create the CellRenderer and ListSelectionModel
            defaults.

            Finally, actually create the List.  Set
            its Model, CellRenderer, and SelectionModel
            as shown below.  Finally, choose the
            type of display for the List (choices outlined
            below).

    ******************************************************/

    // Add data to it
	ExampleListModel = MFieldListModel::create();
    ExampleListModel->setContainer(TheBackground);
    ExampleListModel->setFieldId(GradientBackground::ColorFieldId);

    /******************************************************

            Create ListCellRenderer and 
			ListSelectionModel.  Most 
			often the defauls will be used.
			
			Note: the ListSelectionModel was
			created above and is referenced
			by the ActionListeners.

    ******************************************************/    


    /******************************************************

            Create List itself and assign its 
			Model, CellRenderer, and SelectionModel
			to it.
			-setOrientation(ENUM): Determine the
				Layout of the cells (Horizontal
				or Vertical).  Takes List::VERTICAL_ORIENTATION
				and List::HORIZONTAL_ORIENTATION arguments.

    ******************************************************/    
    ExampleList = List::create();
        ExampleList->setPreferredSize(Vec2f(200, 300));
        ExampleList->setOrientation(List::VERTICAL_ORIENTATION);
        //ExampleList->setOrientation(List::HORIZONTAL_ORIENTATION);
		ExampleList->setModel(ExampleListModel);

    ExampleList->setSelectionModel(ExampleListSelectionModel);


    /******************************************************

            Determine the SelectionModel
            -SINGLE_SELECTION lets you select ONE item
                via a single mouse click
            -SINGLE_INTERVAL_SELECTION lets you select
                one interval via mouse and SHIFT key
            -MULTIPLE_INTERVAL_SELECTION lets you select
                via mouse, and SHIFT and CONTRL keys

            Note: this tutorial is currently set up
            to allow for this to be changed via 
			TogggleButtons with ActionListeners attached 
            to them so this code is commented out.

    ******************************************************/

    //SelectionModel.setMode(DefaultListSelectionModel::SINGLE_SELECTION);
    //SelectionModel.setMode(DefaultListSelectionModel::SINGLE_INTERVAL_SELECTION);
    //SelectionModel.setMode(DefaultListSelectionModel::MULTIPLE_INTERVAL_SELECTION);

    // Create a ScrollPanel for easier viewing of the List (see 27ScrollPanel)
    ScrollPanelRefPtr ExampleScrollPanel = ScrollPanel::create();
        ExampleScrollPanel->setPreferredSize(Vec2f(200,300));
        ExampleScrollPanel->setHorizontalResizePolicy(ScrollPanel::RESIZE_TO_VIEW);
        //ExampleScrollPanel->setVerticalResizePolicy(ScrollPanel::RESIZE_TO_VIEW);
    ExampleScrollPanel->setViewComponent(ExampleList);

    // Create MainFramelayout
    FlowLayoutRefPtr MainInternalWindowLayout = OSG::FlowLayout::create();
    MainInternalWindowLayout->setOrientation(FlowLayout::VERTICAL_ORIENTATION);
    MainInternalWindowLayout->setMajorAxisAlignment(0.5f);
    MainInternalWindowLayout->setMinorAxisAlignment(0.5f);

    LabelRefPtr ListLabel = Label::create();
    ListLabel->setText("Background Colors List");
    ListLabel->setPreferredSize(Vec2f(200.0f, ListLabel->getPreferredSize().y()));

    // Create The Main InternalWindow
    // Create Background to be used with the Main InternalWindow
    ColorLayerRefPtr MainInternalWindowBackground = OSG::ColorLayer::create();
        MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));

    InternalWindowRefPtr MainInternalWindow = OSG::InternalWindow::create();
    MainInternalWindow->pushToChildren(ListLabel);
    MainInternalWindow->pushToChildren(ExampleScrollPanel);
    MainInternalWindow->setLayout(MainInternalWindowLayout);
    MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
    MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
    MainInternalWindow->setScalingInDrawingSurface(Vec2f(0.7f,0.5f));
    MainInternalWindow->setDrawTitlebar(false);
    MainInternalWindow->setResizable(false);

    // Create the Drawing Surface
    UIDrawingSurfaceRefPtr TutorialDrawingSurface = UIDrawingSurface::create();
        TutorialDrawingSurface->setGraphics(TutorialGraphics);
        TutorialDrawingSurface->setEventProducer(TutorialWindow);
    
	TutorialDrawingSurface->openWindow(MainInternalWindow);

    // Create the UI Foreground Object
    UIForegroundRefPtr TutorialUIForeground = OSG::UIForeground::create();

        TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // Tell the Manager what to manage
    mgr->setWindow(TutorialWindow);
    mgr->setRoot(scene);

    // Add the UI Foreground Object to the Scene
    ViewportRefPtr TutorialViewport = mgr->getWindow()->getPort(0);
    TutorialViewport->addForeground(TutorialUIForeground);
    TutorialViewport->setBackground(TheBackground);

    // Show the whole Scene
    mgr->showAll();


    //Open Window
    Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
    TutorialWindow->openWindow(WinPos,
            WinSize,
            "44MFieldList");

    //Enter main Loop
    TutorialWindow->mainLoop();

    osgExit();

    return 0;
}
int main(int argc, char **argv)
{
    preloadSharedObject("OSGImageFileIO");
    // OSG init
    osgInit(argc,argv);

    {
        // Set up Window
        WindowEventProducerRecPtr TutorialWindow = createNativeWindow();
        TutorialWindow->initWindow();

        // Create the SimpleSceneManager helper
        SimpleSceneManager sceneManager;
        TutorialWindow->setDisplayCallback(boost::bind(display, &sceneManager));
        TutorialWindow->setReshapeCallback(boost::bind(reshape, _1, &sceneManager));

        // Tell the Manager what to manage
        sceneManager.setWindow(TutorialWindow);

        //Attach to events
        TutorialWindow->connectMousePressed(boost::bind(mousePressed, _1, &sceneManager));
        TutorialWindow->connectMouseReleased(boost::bind(mouseReleased, _1, &sceneManager));
        TutorialWindow->connectMouseMoved(boost::bind(mouseMoved, _1, &sceneManager));
        TutorialWindow->connectMouseDragged(boost::bind(mouseDragged, _1, &sceneManager));
        TutorialWindow->connectMouseWheelMoved(boost::bind(mouseWheelMoved, _1, &sceneManager));

        // Creating the Particle System Material
        // Here, the image is loaded.  The entire image sequence is conatined in one image,
        // which reduces texture memory overhead and runs faster.
        TextureObjChunkRefPtr QuadTextureChunk = TextureObjChunk::create();
        ImageRefPtr LoadedImage = ImageFileHandler::the()->read("Data/SpriteExplode.png");    
        QuadTextureChunk->setImage(LoadedImage);

        TextureEnvChunkRefPtr QuadTextureEnvChunk = TextureEnvChunk::create();
        QuadTextureEnvChunk->setEnvMode(GL_MODULATE);

        BlendChunkRefPtr PSBlendChunk = BlendChunk::create();
        PSBlendChunk->setSrcFactor(GL_SRC_ALPHA);
        PSBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);

        MaterialChunkRefPtr PSMaterialChunk = MaterialChunk::create();
        PSMaterialChunk->setAmbient(Color4f(0.3f,0.0f,0.0f,1.0f));
        PSMaterialChunk->setDiffuse(Color4f(0.7f,0.0f,0.0f,1.0f));
        PSMaterialChunk->setSpecular(Color4f(0.9f,0.0f,0.0f,1.0f));
        PSMaterialChunk->setColorMaterial(GL_AMBIENT_AND_DIFFUSE);

        ChunkMaterialRefPtr PSMaterial = ChunkMaterial::create();
        PSMaterial->addChunk(QuadTextureChunk);
        PSMaterial->addChunk(QuadTextureEnvChunk);
        PSMaterial->addChunk(PSMaterialChunk);
        PSMaterial->addChunk(PSBlendChunk);

        //Particle System
        ParticleSystemRecPtr ExampleParticleSystem = ParticleSystem::create();
        ExampleParticleSystem->attachUpdateProducer(TutorialWindow);

        //Age Particle Function.  Controls which image is shown when, based on the age of a particle.
        AgeParticleFunctionRecPtr AgeFunc = AgeParticleFunction::create();
        AgeFunc->setSequenceTime(0.1f); // image changes every 0.1 seconds.
        AgeFunc->setSequenceOrder(AgeParticleFunction::CUSTOM); // using the custom sequence below.
        /*
           Here, a custom sequence for the image ordering is assembled.  The image sequence will be shown in 
           the order specified here.  Once the end of the sequence is reached, the sequence repeats.
           */
        AgeFunc->editMFCustomSequence()->push_back(0);
        AgeFunc->editMFCustomSequence()->push_back(1);
        AgeFunc->editMFCustomSequence()->push_back(2);
        AgeFunc->editMFCustomSequence()->push_back(3);
        AgeFunc->editMFCustomSequence()->push_back(4);
        AgeFunc->editMFCustomSequence()->push_back(5);
        AgeFunc->editMFCustomSequence()->push_back(4);
        AgeFunc->editMFCustomSequence()->push_back(3);
        AgeFunc->editMFCustomSequence()->push_back(2);
        AgeFunc->editMFCustomSequence()->push_back(1);

        //Particle System Drawer - 
        QuadSequenceParticleSystemDrawerRecPtr ExampleParticleSystemDrawer = QuadSequenceParticleSystemDrawer::create();
        // image dimensions (in pixels) are required if there is a border on the images.
        ExampleParticleSystemDrawer->setImageDimensions(Vec2us(780,520));
        // The "dimensions" of the sequence contained in the image.  For this image,
        // there are 3 images in the "x" direction, and two in the "y" direction, for a 
        // total of 6.
        ExampleParticleSystemDrawer->setSequenceDimensions(Vec2b(3,2));
        // width of the border on each side of the image, in pixels.
        ExampleParticleSystemDrawer->setBorderOffsets(Vec2b(0,0));
        // this is the age function we just created above.
        ExampleParticleSystemDrawer->setSequenceFunction(AgeFunc);

        RateParticleGeneratorRecPtr ExampleParticleGenerator = RateParticleGenerator::create();
        //Attach the function objects to the Generator
        ExampleParticleGenerator->setPositionDistribution(createPositionDistribution());
        ExampleParticleGenerator->setLifespanDistribution(createLifespanDistribution());
        ExampleParticleGenerator->setVelocityDistribution(createVelocityDistribution());
        ExampleParticleGenerator->setAccelerationDistribution(createAccelerationDistribution());
        ExampleParticleGenerator->setSizeDistribution(createSizeDistribution());
        ExampleParticleGenerator->setGenerationRate(40.0f);

        //Particle System Node
        ParticleSystemCoreRefPtr ParticleNodeCore = ParticleSystemCore::create();
        ParticleNodeCore->setSystem(ExampleParticleSystem);
        ParticleNodeCore->setDrawer(ExampleParticleSystemDrawer);
        ParticleNodeCore->setMaterial(PSMaterial);
        ParticleNodeCore->setSortingMode(ParticleSystemCore::BACK_TO_FRONT);

        NodeRefPtr ParticleNode = Node::create();
        ParticleNode->setCore(ParticleNodeCore);

        ExampleParticleSystem->addParticle(Pnt3f(10.0,0.0,0.0),
                                           Vec3f(0.0,1.0,0.0),
                                           Color4f(1.0,1.0,1.0,1.0),
                                           Vec3f(1.0,1.0,1.0),
                                           0.01,
                                           Vec3f(0.0,0.0,0.0),
                                           Vec3f(0.0,0.0,0.0));

        ExampleParticleSystem->addParticle(Pnt3f(-10.0,0.0,0.0),
                                           Vec3f(0.0,1.0,0.0),
                                           Color4f(1.0,1.0,1.0,1.0),
                                           Vec3f(1.0,1.0,1.0),
                                           0.01,
                                           Vec3f(0.0,0.0,0.0),
                                           Vec3f(0.0,0.0,0.0));

        ExampleParticleSystem->pushToGenerators(ExampleParticleGenerator);
        // Make Main Scene Node and add the Torus
        NodeRefPtr scene = makeCoredNode<Group>();
        scene->addChild(ParticleNode);

        TutorialWindow->connectKeyTyped(boost::bind(keyTyped, _1,
                                                    &sceneManager,
                                                    AgeFunc.get()));

        sceneManager.setRoot(scene);

        // Show the whole Scene
        sceneManager.showAll();

        //Open Window
        Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
        Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
        TutorialWindow->openWindow(WinPos,
                                   WinSize,
                                   "05a - QuadSequenceParticleDrawer");

        //Enter main Loop
        TutorialWindow->mainLoop();
    }

    osgExit();

    return 0;
}
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    {
        // Set up Window
        WindowEventProducerRecPtr TutorialWindow = createNativeWindow();
        TutorialWindow->initWindow();

        // Create the SimpleSceneManager helper
        SimpleSceneManager sceneManager;
        TutorialWindow->setDisplayCallback(boost::bind(display, &sceneManager));
        TutorialWindow->setReshapeCallback(boost::bind(reshape, _1, &sceneManager));

        // Tell the Manager what to manage
        sceneManager.setWindow(TutorialWindow);

        //Attach to events
        TutorialWindow->connectMousePressed(boost::bind(mousePressed, _1, &sceneManager));
        TutorialWindow->connectMouseReleased(boost::bind(mouseReleased, _1, &sceneManager));
        TutorialWindow->connectMouseMoved(boost::bind(mouseMoved, _1, &sceneManager));
        TutorialWindow->connectMouseDragged(boost::bind(mouseDragged, _1, &sceneManager));
        TutorialWindow->connectMouseWheelMoved(boost::bind(mouseWheelMoved, _1, &sceneManager));

        //Particle System Material
        PointChunkRefPtr PSPointChunk = PointChunk::create();
        PSPointChunk->setSize(5.0f);
        PSPointChunk->setSmooth(true);

        BlendChunkRefPtr PSBlendChunk = BlendChunk::create();
        PSBlendChunk->setSrcFactor(GL_SRC_ALPHA);
        PSBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);

        MaterialChunkRefPtr PSMaterialChunkChunk = MaterialChunk::create();
        PSMaterialChunkChunk->setAmbient(Color4f(1.0f,1.0f,1.0f,1.0f));
        PSMaterialChunkChunk->setDiffuse(Color4f(0.7f,0.7f,0.7f,1.0f));
        PSMaterialChunkChunk->setSpecular(Color4f(0.9f,0.9f,0.9f,1.0f));
        PSMaterialChunkChunk->setColorMaterial(GL_NONE);

        ChunkMaterialRefPtr PSMaterial = ChunkMaterial::create();
        PSMaterial->addChunk(PSPointChunk);
        PSMaterial->addChunk(PSMaterialChunkChunk);
        PSMaterial->addChunk(PSBlendChunk);

        //Particle System
        ParticleSystemRefPtr ExampleParticleSystem = ParticleSystem::create();
        ExampleParticleSystem->addParticle(Pnt3f(0,25,0),
                                           Vec3f(0.0,0.0f,1.0f),
                                           Color4f(1.0,1.0,1.0,1.0), 
                                           Vec3f(1.0,1.0,1.0), 
                                           0.1, 
                                           Vec3f(0.0f,0.0f,0.0f), //Velocity
                                           Vec3f(0.0f,0.0f,0.0f)
                                          );
        ExampleParticleSystem->addParticle(Pnt3f(0,-25,0),
                                           Vec3f(0.0,0.0f,1.0f),
                                           Color4f(1.0,1.0,1.0,1.0), 
                                           Vec3f(1.0,1.0,1.0), 
                                           0.1, 
                                           Vec3f(0.0f,0.0f,0.0f), //Velocity
                                           Vec3f(0.0f,0.0f,0.0f)
                                          );
        ExampleParticleSystem->attachUpdateProducer(TutorialWindow);

        //Particle System Drawer (Point)
        PointParticleSystemDrawerRecPtr ExamplePointParticleSystemDrawer = PointParticleSystemDrawer::create();

        //Particle System Drawer (line)
        LineParticleSystemDrawerRecPtr ExampleLineParticleSystemDrawer = LineParticleSystemDrawer::create();
        ExampleLineParticleSystemDrawer->setLineDirectionSource(LineParticleSystemDrawer::DIRECTION_VELOCITY);
        ExampleLineParticleSystemDrawer->setLineLengthSource(LineParticleSystemDrawer::LENGTH_SIZE_X);
        ExampleLineParticleSystemDrawer->setLineLength(2.0f);
        ExampleLineParticleSystemDrawer->setEndPointFading(Vec2f(0.0f,1.0f));

        //Create a Rate Particle Generator
        RateParticleGeneratorRefPtr ExampleGenerator = RateParticleGenerator::create();

        //Attach the function objects to the Generator
        ExampleGenerator->setPositionDistribution(createPositionDistribution());
        ExampleGenerator->setLifespanDistribution(createLifespanDistribution());
        ExampleGenerator->setGenerationRate(200);

        UniformParticleAffectorRecPtr ExampleUniformAffector = UniformParticleAffector::create();
        ExampleUniformAffector->setMagnitude(20.0); // force which the field exerts on particles (negative = towards the air field's beacon location)
        NodeRefPtr UniformBeacon = Node::create();
        ExampleUniformAffector->setBeacon(UniformBeacon); // set to 'emulate' from (0,0,0)
        ExampleUniformAffector->setDirection(Vec3f(1.0,0.0,0.0)); // direction which field is exerted
        ExampleUniformAffector->setMaxDistance(-1.0); // particles affected regardless of distance from
        ExampleUniformAffector->setAttenuation(0.0); // strength of uniform field dimishes by dist^attenuation, in this case it is constant regardless of distance
        ExampleUniformAffector->setParticleMass(10.0);



        //Attach the Generator and Affector to the Particle System
        ExampleParticleSystem->pushToGenerators(ExampleGenerator);
        ExampleParticleSystem->pushToAffectors(ExampleUniformAffector);
        ExampleParticleSystem->setMaxParticles(500);


        //Particle System Node
        ParticleSystemCoreRecPtr ParticleNodeCore = ParticleSystemCore::create();
        ParticleNodeCore->setSystem(ExampleParticleSystem);
        ParticleNodeCore->setDrawer(ExamplePointParticleSystemDrawer);
        ParticleNodeCore->setMaterial(PSMaterial);

        NodeRefPtr ParticleNode = Node::create();
        ParticleNode->setCore(ParticleNodeCore);


        // Make Main Scene Node and add the Torus
        NodeRefPtr scene = Node::create();
        scene->setCore(Group::create());
        scene->addChild(ParticleNode);

        TutorialWindow->connectKeyTyped(boost::bind(keyTyped, _1,
                                                    &sceneManager,
                                                    ParticleNodeCore.get(),
                                                    ExamplePointParticleSystemDrawer.get(),
                                                    ExampleLineParticleSystemDrawer.get(),
                                                    ExampleUniformAffector.get()));

        sceneManager.setRoot(scene);

        // Show the whole Scene
        sceneManager.showAll();

        sceneManager.getCamera()->setFar(1000.0);

        std::cout << "Uniform Particle Affector Tutorial Controls:\n"
            << "1: Use point drawer\n"
            << "2: Use line drawer\n"
            << "W,A,S,D: Change direction of field\n"
            << "Ctrl + Q: Exit Tutorial";

        //Open Window
        Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
        Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
        TutorialWindow->openWindow(WinPos,
                                   WinSize,
                                   "19UniformFieldParticleAffector");

        //Enter main Loop
        TutorialWindow->mainLoop();

    }
    osgExit();

    return 0;
}
Example #28
0
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindow = createNativeWindow();
    TutorialWindow->initWindow();

    TutorialWindow->setDisplayCallback(display);
    TutorialWindow->setReshapeCallback(reshape);

    TutorialKeyListener TheKeyListener;
    TutorialWindow->addKeyListener(&TheKeyListener);

    // Make Torus Node (creates Torus in background of scene)
    NodeRefPtr TorusGeometryNode = makeTorus(.5, 2, 16, 16);

    // Make Main Scene Node and add the Torus
    NodeRefPtr scene = OSG::Node::create();
        scene->setCore(OSG::Group::create());
        scene->addChild(TorusGeometryNode);

    // Create the Graphics
    GraphicsRefPtr TutorialGraphics = OSG::Graphics2D::create();

    // Initialize the LookAndFeelManager to enable default settings
    LookAndFeelManager::the()->getLookAndFeel()->init();

    // Create a simple Font to be used with the ExampleTextArea
    UIFontRefPtr ExampleFont = OSG::UIFont::create();
        ExampleFont->setSize(16);

    /******************************************************


        Create and edit the TextArea and determine its 
        characteristics.  A TextArea is a component 
        that allows you to enter text into the box via 
        keyboard input.  You can select text by    using 
        your mouse or pressing shift and the left and 
        right arrow keys.

        The only difference between a TextArea and
        TextField is that a TextArea can have 
        multiple lines of text 
        within it.

        -setTextColor(Color4f): Determine color of 
            text within TextArea.
        -setSelectionBoxColor(Color4f): Determine the
			color that highlighting around the 
			selected text appears.
        -setSelectionTextColor(Color4f): Determine the 
            color the selected text appears.
        -setText("TextToBeDisplayed"): Determine  
            initial text within TextArea.
        -setFont(FontName): Determine the Font 
			used within TextArea
        -setSelectionStart(StartCharacterNumber):
            Determine the character which the 
            selection will initially start after.
        -setSelectionEnd(EndCharacterNumber): 
            Determine the character which the 
            selection will end before.
        -setCaretPosition(Location): Determine the 
            location of the Caret within the TextArea.
			Note: this does not do too much
            currently because the only way 
            to cause the TextArea to gain focus is
            to click within it, causing the 
            Caret to move.
            
    ******************************************************/

    // Create a TextArea component
    TextAreaRefPtr ExampleTextArea = OSG::TextArea::create();

        ExampleTextArea->setPreferredSize(Vec2f(300, 200));
        ExampleTextArea->setMinSize(Vec2f(300, 200));
        ExampleTextArea->setTextColor(Color4f(0.0, 0.0, 0.0, 1.0));
        ExampleTextArea->setSelectionBoxColor(Color4f(0.0, 0.0, 1.0, 1.0));
        ExampleTextArea->setSelectionTextColor(Color4f(1.0, 1.0, 1.0, 1.0));
        // Determine the font and initial text
        ExampleTextArea->setText("What");
        ExampleTextArea->setFont(ExampleFont);
        // This will select the "a" from above
        ExampleTextArea->setSelectionStart(2);
        ExampleTextArea->setSelectionEnd(3);
        ExampleTextArea->setCaretPosition(2);
        //ExampleTextArea->setLineWrap(false);
        
    // Create a ScrollPanel
    ScrollPanelRefPtr TextAreaScrollPanel = ScrollPanel::create();
        TextAreaScrollPanel->setPreferredSize(Vec2f(200,200));
        TextAreaScrollPanel->setHorizontalResizePolicy(ScrollPanel::RESIZE_TO_VIEW);
    // Add the TextArea to the ScrollPanel so it is displayed
	TextAreaScrollPanel->setViewComponent(ExampleTextArea);

    
    // Create The Main InternalWindow
    // Create Background to be used with the Main InternalWindow
    ColorLayerRefPtr MainInternalWindowBackground = OSG::ColorLayer::create();
        MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));

    LayoutRefPtr MainInternalWindowLayout = OSG::FlowLayout::create();

    InternalWindowRefPtr MainInternalWindow = OSG::InternalWindow::create();
       MainInternalWindow->pushToChildren(TextAreaScrollPanel);
       MainInternalWindow->setLayout(MainInternalWindowLayout);
       MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
	   MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
	   MainInternalWindow->setScalingInDrawingSurface(Vec2f(0.5f,0.5f));
	   MainInternalWindow->setDrawTitlebar(false);
	   MainInternalWindow->setResizable(false);

    // Create the Drawing Surface
    UIDrawingSurfaceRefPtr TutorialDrawingSurface = UIDrawingSurface::create();
        TutorialDrawingSurface->setGraphics(TutorialGraphics);
        TutorialDrawingSurface->setEventProducer(TutorialWindow);
	
	TutorialDrawingSurface->openWindow(MainInternalWindow);

    // Create the UI Foreground Object
    UIForegroundRefPtr TutorialUIForeground = OSG::UIForeground::create();

        TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);


    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // Tell the Manager what to manage
    mgr->setWindow(TutorialWindow);
    mgr->setRoot(scene);

    // Add the UI Foreground Object to the Scene
    ViewportRefPtr TutorialViewport = mgr->getWindow()->getPort(0);
        TutorialViewport->addForeground(TutorialUIForeground);

    // Show the whole Scene
    mgr->showAll();


    //Open Window
    Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
    TutorialWindow->openWindow(WinPos,
            WinSize,
            "22TextArea");

    //Enter main Loop
    TutorialWindow->mainLoop();

    osgExit();

    return 0;
}
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    {
        // Set up Window
        WindowEventProducerRecPtr TutorialWindow = createNativeWindow();

        //Initialize Window
        TutorialWindow->initWindow();

        SimpleSceneManager sceneManager;
        TutorialWindow->setDisplayCallback(boost::bind(display, &sceneManager));
        TutorialWindow->setReshapeCallback(boost::bind(reshape, _1, &sceneManager));

        // Tell the Manager what to manage
        sceneManager.setWindow(TutorialWindow);

        //Attach to events
        TutorialWindow->connectMousePressed(boost::bind(mousePressed, _1, &sceneManager));
        TutorialWindow->connectMouseReleased(boost::bind(mouseReleased, _1, &sceneManager));
        TutorialWindow->connectMouseDragged(boost::bind(mouseDragged, _1, &sceneManager));
        TutorialWindow->connectMouseWheelMoved(boost::bind(mouseWheelMoved, _1, &sceneManager));

        BoostPath FilePath("../Animation/Data/Nanobot.dae");
        if(argc >= 2)
        {
            FilePath = BoostPath(argv[1]);
            if(!boost::filesystem::exists(FilePath))
            {
                std::cerr << "Could not load file: "<< FilePath.string()
                          << ", because no such files exists."<< std::endl;
                FilePath = BoostPath("../Animation/Data/Nanobot.dae");
            }
        }

        NodeRefPtr LoadedRoot;
        std::vector<AnimationRecPtr> LoadedAnimations;

        FCFileType::FCPtrStore ObjStore;
        try
        {
            ObjStore = FCFileHandler::the()->read(FilePath);
        }
        catch(std::exception &ex)
        {
            std::cerr << "Failed to load file: " << FilePath.string() << ", error:"
                     << ex.what()                        << std::endl;
            return -1;
        }
        for(FCFileType::FCPtrStore::iterator StorItor(ObjStore.begin());
            StorItor != ObjStore.end();
            ++StorItor)
        {
            //Animations
            if((*StorItor)->getType().isDerivedFrom(Animation::getClassType()))
            {
                LoadedAnimations.push_back(dynamic_pointer_cast<Animation>(*StorItor));
                LoadedAnimations.back()->attachUpdateProducer(TutorialWindow);
                LoadedAnimations.back()->start();
            }
            //Root Node
            if((*StorItor)->getType() == Node::getClassType() &&
                    dynamic_pointer_cast<Node>(*StorItor)->getParent() == NULL)
            {
                LoadedRoot = dynamic_pointer_cast<Node>(*StorItor);
            }
        }

        if(LoadedRoot == NULL)
        {
            LoadedRoot = SceneFileHandler::the()->read(FilePath.string().c_str());
        }

        if(LoadedRoot == NULL)
        {
            LoadedRoot= makeTorus(.5, 2, 32, 32);
        }

        //Make the fog node
        PostShaderStageRecPtr PostShaderStageCore = PostShaderStage::create();
        PostShaderStageCore->clearPasses();
        PostShaderStageCore->addPass("", generateNoEffectProg());


        DirectionalLightRecPtr SceneLightCore = DirectionalLight::create();
        SceneLightCore->setAmbient(Color4f(0.2f, 0.2f, 0.2f, 1.0f));
        SceneLightCore->setDiffuse(Color4f(0.8f, 0.8f, 0.8f, 1.0f));
        SceneLightCore->setSpecular(Color4f(1.0f, 1.0f, 1.0f, 1.0f));

        NodeRefPtr SceneLight = makeNodeFor(SceneLightCore);
        SceneLight->addChild(LoadedRoot);

        NodeRefPtr PostShaderStageNode = makeNodeFor(PostShaderStageCore);
        PostShaderStageNode->addChild(SceneLight);

        //Make Main Scene Node
        NodeRefPtr scene = makeCoredNode<Group>();

        scene->addChild(PostShaderStageNode);

        // tell the manager what to manage
        sceneManager.setRoot  (scene);
        SceneLightCore->setBeacon(sceneManager.getCamera()->getBeacon());

        //Create the Documentation Foreground and add it to the viewport
        SimpleScreenDoc TheSimpleScreenDoc(&sceneManager, TutorialWindow);

        // show the whole scene
        sceneManager.showAll();

        sceneManager.getWindow()->getPort(0)->setTravMask(1);
        RenderOptionsRecPtr ViewportRenderOptions = RenderOptions::create();
        ViewportRenderOptions->setRenderProperties(0x0);
        ViewportRenderOptions->setRenderProperties(RenderPropertiesPool::the()->getFrom1("Default"));
        ViewportRenderOptions->setRenderProperties(0x01);

        sceneManager.getWindow()->getPort(0)->setRenderOptions(ViewportRenderOptions);

        Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
        Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
        TutorialWindow->openWindow(WinPos,
                                   WinSize,
                                   "Collada Loader");

        TutorialWindow->connectKeyPressed(boost::bind(keyPressed, _1,
                                                      TutorialWindow.get(),
                                                      PostShaderStageCore.get()));

        //Enter main Loop
        TutorialWindow->mainLoop();

    }

    osgExit();

    return 0;
}
Example #30
0
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    {
        TheLuaManager->init();

        // Set up Window
        WindowEventProducerRecPtr TutorialWindow = createNativeWindow();
        TutorialWindow->initWindow();

        // Create the SimpleSceneManager helper
        SimpleSceneManager sceneManager;
        TutorialWindow->setDisplayCallback(boost::bind(display, &sceneManager));
        TutorialWindow->setReshapeCallback(boost::bind(reshape, _1, &sceneManager));

        // Tell the Manager what to manage
        sceneManager.setWindow(TutorialWindow);

        //Setup the Lua Manager

        BoostPath ModulePath("./Data/");
        std::string PackagePath = std::string("?;")
            + (ModulePath / "?.lua" ).file_string() + ";"
            + (ModulePath / "?" /  "init.lua").file_string();
        TheLuaManager->setPackagePath(PackagePath);

        // Make Torus Node (creates Torus in background of scene)
        GeometryRefPtr TorusGeometry = makeTorusGeo(.5, 2, 16, 16);
        setName(TorusGeometry,"Torus Geometry");
        //calcVertexTangents(TorusGeometry,0,Geometry::TexCoords7FieldId, Geometry::TexCoords6FieldId);


        NodeRefPtr TorusGeometryNode = Node::create();
        setName(TorusGeometryNode,"Torus Geometry Node");
        TorusGeometryNode->setCore(TorusGeometry);

        //Torus Transformation Node
        TransformRefPtr TheTorusNodeTransform = Transform::create();

        NodeRefPtr TheTorusTransfromNode = Node::create();
        TheTorusTransfromNode->setCore(TheTorusNodeTransform);
        TheTorusTransfromNode->addChild(TorusGeometryNode);
        setName(TheTorusTransfromNode,"Torus Transform Node");

        // Make Main Scene Node and add the Torus
        NodeRefPtr scene = Node::create();
        scene->setCore(Group::create());
        scene->addChild(TheTorusTransfromNode);
        setName(scene,"Scene Node");

        //Light Beacon Node
        TransformRefPtr TheLightBeaconNodeTransform = Transform::create();

        NodeRefPtr TheLightBeaconNode = Node::create();
        TheLightBeaconNode->setCore(TheLightBeaconNodeTransform);
        setName(TheLightBeaconNode,"Light Beacon Node");


        //Light Node
        DirectionalLightRefPtr TheLightCore = DirectionalLight::create();
        TheLightCore->setDirection(Vec3f(1.0,0.0,0.0));
        TheLightCore->setAmbient(Color4f(1.0,1.0,1.0,1.0));
        TheLightCore->setDiffuse(Color4f(1.0,1.0,1.0,1.0));
        TheLightCore->setSpecular(Color4f(1.0,1.0,1.0,1.0));
        TheLightCore->setBeacon(TheLightBeaconNode);

        NodeRefPtr TheLightNode = Node::create();
        TheLightNode->setCore(TheLightCore);
        TheLightNode->addChild(scene);
        setName(TheLightNode,"Light Node");

        NodeRefPtr RootNode = Node::create();
        RootNode->setCore(Group::create());
        RootNode->addChild(TheLightNode);
        RootNode->addChild(TheLightBeaconNode);
        setName(RootNode,"Root Node");

        // Create the Graphics
        GraphicsRefPtr TutorialGraphics = Graphics2D::create();

        // Initialize the LookAndFeelManager to enable default settings
        LookAndFeelManager::the()->getLookAndFeel()->init();

        //Create the Main interface
        LuaDebuggerInterface TheLuaDebuggerInterface;

        // Create The Main InternalWindow
        // Create Background to be used with the Main InternalWindow
        ColorLayerRefPtr MainInternalWindowBackground = ColorLayer::create();
        MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));

        BorderLayoutRefPtr MainInternalWindowLayout = BorderLayout::create();

        //Split Panel
        BorderLayoutConstraintsRefPtr SplitPanelConstraints = BorderLayoutConstraints::create();
        SplitPanelConstraints->setRegion(BorderLayoutConstraints::BORDER_CENTER);
        TheLuaDebuggerInterface.getMainSplitPanel()->setConstraints(SplitPanelConstraints);

        BorderLayoutConstraintsRefPtr ButtonPanelConstraints = BorderLayoutConstraints::create();
        ButtonPanelConstraints->setRegion(BorderLayoutConstraints::BORDER_NORTH);
        TheLuaDebuggerInterface.getButtonPanel()->setConstraints(ButtonPanelConstraints);

        BorderLayoutConstraintsRefPtr CodeAreaInfoPanelConstraints = BorderLayoutConstraints::create();
        CodeAreaInfoPanelConstraints->setRegion(BorderLayoutConstraints::BORDER_SOUTH);
        TheLuaDebuggerInterface.getCodeAreaInfoPanel()->setConstraints(CodeAreaInfoPanelConstraints);

        InternalWindowRefPtr MainInternalWindow = InternalWindow::create();
        MainInternalWindow->pushToChildren(TheLuaDebuggerInterface.getButtonPanel());
        MainInternalWindow->pushToChildren(TheLuaDebuggerInterface.getMainSplitPanel());
        MainInternalWindow->pushToChildren(TheLuaDebuggerInterface.getCodeAreaInfoPanel());
        MainInternalWindow->setLayout(MainInternalWindowLayout);
        MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
        MainInternalWindow->setTitle("Lua Debugger");
        setName(MainInternalWindow,"Internal Window");

        // Create the Drawing Surface
        UIDrawingSurfaceRefPtr TutorialDrawingSurface = UIDrawingSurface::create();
        TutorialDrawingSurface->setGraphics(TutorialGraphics);
        TutorialDrawingSurface->setEventProducer(TutorialWindow);

        TutorialDrawingSurface->openWindow(MainInternalWindow);

        // Create the UI Foreground Object
        UIForegroundRefPtr TutorialUIForeground = UIForeground::create();

        TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);

        //Scene Background
        GradientBackgroundRefPtr SceneBackground = GradientBackground::create();
        SceneBackground->addLine(Color3f(0.0,0.0,0.0),0.0);
        setName(SceneBackground,"Scene Background");

        // Tell the Manager what to manage
        sceneManager.setWindow(TutorialWindow);
        sceneManager.setRoot(RootNode);
        //sceneManager.setHeadlight(false);

        // Add the UI Foreground Object to the Scene
        ViewportRefPtr TutorialViewport = sceneManager.getWindow()->getPort(0);
        TutorialViewport->addForeground(TutorialUIForeground);
        TutorialViewport->setBackground(SceneBackground);

        TutorialWindow->connectKeyTyped(boost::bind(keyTyped,
                                                    _1,
                                                    &TheLuaDebuggerInterface));

        // Show the whole Scene
        sceneManager.showAll();


        //Open Window
        Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
        Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
        TutorialWindow->openWindow(WinPos,
                                   WinSize,
                                   "03LuaDebugger");

        MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
        MainInternalWindow->setPreferredSize(WinSize * 0.85);

        //Enter main Loop
        TutorialWindow->mainLoop();

        TheLuaManager->uninit();
    }

    osgExit();

    return 0;
}