示例#1
0
int main (int argc, char **argv)
{
	osgInit(argc,argv);

	// GLUT init

	glutInit(&argc, argv);
	glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
	int winid = glutCreateWindow("OpenSG");
	glutKeyboardFunc(key);
	glutVisibilityFunc(vis);
	glutReshapeFunc(reshape);
	glutDisplayFunc(display);       
	glutMouseFunc(mouse);   
	glutMotionFunc(motion); 
	
	glutIdleFunc(display);	


    glEnable( GL_NORMALIZE );
    glEnable( GL_DEPTH_TEST );

	// OSG

	// create the graph

	// beacon for camera and light	
    NodePtr b1n = Node::create();
    GroupPtr b1 = Group::create();
	beginEditCP(b1n);
	b1n->setCore( b1 );
	endEditCP(b1n);

	// transformation
    NodePtr t1n = Node::create();
    TransformPtr t1 = Transform::create();
	beginEditCP(t1n);
	t1n->setCore( t1 );
	t1n->addChild( b1n );
	endEditCP(t1n);

	cam_trans = t1;

	// light
	
	NodePtr dlight = Node::create();
	headlight = DirectionalLight::create();

	beginEditCP(dlight);
	dlight->setCore( headlight );
	endEditCP(dlight);
	
	beginEditCP(headlight);
	headlight->setAmbient( .3, .3, .3, 1 );
	headlight->setDiffuse( 1, 1, 1, 1 );
	headlight->setSpecular( 1, 1, 1, 1 );
	headlight->setDirection(0,0,1);
	headlight->setBeacon( b1n);
	endEditCP(headlight);

	// root
    root = Node::create();
    GroupPtr gr1 = Group::create();
	beginEditCP(root);
	root->setCore( gr1 );
	root->addChild( t1n );
	root->addChild( dlight );
	endEditCP(root);

	// Create the scene

    NodePtr sroot = Node::create();

 	beginEditCP(dlight);
    dlight->addChild(sroot);
   	endEditCP(dlight);

    GroupPtr gr = Group::create();

    beginEditCP(sroot);
    sroot->setCore(gr);
    endEditCP(sroot);

    // a transform to move it around
 
    NodePtr tnode = Node::create();
    tr = Transform::create();
    beginEditCP(tnode);
    tnode->setCore( tr );
    endEditCP(tnode);

    beginEditCP(sroot);
    sroot->addChild(tnode);
    endEditCP(sroot);

    // the billboard
 
    NodePtr bnode = Node::create();
    bill = Billboard::create();
    beginEditCP(bnode);
    bnode->setCore( bill );
    endEditCP(bnode);

    beginEditCP(tnode);
    tnode->addChild(bnode);
    endEditCP(tnode);
  
    // a geometry to billboard
    NodePtr geo = makeTorus( .2, 1, 16, 3);

    beginEditCP(bnode);
    bnode->addChild( geo );
    endEditCP(bnode);
 
    // a geometry to lead the render action somewhere else
    geo = makePlane( 2, 2, 2, 2 );

    beginEditCP(sroot);
    sroot->addChild( geo );
    endEditCP(sroot);

    dlight->updateVolume();
        
    Vec3f min,max;
    dlight->getVolume().getBounds( min, max );
	
    std::cout << "Volume: from " << min << " to " << max << std::endl;

    //std::cerr << "Tree: " << std::endl;
    //root->dump();

	// Camera
	PerspectiveCameraPtr cam = PerspectiveCamera::create();

	cam->setBeacon( b1n );
	cam->setFov( deg2rad( 60 ) );
	cam->setNear( .1 );
	cam->setFar( 20. );

	// Background
	GradientBackgroundPtr bkgnd = GradientBackground::create();
	
	bkgnd->addLine( Color3f( 0,0,0 ), 0 );
	bkgnd->addLine( Color3f( .5,.5,0 ), 0.5 );
	bkgnd->addLine( Color3f( .7,.7,1 ), 0.5 );
	bkgnd->addLine( Color3f( 0,0,1 ), 1 );

	// Viewport

	ViewportPtr vp = Viewport::create();
	vp->setCamera( cam );
	vp->setBackground( bkgnd );
	vp->setRoot( root );
	vp->setSize( 0,0, 1,1 );

	// Window
	std::cout << "GLUT winid: " << winid << std::endl;

	GLUTWindowPtr gwin;

	GLint glvp[4];
	glGetIntegerv( GL_VIEWPORT, glvp );

	gwin = GLUTWindow::create();
	gwin->setId(winid);
	gwin->setSize( glvp[2], glvp[3] );

	win = gwin;

	win->addPort( vp );

	// Actions
	
	dact = DrawAction::create();
	ract = RenderAction::create();

	// tball

	Vec3f pos(0,
              0,
              max[2] + 1.5 * (max[2] - min[2]));

	tball.setMode( Trackball::OSGObject );
	tball.setStartPosition( pos, true );
	tball.setSum( true );
	tball.setTranslationMode( Trackball::OSGFree );
    tball.setTranslationScale(10.);
	// run...
	
	glutMainLoop();
	
    return 0;
}
示例#2
0
int main(int argc, char **argv)
{
    for(int i = 0; i < argc; i++)
    {
        std::cout << "Param " << i << ":" << argv[i] << std::endl;
    }

    OSG::osgInit(argc, argv);

    const char    *inFileName = "tie.bin";

    if(argc > 1)
        inFileName = argv[1];

    std::ifstream in(inFileName, std::ios::binary);
    if(!in)
    {
        std::cerr <<
            "ERROR: Cannot open file " <<
            inFileName <<
            "" <<
            std::endl;
        return -1;
    }

    OSG::BINLoader loader(in);
    loader.read();
    in.close();
    std::cout <<
        "MAIN: " <<
        getContainerId(loader.getRootNode()) <<
        " is root" <<
        std::endl;

    // GLUT init
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);

    int winid = glutCreateWindow("OpenSG");
    glutKeyboardFunc(key);
    glutVisibilityFunc(vis);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);

    glutIdleFunc(display);

    // glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_NORMALIZE);
    glDisable(GL_LIGHTING);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    glClearColor(0.5, 0.5, 0.5, 1.);

    // OSG
    //    OSGSceneFileHandler::the().print();
    //    FhsFile::touch();
    // create the graph
    // beacon for camera and light
    NodePtr     b1n = Node::create();
    GroupPtr    b1 = Group::create();
    beginEditCP(b1n);
    b1n->setCore(b1);
    endEditCP(b1n);

    // transformation
    NodePtr         t1n = Node::create();
    TransformPtr    t1 = Transform::create();
    beginEditCP(t1n);
    t1n->setCore(t1);
    t1n->addChild(b1n);
    endEditCP(t1n);

    cam_trans = t1;

    // light
    NodePtr dlight = Node::create();
    headlight = DirectionalLight::create();

    beginEditCP(dlight);
    dlight->setCore(headlight);
    endEditCP(dlight);

    beginEditCP(headlight);
    headlight->setAmbient(.3, .3, .3, 1);
    headlight->setDiffuse(1, 1, 1, 1);
    headlight->setSpecular(1, 1, 1, 1);
    headlight->setDirection(0, 0, 1);
    headlight->setBeacon(b1n);
    endEditCP(headlight);

    // root
    root = Node::create();

    GroupPtr    gr1 = Group::create();
    beginEditCP(root);
    root->setCore(gr1);
    root->addChild(t1n);
    root->addChild(dlight);
    endEditCP(root);

    // Load the file
    NodePtr     fileRoot = Node::create();

    //  OSGActivateColMatPtr colMat = OSGActivateColMat::create();
    GroupPtr    gr = Group::create();

    beginEditCP(fileRoot);

    //  fileRoot->setCore(colMat);
    fileRoot->setCore(gr);
    endEditCP(fileRoot);

    beginEditCP(dlight);
    dlight->addChild(fileRoot);
    endEditCP(dlight);

    //   for(UInt32 numFiles = 1; numFiles < argc; numFiles++)
    //    {
    //       file = SceneFileHandler::the().read(argv[1]);
    file = loader.getRootNode();
    beginEditCP(fileRoot);
    fileRoot->addChild(file);
    fileRoot->invalidateVolume();
    endEditCP(fileRoot);

    //    }
    dlight->updateVolume();

    Vec3f   min, max;
    dlight->getVolume().getBounds(min, max);

    std::cout << "Volume: from " << min << " to " << max << std::endl;

    //std::cerr << "Tree: " << std::endl;
    //root->dump();
    // Camera
    PerspectiveCameraPtr    cam = PerspectiveCamera::create();

    cam->setBeacon(b1n);
    cam->setFov(deg2rad(60));
    cam->setNear(1.);
    cam->setFar(100000.);

    // Background
    GradientBackgroundPtr   bkgnd = GradientBackground::create();

    bkgnd->addLine(Color3f(0, 0, 0), 0);
    bkgnd->addLine(Color3f(.5, .5, 0), 0.5);
    bkgnd->addLine(Color3f(.7, .7, 1), 0.5);
    bkgnd->addLine(Color3f(0, 0, 1), 1);

    // Viewport
    ViewportPtr vp = Viewport::create();
    vp->setCamera(cam);
    vp->setBackground(bkgnd);
    vp->setRoot(root);
    vp->setSize(0, 0, 1, 1);

    // Window
    std::cout << "GLUT winid: " << winid << std::endl;

    GLUTWindowPtr   gwin;

    GLint           glvp[4];
    glGetIntegerv(GL_VIEWPORT, glvp);

    gwin = GLUTWindow::create();
    gwin->setId(winid);
    gwin->setSize(glvp[2], glvp[3]);

    win = gwin;

    win->addPort(vp);

    // Actions
    dact = DrawAction::create();
    ract = RenderAction::create();

    // tball
    /*
	Vec3f pos(min[0] + 0.5 * (max[0] - min[0]),
              min[1] + 0.5 * (max[1] - min[1]),
              max[2] + 1.5 * (max[2] - min[2]));
*/
    Vec3f   pos(0, 0, max[2] + 1.5 * (max[2] - min[2]));

    tball.setMode(Trackball::OSGObject);
    tball.setStartPosition(pos, true);
    tball.setSum(true);
    tball.setTranslationMode(Trackball::OSGFree);
    tball.setTranslationScale(10000.);

    // run...
    glutMainLoop();

    return 0;
}
示例#3
0
int main(int argc, char *argv[])
{
    osgLogP->setLogLevel(LOG_NOTICE);

    osgInit(argc, argv);

    int winid = setupGLUT(&argc, argv);

    // create a GLUT window
    GLUTWindowPtr gwin = GLUTWindow::create();
    gwin->setId(winid);
    gwin->init();

    osgLogP->setLogLevel(LOG_DEBUG);

    // build the test scene
    NodePtr  pRoot      = Node ::create();
    GroupPtr pRootCore  = Group::create();
    NodePtr  pRayGeo    = Node ::create();
    NodePtr  pScene     = buildGraph();
    GroupPtr pSceneCore = Group::create();

    Time     tStart;
    Time     tStop;
    Time     tDFTotal  = 0.0;
    Time     tDFSTotal = 0.0;
    Time     tPTotal   = 0.0;
    Time     tOTotal   = 0.0;

    StatCollector statP;
    StatCollector statDF;
    StatCollector statDFS;

    beginEditCP(pRoot, Node::CoreFieldId | Node::ChildrenFieldId);
    pRoot->setCore (pRootCore   );
    pRoot->addChild(pScene      );
    pRoot->addChild(pRayGeo     );
    endEditCP  (pRoot, Node::CoreFieldId | Node::ChildrenFieldId);

    createRays(uiNumRays, testRays);

    // build the geometry to visualize the rays
    pPoints = GeoPositions3f::create();
    beginEditCP(pPoints);
    pPoints->addValue(Pnt3f(0.0, 0.0, 0.0));
    pPoints->addValue(Pnt3f(0.0, 0.0, 0.0));
    pPoints->addValue(Pnt3f(0.0, 0.0, 0.0));
    pPoints->addValue(Pnt3f(0.0, 0.0, 0.0));
    pPoints->addValue(Pnt3f(0.0, 0.0, 0.0));
    endEditCP  (pPoints);

    GeoIndicesUI32Ptr pIndices = GeoIndicesUI32::create();
    beginEditCP(pIndices);
    pIndices->addValue(0);
    pIndices->addValue(1);
    pIndices->addValue(2);
    pIndices->addValue(3);
    pIndices->addValue(4);
    endEditCP  (pIndices);

    GeoPLengthsPtr pLengths = GeoPLengthsUI32::create();
    beginEditCP(pLengths);
    pLengths->addValue(2);
    pLengths->addValue(3);
    endEditCP  (pLengths);

    GeoPTypesPtr pTypes = GeoPTypesUI8::create();
    beginEditCP(pTypes);
    pTypes->addValue(GL_LINES    );
    pTypes->addValue(GL_TRIANGLES);
    endEditCP  (pTypes);

    GeoColors3fPtr pColors = GeoColors3f::create();
    beginEditCP(pColors);
    pColors->addValue(Color3f(1.0, 1.0, 1.0));
    pColors->addValue(Color3f(1.0, 0.0, 0.0));
    pColors->addValue(Color3f(1.0, 0.0, 0.0));
    pColors->addValue(Color3f(1.0, 0.0, 0.0));
    pColors->addValue(Color3f(1.0, 0.0, 0.0));
    endEditCP  (pColors);

    SimpleMaterialPtr pMaterial = SimpleMaterial::create();
    beginEditCP(pMaterial);
    pMaterial->setLit(false);
    endEditCP  (pMaterial);

    GeometryPtr pRayGeoCore = Geometry::create();
    beginEditCP(pRayGeoCore);
    pRayGeoCore->setPositions(pPoints  );
    pRayGeoCore->setIndices  (pIndices );
    pRayGeoCore->setLengths  (pLengths );
    pRayGeoCore->setTypes    (pTypes   );
    pRayGeoCore->setColors   (pColors  );
    pRayGeoCore->setMaterial (pMaterial);
    endEditCP  (pRayGeoCore);

    beginEditCP(pRayGeo, Node::CoreFieldId);
    pRayGeo->setCore(pRayGeoCore);
    endEditCP  (pRayGeo, Node::CoreFieldId);

    IntersectActor::regDefaultClassEnter(
        osgTypedFunctionFunctor2CPtr<
            NewActionTypes::ResultE,          NodeCorePtr,
            ActorBase::FunctorArgumentType &              >(enterDefault));


    NewActionBase  *pDFAction  = DepthFirstAction     ::create();
    NewActionBase  *pDFSAction = DepthFirstStateAction::create();
    NewActionBase  *pPAction   = PriorityAction       ::create();
    IntersectActor *pIActorDF  = IntersectActor       ::create();
    IntersectActor *pIActorDFS = IntersectActor       ::create();
    IntersectActor *pIActorP   = IntersectActor       ::create();

    pDFAction ->setStatistics(&statDF );
    pDFSAction->setStatistics(&statDFS);
    pPAction  ->setStatistics(&statP  );

    // IntersectActor with DFS-Action does not need leave calls
    pIActorDFS->setLeaveNodeFlag(false);

    pDFAction ->addActor(pIActorDF );
    pDFSAction->addActor(pIActorDFS);
    pPAction  ->addActor(pIActorP  );

    // create old action
    IntersectAction *pIntAction = IntersectAction ::create();

    // make sure bv are up to date
    pScene->updateVolume();


    SINFO << "-=< Intersect >=-" << endLog;

    std::vector<Line>::iterator itRays  = testRays.begin();
    std::vector<Line>::iterator endRays = testRays.end  ();

    for(; itRays != endRays; ++itRays)
    {
        // DepthFirst

        tStart = getSystemTime();

        pIActorDF->setRay        (*itRays);
        pIActorDF->setMaxDistance(10000.0);
        pIActorDF->reset         (       );

        pDFAction->apply(pScene);

        tStop            =  getSystemTime();
        tDFTotal += (tStop - tStart);

        if(pIActorDF->getHit() == true)
        {
            IntersectResult result;

            result._hit  = true;
            result._pObj = pIActorDF->getHitObject       ();
            result._tri  = pIActorDF->getHitTriangleIndex();
            result._dist = pIActorDF->getHitDistance     ();
            result._time = (tStop - tStart);

            resultsDF.push_back(result);
        }
        else
        {
            IntersectResult result;

            result._hit  = false;
            result._pObj = NullFC;
            result._tri  = -1;
            result._dist = 0.0;
            result._time = (tStop - tStart);

            resultsDF.push_back(result);
        }

        std::string strStatDF;
        statDF.putToString(strStatDF);

        //SINFO << "stat DF:  " << strStatDF << endLog;

        // Depth First State

        tStart = getSystemTime();

        pIActorDFS->setRay        (*itRays);
        pIActorDFS->setMaxDistance(10000.0);
        pIActorDFS->reset         (       );

        pDFSAction->apply(pScene);

        tStop     =  getSystemTime();
        tDFSTotal += (tStop - tStart);

        if(pIActorDFS->getHit() == true)
        {
            IntersectResult result;

            result._hit  = true;
            result._pObj = pIActorDFS->getHitObject       ();
            result._tri  = pIActorDFS->getHitTriangleIndex();
            result._dist = pIActorDFS->getHitDistance     ();
            result._time = (tStop - tStart);

            resultsDFS.push_back(result);
        }
        else
        {
            IntersectResult result;

            result._hit  = false;
            result._pObj = NullFC;
            result._tri  = -1;
            result._dist = 0.0;
            result._time = (tStop - tStart);

            resultsDFS.push_back(result);
        }

        std::string strStatDFS;
        statDFS.putToString(strStatDFS);

        //SINFO << "stat DFS: " << strStatDFS << endLog;

        // Priority

        tStart = getSystemTime();

        pIActorP->setRay        (*itRays);
        pIActorP->setMaxDistance(10000.0);
        pIActorP->reset         (       );

        pPAction->apply(pScene);

        tStop          =  getSystemTime();
        tPTotal += (tStop - tStart);

        if(pIActorP->getHit() == true)
        {
            IntersectResult result;

            result._hit  = true;
            result._pObj = pIActorP->getHitObject       ();
            result._tri  = pIActorP->getHitTriangleIndex();
            result._dist = pIActorP->getHitDistance     ();
            result._time = (tStop - tStart);

            resultsP.push_back(result);
        }
        else
        {
            IntersectResult result;

            result._hit  = false;
            result._pObj = NullFC;
            result._tri  = -1;
            result._dist = 0.0;
            result._time = (tStop - tStart);

            resultsP.push_back(result);
        }

        std::string strStatP;
        statP.putToString(strStatP);

        //SINFO << "stat P:   " << strStatP << endLog;

        // Old

        tStart = getSystemTime();

        pIntAction->setLine(*itRays, 100000);
        pIntAction->apply  (pScene         );

        tStop     =  getSystemTime();
        tOTotal += (tStop - tStart);

        if(pIntAction->didHit() == true)
        {
            IntersectResult result;

            result._hit  = true;
            result._pObj = pIntAction->getHitObject  ();
            result._tri  = pIntAction->getHitTriangle();
            result._dist = pIntAction->getHitT       ();
            result._time = (tStop - tStart);

            resultsO.push_back(result);
        }
        else
        {
            IntersectResult result;

            result._hit  = false;
            result._pObj = NullFC;
            result._tri  = -1;
            result._dist = 0.0;
            result._time = (tStop - tStart);

            resultsO.push_back(result);
        }
    }

    UInt32 DFwins      = 0;
    UInt32 DFwinsHit   = 0;
    UInt32 DFwinsMiss  = 0;

    UInt32 DFSwins     = 0;
    UInt32 DFSwinsHit  = 0;
    UInt32 DFSwinsMiss = 0;

    UInt32 Pwins       = 0;
    UInt32 PwinsHit    = 0;
    UInt32 PwinsMiss   = 0;

    UInt32 Owins       = 0;
    UInt32 OwinsHit    = 0;
    UInt32 OwinsMiss   = 0;

    UInt32 failCount   = 0;
    UInt32 passCount   = 0;
    UInt32 hitCount    = 0;
    UInt32 missCount   = 0;

    for(UInt32 i = 0; i < uiNumRays; ++i)
    {
        bool DFfastest  = ((resultsDF [i]._time <= resultsDFS[i]._time) &&
                           (resultsDF [i]._time <= resultsP  [i]._time) &&
                           (resultsDF [i]._time <= resultsO  [i]._time)   );
        bool DFSfastest = ((resultsDFS[i]._time <= resultsDF [i]._time) &&
                           (resultsDFS[i]._time <= resultsP  [i]._time) &&
                           (resultsDFS[i]._time <= resultsO  [i]._time)   );
        bool Pfastest   = ((resultsP  [i]._time <= resultsDF [i]._time) &&
                           (resultsP  [i]._time <= resultsDFS[i]._time) &&
                           (resultsP  [i]._time <= resultsO  [i]._time)   );
        bool Ofastest   = ((resultsO  [i]._time <= resultsDF [i]._time) &&
                           (resultsO  [i]._time <= resultsDFS[i]._time) &&
                           (resultsO  [i]._time <= resultsP  [i]._time)   );

        if((resultsDF [i]._hit == resultsDFS[i]._hit) &&
           (resultsDFS[i]._hit == resultsP  [i]._hit) &&
           (resultsP  [i]._hit == resultsO  [i]._hit)    )
        {
            if((osgabs(resultsDF [i]._dist - resultsDFS[i]._dist) >= 0.001) ||
               (osgabs(resultsDFS[i]._dist - resultsP  [i]._dist) >= 0.001) ||
               (osgabs(resultsP  [i]._dist - resultsO  [i]._dist) >= 0.001) ||
               (osgabs(resultsO  [i]._dist - resultsDF [i]._dist) >= 0.001)   )
            {
                ++failCount;

                SINFO << "FAIL: df: " << resultsDF [i]._dist
                      << " dfs: "     << resultsDFS[i]._dist
                      << " p: "       << resultsP  [i]._dist
                      << " o: "       << resultsO  [i]._dist
                      << endLog;
                SINFO << "FAIL: df: " << resultsDF [i]._tri
                      << " dfs: "     << resultsDFS[i]._tri
                      << " p: "       << resultsP  [i]._tri
                      << " o: "       << resultsO  [i]._tri
                      << endLog;
            }
            else
            {
                ++passCount;
            }

            if(resultsDF[i]._hit == true)
            {
                ++hitCount;

                DFwinsHit  = DFfastest  ? DFwinsHit  + 1 : DFwinsHit;
                DFSwinsHit = DFSfastest ? DFSwinsHit + 1 : DFSwinsHit;
                PwinsHit   = Pfastest   ? PwinsHit   + 1 : PwinsHit;
                OwinsHit   = Ofastest   ? OwinsHit   + 1 : OwinsHit;
            }
            else
            {
                ++missCount;

                DFwinsMiss  = DFfastest  ? DFwinsMiss  + 1 : DFwinsMiss;
                DFSwinsMiss = DFSfastest ? DFSwinsMiss + 1 : DFSwinsMiss;
                PwinsMiss   = Pfastest   ? PwinsMiss   + 1 : PwinsMiss;
                OwinsMiss   = Ofastest   ? OwinsMiss   + 1 : OwinsMiss;
            }

            DFwins  = DFfastest  ? DFwins  + 1 : DFwins;
            DFSwins = DFSfastest ? DFSwins + 1 : DFSwins;
            Pwins   = Pfastest   ? Pwins   + 1 : Pwins;
            Owins   = Ofastest   ? Owins   + 1 : Owins;
        }
        else
        {
            ++failCount;
        }

        //SINFO << i << " \t" << (DFfastest  ? "D ->" : "    ") << " hit: " << resultsDF [i]._hit << " time: " << resultsDF [i]._time << endLog;
        //SINFO << "  \t"     << (DFSfastest ? "S ->" : "    ") << " hit: " << resultsDFS[i]._hit << " time: " << resultsDFS[i]._time << endLog;
        //SINFO << "  \t"     << (Pfastest   ? "P ->" : "    ") << " hit: " << resultsP  [i]._hit << " time: " << resultsP  [i]._time << endLog;
        //SINFO << "  \t"     << (Ofastest   ? "O ->" : "    ") << " hit: " << resultsO  [i]._hit << " time: " << resultsO  [i]._time << endLog;
    }

    SINFO << " df total:  "    << tDFTotal   << (tDFTotal < tDFSTotal && tDFTotal < tPTotal && tDFTotal < tOTotal ? " *" : "  ") 
          << " wins: "         << DFwins     << " (" << (static_cast<Real32>(DFwins)     / static_cast<Real32>(passCount)) * 100.0 << "%)\t"
          << " wins on hit: "  << DFwinsHit  << " (" << (static_cast<Real32>(DFwinsHit)  / static_cast<Real32>(hitCount )) * 100.0 << "%)\t"
          << " wins on miss: " << DFwinsMiss << " (" << (static_cast<Real32>(DFwinsMiss) / static_cast<Real32>(missCount)) * 100.0 << "%)"
          << endLog;

    SINFO << " dfs total: "    << tDFSTotal  << (tDFSTotal < tDFTotal && tDFSTotal < tPTotal && tDFSTotal < tOTotal ? " *" : "  ") 
          << " wins: "         << DFSwins     << " (" << (static_cast<Real32>(DFSwins)     / static_cast<Real32>(passCount)) * 100.0 << "%)\t"
          << " wins on hit: "  << DFSwinsHit  << " (" << (static_cast<Real32>(DFSwinsHit)  / static_cast<Real32>(hitCount )) * 100.0 << "%)\t"
          << " wins on miss: " << DFSwinsMiss << " (" << (static_cast<Real32>(DFSwinsMiss) / static_cast<Real32>(missCount)) * 100.0 << "%)"
          << endLog;

    SINFO << " p total:   "    << tPTotal   << (tPTotal < tDFTotal && tPTotal < tDFSTotal && tPTotal < tOTotal ? " *" : "  ") 
          << " wins: "         << Pwins     << " (" << (static_cast<Real32>(Pwins)     / static_cast<Real32>(passCount)) * 100.0 << "%)\t"
          << " wins on hit: "  << PwinsHit  << " (" << (static_cast<Real32>(PwinsHit)  / static_cast<Real32>(hitCount )) * 100.0 << "%)\t"
          << " wins on miss: " << PwinsMiss << " (" << (static_cast<Real32>(PwinsMiss) / static_cast<Real32>(missCount)) * 100.0 << "%)"
          << endLog;

    SINFO << " o total:   "    << tOTotal   << (tOTotal < tDFTotal && tOTotal < tDFSTotal && tOTotal < tPTotal ? " *" : "  ") 
          << " wins: "         << Owins     << " (" << (static_cast<Real32>(Owins)     / static_cast<Real32>(passCount)) * 100.0 << "%)\t"
          << " wins on hit: "  << OwinsHit  << " (" << (static_cast<Real32>(OwinsHit)  / static_cast<Real32>(hitCount )) * 100.0 << "%)\t"
          << " wins on miss: " << OwinsMiss << " (" << (static_cast<Real32>(OwinsMiss) / static_cast<Real32>(missCount)) * 100.0 << "%)"
          << endLog;

    SINFO << "pass: "******" fail: " << failCount
          << " hit: " << hitCount  << " miss: " << missCount << endLog;

    osgLogP->setLogLevel(LOG_NOTICE);

#if 0
    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // tell the manager what to manage
    mgr->setWindow(gwin );
    mgr->setRoot  (pRoot);

    // show the whole scene
    mgr->showAll();

    // GLUT main loop
    glutMainLoop();
#endif


    return 0;
}
示例#4
0
//------------------------------------------------------------------------------
// The main method
//------------------------------------------------------------------------------
int main(int argc, char **argv) {
	osgInit(argc, argv);                 // initialize OpenSG
	int winid = setupGLUT(&argc, argv);  // initialize GLUT

	// the connection between GLUT and OpenSG is established
	GLUTWindowPtr gwin = GLUTWindow::create();
	gwin->setId(winid);
	gwin->init();

//----------------------------------------------------------------------------//
// Snippet-1-1 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// very first step: load the configuration of the file structures, basically
	// paths are set. The Configuration always has to be loaded first since each
	// module uses the paths set in the configuration-file
	if (!Configuration::loadConfig("config/general.xml")) {
		printf("Error: could not load config-file!\n");
		return -1;
	}
//----------------------------------------------------------------------------//
// Snippet-1-1 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-4 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// register callbacks
	InputInterface::registerModuleInitCallback(initInputInterface);
	SystemCore::registerModuleInitCallback(initModules);
//----------------------------------------------------------------------------//
// Snippet-2-4 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-3-3 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	SystemCore::registerCoreComponentInitCallback(initCoreComponents);
//----------------------------------------------------------------------------//
// Snippet-3-3 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-1-2 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	std::string systemCoreConfigFile = Configuration::getString(
			"SystemCore.systemCoreConfiguration");
	std::string outputInterfaceConfigFile = Configuration::getString(
			"Interfaces.outputInterfaceConfiguration");

//	// !!!!!! Remove in tutorial part 2, Snippet-2-1 - BEGIN
//	if (!SystemCore::configure(systemCoreConfigFile, outputInterfaceConfigFile)) {
//		printf("Error: failed to setup SystemCore!\n");
//		return -1;
//	}
//	// !!!!!! Remove - END
//----------------------------------------------------------------------------//
// Snippet-1-2 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-1 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// !!!!!! Remove part of Snippet-1-2 (right above)
	// in addition to the SystemCore config file, modules and interfaces config
	// files have to be loaded.
	std::string modulesConfigFile = Configuration::getString(
				"Modules.modulesConfiguration");
	std::string inputInterfaceConfigFile = Configuration::getString(
			"Interfaces.inputInterfaceConfiguration");

	if (!SystemCore::configure(systemCoreConfigFile, outputInterfaceConfigFile, inputInterfaceConfigFile,
			modulesConfigFile)) {
		printf("Error: failed to setup SystemCore!\n");
		printf("Please check if the Plugins-path is correctly set to the inVRs-lib directory in the ");
		printf("'final/config/general.xml' config file, e.g.:\n");
		printf("<path name=\"Plugins\" path=\"/home/guest/inVRs/lib\"/>\n");
		return -1;
	}
//----------------------------------------------------------------------------//
// Snippet-2-1 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-3-1 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// generate or load and configure height maps of the used tiles
	HeightMapManager::generateTileHeightMaps();
//----------------------------------------------------------------------------//
// Snippet-3-1 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-15 - BEGIN                                                       //
//----------------------------------------------------------------------------//
	// generate and configure the SkyBox
	std::string skyPath = Configuration::getPath("Skybox");
	skybox.init(5,5,5, 1000, (skyPath+"lostatseaday/lostatseaday_dn.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_up.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_ft.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_bk.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_rt.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_lf.jpg").c_str());
//----------------------------------------------------------------------------//
// Snippet-2-15 - END                                                         //
//----------------------------------------------------------------------------//

	NodePtr root = Node::create();
	beginEditCP(root);
		root->setCore(Group::create());

//----------------------------------------------------------------------------//
// Snippet-1-3 - BEGIN                                                        //
//----------------------------------------------------------------------------//
		OpenSGSceneGraphInterface* sgIF =
			dynamic_cast<OpenSGSceneGraphInterface*>(OutputInterface::getSceneGraphInterface());
		if (!sgIF) {
			printf("Error: Failed to get OpenSGSceneGraphInterface!\n");
			printf("Please check if the OutputInterface configuration is correct!\n");
			return -1;
		}
		// retrieve root node of the SceneGraphInterface (method is OpenSG specific)
		NodePtr scene = sgIF->getNodePtr();

		root->addChild(scene);
//----------------------------------------------------------------------------//
// Snippet-1-3 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-16 - BEGIN                                                       //
//----------------------------------------------------------------------------//
		// add the SkyBox to the scene
		root->addChild(skybox.getNodePtr());
//----------------------------------------------------------------------------//
// Snippet-2-16 - END                                                         //
//----------------------------------------------------------------------------//

	endEditCP(root);

//----------------------------------------------------------------------------//
// Snippet-2-5 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// fetch users camera, it is used to tell the Navigator where we are
	localUser = UserDatabase::getLocalUser();
	if (!localUser) {
		printd(ERROR, "Error: Could not find localUser!\n");
		return -1;
	}

	camera = localUser->getCamera();
	if (!camera) {
		printd(ERROR, "Error: Could not find camera!\n");
		return -1;
	}

	avatar = localUser->getAvatar();
	if (!avatar) {
		printd(ERROR, "Error: Could not find avatar!\n");
		return -1;
	}
	avatar->showAvatar(false);

  // set our transformation to the start transformation
	TransformationData startTrans =
		WorldDatabase::getEnvironmentWithId(1)->getStartTransformation(0);
	localUser->setNavigatedTransformation(startTrans);
//----------------------------------------------------------------------------//
// Snippet-2-5 - END                                                          //
//----------------------------------------------------------------------------//

	mgr = new SimpleSceneManager;  // create the SimpleSceneManager
	mgr->setWindow(gwin);          // tell the manager what to manage
	mgr->setRoot(root);            // attach the scenegraph to the  root node
	mgr->showAll();                // show the whole scene
	mgr->getCamera()->setNear(0.1);

//----------------------------------------------------------------------------//
// Snippet-2-6 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// Navigator is part of SimpleSceneManager and not of the inVRs framework
	Navigator *nav = mgr->getNavigator();
	nav->setMode(Navigator::NONE);     // turn off the navigator
	lastTimeStamp = timer.getTime();   // initialize timestamp;
	camMatrix = gmtl::MAT_IDENTITY44F; // initial setting of the camera matrix
//----------------------------------------------------------------------------//
// Snippet-2-6 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-5-2                                                                //
//----------------------------------------------------------------------------//

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

    // GLUT init
    int winid = setupGLUT(&argc, argv);
    gwin = GLUTWindow::create();

    // create root
    rootNode = makeCoredNode<Group>();
    NodePtr scene = makeCoredNode<Group>();

    // create lights
    TransformPtr point1_trans;
    NodePtr point1 = makeCoredNode<PointLight>(&_point1_core);
    NodePtr point1_beacon = makeCoredNode<Transform>(&point1_trans);
    beginEditCP(point1_trans);
        point1_trans->editMatrix().setTranslate(0.0, 0.0, 25.0);
    endEditCP(point1_trans);

    beginEditCP(_point1_core);
        _point1_core->setAmbient(0.15,0.15,0.15,1);
        _point1_core->setDiffuse(0.4,0.4,0.4,1);
        _point1_core->setSpecular(0.0,0.0,0.0,1);
        _point1_core->setBeacon(point1_beacon);
        _point1_core->setOn(true);
    endEditCP(_point1_core);

    TransformPtr point2_trans;
    NodePtr point2 = makeCoredNode<PointLight>(&_point2_core);
    NodePtr point2_beacon = makeCoredNode<Transform>(&point2_trans);
    beginEditCP(point2_trans);
        point2_trans->editMatrix().setTranslate(5.0, 5.0, 20.0);
    endEditCP(point2_trans);

    beginEditCP(_point2_core);
        _point2_core->setAmbient(0.15,0.15,0.15,1);
        _point2_core->setDiffuse(0.4,0.4,0.4,1);
        _point2_core->setSpecular(0.0,0.0,0.0,1);
        _point2_core->setBeacon(point2_beacon);
        _point2_core->setOn(true);
    endEditCP(_point2_core);

    beginEditCP(point1);
        point1->addChild(point2);
    endEditCP(point1);

    beginEditCP(point2);
        point2->addChild(scene);
    endEditCP(point2);

    // create scene
    
    // bottom
    NodePtr plane = makePlane(25.0, 25.0, 128, 128);
    
    int size = imageWinWidth*imageWinHeight*256;

    ImagePtr plane_img = Image::create();

    beginEditCP(plane_img);
    plane_img->set(Image::OSG_RGBA_PF, imageWinWidth, imageWinHeight, 1, 1, 1, 0, NULL);
    endEditCP(plane_img);

    TextureChunkPtr plane_tex = TextureChunk::create();
    beginEditCP(plane_tex);
        plane_tex->setImage(plane_img);
        plane_tex->setMinFilter(GL_LINEAR);
        plane_tex->setMagFilter(GL_LINEAR);
        plane_tex->setTarget(GL_TEXTURE_2D);
        plane_tex->setInternalFormat(GL_RGBA16F_ARB);
    endEditCP(plane_tex);

    SHLChunkPtr shl = SHLChunk::create();
    beginEditCP(shl);
        shl->setVertexProgram(_vp_program);
        shl->setFragmentProgram(_fp_program);
        shl->setUniformParameter("tex0", 0);
    endEditCP(shl);

    SimpleMaterialPtr plane_mat = SimpleMaterial::create();
    beginEditCP(plane_mat);
        plane_mat->setAmbient(Color3f(0.3,0.3,0.3));
        plane_mat->setDiffuse(Color3f(1.0,1.0,1.0));
        plane_mat->addChunk(plane_tex);
        plane_mat->addChunk(shl);
    endEditCP(plane_mat);

    GeometryPtr plane_geo = GeometryPtr::dcast(plane->getCore());
    beginEditCP(plane_geo);
        plane_geo->setMaterial(plane_mat);
    beginEditCP(plane_geo);
    
    // box
    box_trans_node = makeCoredNode<Transform>(&_box_trans);
    beginEditCP(_box_trans);
        _box_trans->editMatrix().setTranslate(0.0, 0.0, 12.0);
    endEditCP(_box_trans);
    NodePtr box = makeBox(4.0, 4.0, 0.8, 10, 10 , 10);
    beginEditCP(box_trans_node);
        box_trans_node->addChild(box);
    endEditCP(box_trans_node);
    
    PolygonChunkPtr pchunk = osg::PolygonChunk::create();
    beginEditCP(pchunk);
        pchunk->setCullFace(GL_BACK);
    endEditCP(pchunk);

    SimpleMaterialPtr box_mat = SimpleMaterial::create();
    beginEditCP(box_mat);
        box_mat->setAmbient(Color3f(0.0,0.0,0.0));
        box_mat->setDiffuse(Color3f(0.0,0.0,1.0));
        box_mat->addChunk(pchunk);
    endEditCP(box_mat);

    GeometryPtr box_geo = GeometryPtr::dcast(box->getCore());
    beginEditCP(box_geo);
        box_geo->setMaterial(box_mat);
    beginEditCP(box_geo);

    // cylinder1
    NodePtr cylinder1_trans_node = makeCoredNode<Transform>(&_cylinder1_trans);
    beginEditCP(_cylinder1_trans);
        _cylinder1_trans->editMatrix().setTranslate(0.0, 0.0, 5.0);
    endEditCP(_cylinder1_trans);
    NodePtr cylinder1 = OSG::makeCylinder(10.0, 0.4, 32, true, true ,true);
    beginEditCP(cylinder1_trans_node);
        cylinder1_trans_node->addChild(cylinder1);
    endEditCP(cylinder1_trans_node);

    SimpleMaterialPtr cylinder1_mat = SimpleMaterial::create();
    beginEditCP(cylinder1_mat);
        cylinder1_mat->setAmbient(Color3f(0.0,0.0,0.0));
        cylinder1_mat->setDiffuse(Color3f(1.0,0.0,0.0));
        cylinder1_mat->addChunk(pchunk);
    endEditCP(cylinder1_mat);

    GeometryPtr cylinder1_geo = GeometryPtr::dcast(cylinder1->getCore());
    beginEditCP(cylinder1_geo);
        cylinder1_geo->setMaterial(cylinder1_mat);
    beginEditCP(cylinder1_geo);
    
    // cylinder2
    NodePtr cylinder2_trans_node = makeCoredNode<Transform>(&_cylinder2_trans);
    beginEditCP(_cylinder2_trans);
        _cylinder2_trans->editMatrix().setTranslate(0.0, 0.0, 8.0);
    endEditCP(_cylinder2_trans);
    NodePtr cylinder2 = OSG::makeCylinder(10.0, 0.4, 32, true, true ,true);
    beginEditCP(cylinder2_trans_node);
        cylinder2_trans_node->addChild(cylinder2);
    endEditCP(cylinder2_trans_node);

    SimpleMaterialPtr cylinder2_mat = SimpleMaterial::create();
    beginEditCP(cylinder2_mat);
        cylinder2_mat->setAmbient(Color3f(0.0,0.0,0.0));
        cylinder2_mat->setDiffuse(Color3f(0.0,1.0,0.0));
        cylinder2_mat->addChunk(pchunk);
    endEditCP(cylinder2_mat);

    GeometryPtr cylinder2_geo = GeometryPtr::dcast(cylinder2->getCore());
    beginEditCP(cylinder2_geo);
        cylinder2_geo->setMaterial(cylinder2_mat);
    beginEditCP(cylinder2_geo);

    // scene
    beginEditCP(scene);
        scene->addChild(plane);
        scene->addChild(box_trans_node);
        scene->addChild(cylinder1_trans_node);
        scene->addChild(cylinder2_trans_node);
    endEditCP(scene);

    vp = ShadowViewport::create();
    
    GradientBackgroundPtr gbg = GradientBackground::create();
    SolidBackgroundPtr sbg = SolidBackground::create();

    UChar8 imgdata[] = {  255,0,0,  0,255,0,  0,0,255, 255,255,0 };
    ImagePtr img1 = Image::create();
    img1->set(Image::OSG_RGB_PF, 2, 2, 1, 1, 1, 0, imgdata);

    TextureChunkPtr tcPtr = TextureChunk::create();
    beginEditCP(tcPtr);
        tcPtr->setImage(img1);
    endEditCP(tcPtr);
    TextureBackgroundPtr bkg = TextureBackground::create();
    beginEditCP(bkg);
        bkg->setTexture(tcPtr);
    endEditCP(bkg);
    
    beginEditCP(sbg);
        sbg->setColor(Color3f(0.2,0.4,0.6));
    endEditCP(sbg);
    
    beginEditCP(gbg);
        gbg->addLine(Color3f(0.7, 0.7, 0.8), 0);
        gbg->addLine(Color3f(0.1, 0.1, 0.3), 1);
    endEditCP(gbg);

    beginEditCP(rootNode);
        rootNode->addChild(point1);
        rootNode->addChild(point1_beacon);
        rootNode->addChild(point2_beacon);
    endEditCP(rootNode);

    //FBOViewportPtr
    fbo_vp = FBOViewport::create();
    addRefCP(fbo_vp);

    // the Camera for the map
    cam = PerspectiveCamera::create();
    beginEditCP(cam);
        cam->setFov(osgdegree2rad(90));
        cam->setAspect(1);
        cam->setNear(0.001);
        cam->setFar(10000);
        cam->setBeacon(box_trans_node);
    endEditCP(cam);

    beginEditCP(fbo_vp);
        fbo_vp->setBackground(bkg);
        fbo_vp->setRoot(rootNode);
        fbo_vp->setCamera(cam);
        fbo_vp->setSize(0,0,imageWinWidth-1, imageWinHeight-1);
        fbo_vp->setStorageWidth(imageWinWidth);
        fbo_vp->setStorageHeight(imageWinHeight);
        fbo_vp->setDirty(true);
        fbo_vp->editMFTextures    ()->push_back(plane_tex);
        fbo_vp->editMFExcludeNodes()->push_back(plane);
        fbo_vp->setFboOn(true);
    endEditCP(fbo_vp);

    // normal shadow viewport
    beginEditCP(vp);
        vp->setBackground(gbg);
        vp->setRoot(rootNode);
        vp->setSize(0,0,1,1);
    endEditCP(vp);

    beginEditCP(gwin); //Window
        gwin->setId(winid);
        gwin->addPort(vp);
        gwin->init();
    endEditCP(gwin);

    Vec3f min,max;
    rootNode->updateVolume();
    rootNode->getVolume().getBounds( min, max );

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    mgr->setWindow(gwin);
    mgr->setRoot(rootNode);

    //Viewport
    beginEditCP(vp);
        vp->setCamera(mgr->getCamera());
    endEditCP(vp);

    mgr->turnHeadlightOff();

    mgr->showAll();

    // GLUT main loop
    glutMainLoop();

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

    std::string fontfile("testfont.ttf");
    std::string testtext("Test Text");
    UInt32 drawmode;
    
    if(argc > 1)
        testtext = argv[1];
    if(argc > 2)
        fontfile = argv[2];
    if(argc < 4 || sscanf(argv[3], "%d", &drawmode) != 1 )
        drawmode = FTGLFont::Outline;
        
    // GLUT 
    int winid = setupGLUT(&argc, argv);
    GLUTWindowPtr gwin= GLUTWindow::create();
    gwin->setId(winid);
    gwin->init();
   
    
    // Create the Cubes node

    NodePtr scene = makeCoredNode<Group>();

    beginEditCP(scene);
    
    scene->addChild( makeBox(200,200,200, 1,1,1) );
//    scene->addChild( SceneFileHandler::the().read("tie.wrl") );
    endEditCP(scene);


    // Create the text
    
    FTGLFontPtr font = FTGLFont::create();
    
    beginEditCP(font);
    font->setName(fontfile);
    font->setDrawType(drawmode);
    font->setSize(40);
    font->setRes(72);
    font->setDepth(20);
    endEditCP(font);

    FTGLTextPtr text;
    NodePtr tnode = makeCoredNode<FTGLText>(&text);
    
    beginEditCP(text);
    text->setFont(font);
    text->setText(testtext);
    text->setPosition(Pnt3f(0,300,0));
    text->setMaterial(getDefaultMaterial());      
    endEditCP(text);
    

    beginEditCP(scene);
    scene->addChild(tnode);
    endEditCP(scene);
    
    
    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // tell the manager what to manage
    mgr->setWindow(gwin );
    mgr->setRoot  (scene);

    // show the whole scene
    mgr->showAll();
        
    // copy to second window 
    int winid2 = setupGLUT(&argc, argv);
    gwin2= GLUTWindow::create();
    gwin2->setId(winid2);
    gwin2->init();
    
    ViewportPtr ovp = gwin->getPort()[0];
    
    ViewportPtr vp = Viewport::create();
    
    beginEditCP(vp);
    vp->setLeft(0);
    vp->setRight(400);
    vp->setBottom(0);
    vp->setTop(400);
    vp->setCamera(ovp->getCamera());
    vp->setRoot(ovp->getRoot());
    vp->setBackground(ovp->getBackground());
    vp->setParent(gwin2);
    endEditCP(vp);
    
    beginEditCP(gwin2);
    gwin2->getPort().push_back(vp);
    endEditCP(gwin2);
    
    // GLUT main loop
    glutMainLoop();

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

    // GLUT init
    int winid = setupGLUT(&argc, argv);

    // the connection between GLUT and OpenSG
    GLUTWindowPtr gwin = GLUTWindow::create();
    gwin->setId(winid);
    gwin->init();

    // load the scene

    NodePtr scene;
    
    if(argc < 2)
    {
        FWARNING(("No file given!\n"));
 
        scene = makeTorus(.5, 2, 16, 16);
    }
    else
    {
        /*
            All scene file loading is handled via the SceneFileHandler.
        */
        scene = SceneFileHandler::the().read(argv[1]);
    }

    /* 
       An Attachment is a special field container that can be attached to many
       of the internal classes like Nodes and NodeCores. There can be multiple
       Attachments attached to an object.
       
       Attachments can be attached to all FieldContainers that are derived from
       AttachmentContainer. This includes most higher-level classes in the
       system, like Nodes, NodeCores, Windows, Viewports etc.

       The only predefined kind of Attachment is the Name, which can
       keep the name of an object. Some of loaders (e.g. the WRL loader)
       create these kinds of Attachments for named nodes.
    */
    
    /*
        An Attachment is a FieldContainer and as such needs to be created using
        ::create().
    */
    NamePtr name = Name::create();
    
    /* 
        The NameAttachment only has a single field, there's no need to use the
        mask here.
    */
    beginEditCP(name);
    {
        name->getField().setValue("Scene");
    }
    endEditCP  (name);
    
    /*
        Attach the name to the scene node.
     */
    beginEditCP(scene, Node::AttachmentsFieldMask);
    {
        scene->addAttachment(name);
    }
    endEditCP  (scene, Node::AttachmentsFieldMask);
    
    /*
        Check if the scene has a Name attachment
        
        Attachments are categorized by the GroupID of their class. Every
        AttachmentContainer generally keeps only one attachment of a specific
        kind. 
     */
    AttachmentPtr a;
    
    a = scene->findAttachment(Name::getClassType());
    
    if(a!=NullFC)
    {
        NamePtr n = NamePtr::dcast(a);
        
        SLOG << "Node name: " << n->getField().getValue() << endl;
    }
    else
    {
        SLOG << "Node has no name!" << endl;
    }
    
    // use the finder helper to find a named object
    
    finder f;
    NodePtr found;
    
    found = f.find(scene, "Scene");  
    SLOG << "Found object " << found << " named Scene." << endl;
    
    found = f.find(scene, "TF_DETAIL"); 
    if(found == NullFC)
    {
        SLOG << "Found no object named TF_DETAIL (did you load the tie?)." 
             << endl;
    }
    else
    {
        SLOG << "Found object " << found << " named TF_DETAIL." << endl;
    }
    
    // Use the simple attachment defined above
    
    MyAttachmentPtr mya = MyAttachment::create();
    
    beginEditCP(mya);
    {
        mya->getField().setValue(42);
    }
    endEditCP  (mya);
    
    // attach it to the scene
    beginEditCP(scene, Node::AttachmentsFieldMask);
    {
        scene->addAttachment(mya);
    }
    endEditCP  (scene, Node::AttachmentsFieldMask);

    // and check if it's still there       
    a = scene->findAttachment(MyAttachment::getClassType());
    
    if(a!=NullFC)
    {
        MyAttachmentPtr m = MyAttachmentPtr::dcast(a);
        
        SLOG << "Node my value: " << m->getField().getValue() << endl;
    }
    else
    {
        SLOG << "Node has no myAttachment!" << endl;
    }
    
    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // tell the manager what to manage
    mgr->setWindow(gwin );
    mgr->setRoot  (scene);

    // show the whole scene
    mgr->showAll();

    // GLUT main loop
    glutMainLoop();

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

    // GLUT init
    int winid = setupGLUT(&argc, argv);

    // the connection between GLUT and OpenSG
    GLUTWindowPtr gwin = GLUTWindow::create();
    beginEditCP(gwin);
        gwin->setId(winid);
        gwin->setSize( 800, 800 );
        gwin->init();
    endEditCP(gwin);

    // create root node
    _scene = makeCoredNode<Group>();

    GeometryPtr geo = makeBoxGeo(0.5, 0.5, 0.5, 1, 1, 1);

    // share the chunk
    CGChunkPtr cg = CGChunk::create();
    beginEditCP(cg);
        cg->setVertexProfile(CG_PROFILE_ARBVP1);
        cg->setVertexProgram(_vp_program);
        cg->setFragmentProfile(CG_PROFILE_ARBFP1);
        cg->setFragmentProgram(_fp_program);
    endEditCP(cg);

    Int32 size = 4;
    
    // start color
    Vec3f sc(0.0, 0.0, 0.0);
    
    // end color
    Vec3f ec(1.0, 1.0, 1.0);

    Real32 sr = (ec[0] - sc[0]) / Real32((size*2));
    Real32 sg = (ec[1] - sc[1]) / Real32((size*2));
    Real32 sb = (ec[2] - sc[2]) / Real32((size*2));
    
    Vec3f color(sc);

    Int32 x = - size;
    Int32 y = - size;
    Int32 z = - size;

    UInt32 iterations = size*2 * size*2 * size*2;

    printf("Creating %u cubes ...\n", iterations);
    for(UInt32 i=0;i<iterations;++i)
    {
        ChunkMaterialPtr cmat = ChunkMaterial::create();

        // ok use one CGChunk and n CGParameterChunks
        CGParameterChunkPtr cgparameter = CGParameterChunk::create();
        beginEditCP(cgparameter);
            cgparameter->setCGChunk(cg);
            cgparameter->setUniformParameter("SurfaceColor", color);
        endEditCP(cgparameter);
        _cgparameter = cgparameter;

        beginEditCP(cmat);
            cmat->addChunk(cg);
            cmat->addChunk(cgparameter);
        endEditCP(cmat);
    
        TransformPtr trans;
        NodePtr trans_node = makeCoredNode<Transform>(&trans);
        beginEditCP(trans);
            trans->getMatrix().setTranslate(Real32(x), Real32(y), Real32(z));
        endEditCP(trans);

        MaterialGroupPtr mg;
        NodePtr mg_node = makeCoredNode<MaterialGroup>(&mg);
        beginEditCP(mg, MaterialGroup::MaterialFieldMask);
            mg->setMaterial(cmat);
        endEditCP(mg, MaterialGroup::MaterialFieldMask);

        NodePtr geonode = Node::create();
        beginEditCP(geonode, Node::CoreFieldMask);
            geonode->setCore(geo);
        endEditCP(geonode, Node::CoreFieldMask);
        
        beginEditCP(mg_node);
            mg_node->addChild(geonode);
        endEditCP(mg_node);

        beginEditCP(trans_node);
            trans_node->addChild(mg_node);
        endEditCP(trans_node);
    
        // add to scene
        beginEditCP(_scene);
            _scene->addChild(trans_node);
        endEditCP(_scene);
        
        // ----
        ++x;
        color[0] += sr;

        if(x == size)
        {
            x = - size;
            ++y;
            color[0] = sc[0];
            color[1] += sg;
            if(y == size)
            {
                y = - size;
                ++z;
                color[1] = sc[1];
                color[2] += sb;
            }
        }
    }


    // create the SimpleSceneManager helper
    _mgr = new SimpleSceneManager;

    // tell the manager what to manage
    _mgr->setWindow(gwin );
    _mgr->setRoot(_scene);

    // show the whole scene
    _mgr->showAll();

    // create a gradient background.
    GradientBackgroundPtr gback = GradientBackground::create();
    beginEditCP(gback, GradientBackground::LineFieldMask);
        gback->clearLines();
        gback->addLine(Color3f(0.7, 0.7, 0.8), 0);
        gback->addLine(Color3f(0.0, 0.1, 0.3), 1);
    endEditCP(gback, GradientBackground::LineFieldMask);

    WindowPtr win = _mgr->getWindow();
    beginEditCP(win);
        for(int i=0;i<win->getPort().size();++i)
        {
            ViewportPtr vp = win->getPort()[i];
            beginEditCP(vp);
                vp->setBackground(gback);
            endEditCP(vp);
        }
    endEditCP(win);
        
    // GLUT main loop
    glutMainLoop();

    return 0;
}
int main (int argc, char **argv)
{

    // GLUT init

    osgInit(argc, argv);
    osgLog().setLogLevel ( OSG::LOG_DEBUG );

    FieldContainerPtr pProto = Geometry::getClassType().getPrototype();

    GeometryPtr pGeoProto = GeometryPtr::dcast(pProto);

    if(pGeoProto != NullFC)
    {
        pGeoProto->setDlistCache(true);
    }

    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    UInt32 id = glutCreateWindow("OpenSG");
    glutKeyboardFunc(key);
    glutReshapeFunc(resize);
    glutDisplayFunc(display);       
    // glutMouseFunc(mouse);   
    // glutMotionFunc(motion); 
    
    glutIdleFunc(display);
    
    // create a material (need that to test textures)
    
    ChunkMaterialPtr mat;  

    beginEditCP(mat);
    
    mat = ChunkMaterial::create();
   
    MaterialChunkPtr mc = MaterialChunk::create();  
 
    beginEditCP(mc);
    mc->setDiffuse( Color4f( 1,.8,.8,1 ) );
    mc->setAmbient( Color4f( 0.1,0.1,0.1,1 ) );
    mc->setSpecular( Color4f( 1,1,1,1 ) );
    mc->setShininess( 20 );
 
    mc->setBackMaterial(true);
    mc->setBackColorMaterial(GL_DIFFUSE);
    mc->setBackDiffuse( Color4f( 1,0,0,1 ) );
    mc->setBackAmbient( Color4f( 0.1,0.1,0.1,1 ) );
    mc->setBackSpecular( Color4f( 0,1,0,1 ) );
    mc->setBackShininess( 10 );
    mc->setLit(true);
 
    endEditCP(mc);

    mat->addChunk(mc);

    // Texture chunk
    
    UChar8 imgdata[] = 
        {  255,0,0,128,  0,255,0,128,  0,0,255,255,  255,255,255,255 };
    ImagePtr pImage = Image::create();
    pImage->set( Image::OSG_RGBA_PF, 2, 2, 1, 1, 1, 0, imgdata );

    if ( argc > 1 )
        pImage->read( argv[1] );
    
    TextureChunkPtr xchunk;
    xchunk = TextureChunk::create();
    xchunk->setImage( pImage );
    xchunk->setMinFilter( GL_NEAREST );
    xchunk->setMagFilter( GL_NEAREST );
    xchunk->setWrapS( GL_REPEAT );
    xchunk->setWrapT( GL_REPEAT );
    xchunk->setEnvMode( GL_MODULATE );

    mat->addChunk( xchunk );

    endEditCP(mat);

    objects[0] = makePolygon(ccwSquare, 
                             sizeof(ccwSquare)/sizeof(double[3]));
    objects[1] = makePolygon(ccwSquare, 
                             sizeof(ccwSquare)/sizeof(double[3]));
    
    objects[2] = makePolygon(star,
                             sizeof(star)/sizeof(double[3]));
    objects[3] = makePolygon(star,
                             sizeof(star)/sizeof(double[3]));
    
    objects[4] = makePolygon(cwSquare, 
                             sizeof(cwSquare)/sizeof(double[3]));
    objects[5] = makePolygon(cwSquare, 
                             sizeof(cwSquare)/sizeof(double[3]));
    
    objects[6] = makePolygon(doubleEight, 
                             sizeof(doubleEight)/sizeof(double[3]));
    objects[7] = makePolygon(doubleEight, 
                             sizeof(doubleEight)/sizeof(double[3]));

    //tesselate every second object
    for(int i = 1; i < nobjects; i+=2) {

      GeometryPtr::dcast(objects[i]->getCore())->setMaterial( mat );
      std::cerr << "Polygon Node: " << std::hex << objects[i] << std::endl;

      // try to create convex primitives
      OSG::GeometryPtr pGeo = GeometryPtr::dcast(objects[i]->getCore());

      std::cerr << "Tesselating polygon : "
                << i
                << std::endl;

      createConvexPrimitives(pGeo);
    }

    // normal material
    SimpleMaterialPtr nmat;     
    
    nmat = SimpleMaterial::create();
    beginEditCP(nmat);
    nmat->setEmission( Color3f( 0,1,0 ) );
    endEditCP(nmat);
    
    for ( UInt16 i = 0; i < nobjects; i++ )
    {
        normalobjects[i] = calcVertexNormalsGeo(
            GeometryPtr::dcast(objects[i]->getCore()), .5);

        GeometryPtr::dcast(normalobjects[i]->getCore())->setMaterial(nmat);
    }
    
    // 
    // The action

    win = GLUTWindow::create();
    win->setId(id);
    win->init();

    glEnable( GL_LIGHT0 );
    float p[4]={0,0,1,0};
    glLightfv(GL_LIGHT0, GL_POSITION, p);
    float c[4]={1,1,1,1};
    glLightfv(GL_LIGHT0, GL_DIFFUSE, c);
    glLightfv(GL_LIGHT0, GL_SPECULAR, c);
    
    glPointSize( 3 );
    
    glEnable( GL_DEPTH_TEST );
    glEnable( GL_LIGHTING );
    glClearColor( .3, .3, .8, 1 );

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluPerspective( 60, 1, 0.1, 10 );
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    gluLookAt( 3, 3, 3,  0, 0, 0,   0, 0, 1 );
   
    dact = DrawAction::create();
    dact->setWindow(get_pointer(win));
    dact->setFrustumCulling( false );

    glutMainLoop();
    
    return 0;
}
示例#10
0
int main (int argc, char **argv)
{
    osgInit(argc,argv);

    // GLUT init

    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
    int winid = glutCreateWindow("OpenSG");
    glutKeyboardFunc(key);
    glutVisibilityFunc(vis);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);

    glutIdleFunc(display);

    // glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );

    glEnable( GL_DEPTH_TEST );
    glEnable( GL_LIGHTING );
    glEnable( GL_LIGHT0 );

    // OSG

    SceneFileHandler::the().print();

    // create the graph

    // beacon for camera and light
    NodePtr b1n = Node::create();
    GroupPtr b1 = Group::create();
    beginEditCP(b1n);
    b1n->setCore( b1 );
    endEditCP(b1n);

    // transformation
    NodePtr t1n = Node::create();
    TransformPtr t1 = Transform::create();
    beginEditCP(t1n);
    t1n->setCore( t1 );
    t1n->addChild( b1n );
    endEditCP(t1n);

    cam_trans = t1;

    // light

    NodePtr dlight = Node::create();
    DirectionalLightPtr dl = DirectionalLight::create();

    beginEditCP(dlight);
    dlight->setCore( dl );
    endEditCP(dlight);

    beginEditCP(dl);
    dl->setAmbient( .3, .3, .3, 1 );
    dl->setDiffuse( 1, 1, 1, 1 );
    dl->setDirection(0,0,1);
    dl->setBeacon( b1n);
    endEditCP(dl);

    // root
    root = Node::create();
    GroupPtr gr1 = Group::create();
    beginEditCP(root);
    root->setCore( gr1 );
    root->addChild( t1n );
    root->addChild( dlight );
    endEditCP(root);

    // Load the file

    NodePtr file = NullFC;
    NodePtr file1 = NullFC;

    if ( argc > 1 )
        file1 = SceneFileHandler::the().read(argv[1]);

    if ( file1 == NullFC )
    {
        std::cerr << "Couldn't load file, ignoring" << std::endl;
        file1 = makeTorus( .5, 2, 16, 16 );
    }

    file1->updateVolume();

//    file->dump();

//    subRefCP(file);

//    return 0;


    Vec3f min,max;
    file1->getVolume().getBounds( min, max );

    std::cout << "Volume: from " << min << " to " << max << std::endl;


    file = Node::create();
    MaterialGroupPtr testMat = MaterialGroup::create();

    SimpleMaterialPtr defaultMaterial = SimpleMaterial::create();

    beginEditCP(defaultMaterial);
    defaultMaterial->setDiffuse(Color3f(1,.0,.0));
    defaultMaterial->setAmbient(Color3f(0.1,0.1,0.1));
    defaultMaterial->setSpecular(Color3f(1,1,1));
    defaultMaterial->setShininess(20);
    endEditCP  (defaultMaterial);


    testMat->setMaterial(defaultMaterial);

    beginEditCP(file);
    {
//        file->setCore(testMat);
        file->setCore(Group::create());
        file->addChild(file1);
    }
    endEditCP  (file);

    scene_trans      = Transform::create();
    NodePtr sceneTrN = Node::create();

    beginEditCP(sceneTrN);
    {
        sceneTrN->setCore(scene_trans);
        sceneTrN->addChild(file);
        sceneTrN->addChild(makeTorus( .5, 2, 16, 16 ));
    }
    endEditCP(sceneTrN);

    beginEditCP(dlight);
    dlight->addChild(sceneTrN);
    endEditCP(dlight);

    std::cerr << "Tree: " << std::endl;
//  root->dump();

    // Camera

    cam = PerspectiveCamera::create();
    cam->setBeacon( b1n );
    cam->setFov( deg2rad( 90 ) );
    cam->setNear( 0.1 );
    cam->setFar( 100000 );

    // Background
    SolidBackgroundPtr bkgnd = SolidBackground::create();
    beginEditCP(bkgnd, SolidBackground::ColorFieldMask);
    bkgnd->setColor(Color3f(1,1,1));
    endEditCP(bkgnd, SolidBackground::ColorFieldMask);

    // Viewport

    vp = Viewport::create();
    vp->setCamera( cam );
    vp->setBackground( bkgnd );
    vp->setRoot( root );
    vp->setSize( 0,0, 1,1 );

    // Window
    std::cout << "GLUT winid: " << winid << std::endl;

    GLUTWindowPtr gwin;

    GLint glvp[4];
    glGetIntegerv( GL_VIEWPORT, glvp );

    gwin = GLUTWindow::create();
    gwin->setId(winid);
    gwin->setSize( glvp[2], glvp[3] );

    win = gwin;

    win->addPort( vp );

    win->init();

    // Action

    ract = DrawAction::create();
    renact = RenderAction::create();

    // tball

    Vec3f pos;
    pos.setValues(min[0] + ((max[0] - min[0]) * 0.5),
                  min[1] + ((max[1] - min[1]) * 0.5),
                  max[2] + ( max[2] - min[2] ) * 1.5 );

    float scale = (max[2] - min[2] + max[1] - min[1] + max[0] - min[0]) / 6;

    Pnt3f tCenter(min[0] + (max[0] - min[0]) / 2,
                  min[1] + (max[1] - min[1]) / 2,
                  min[2] + (max[2] - min[2]) / 2);

    tball.setMode( Trackball::OSGObject );
    tball.setStartPosition( pos, true );
    tball.setSum( true );
    tball.setTranslationMode( Trackball::OSGFree );
    tball.setTranslationScale(scale);
    tball.setRotationCenter(tCenter);

    // run...

    glutMainLoop();

    return 0;
}
示例#11
0
int main (int argc, char **argv)
{
    osgInit(argc,argv);

    FieldContainerPtr pProto = Geometry::getClassType().getPrototype();

    GeometryPtr pGeoProto = GeometryPtr::dcast(pProto);

    if(pGeoProto != NullFC)
    {
        pGeoProto->setDlistCache(false);
    }

    // GLUT init

    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | GLUT_STENCIL);
    int winid = glutCreateWindow("OpenSG");
    glutKeyboardFunc(key);
    glutVisibilityFunc(vis);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);       
    glutMouseFunc(mouse);   
    glutMotionFunc(motion); 
    
    glutIdleFunc(display);  

    // glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
    
    glEnable( GL_DEPTH_TEST );
    glEnable( GL_LIGHTING );
//    glEnable( GL_LIGHT0 );
    glEnable(GL_NORMALIZE);

    // OSG

    SceneFileHandler::the().print();

    // create the graph

    // beacon for camera and light  
    NodePtr b1n = Node::create();
    GroupPtr b1 = Group::create();
    beginEditCP(b1n);
    b1n->setCore( b1 );
    endEditCP(b1n);

    // transformation
    NodePtr t1n = Node::create();
    TransformPtr t1 = Transform::create();
    beginEditCP(t1n);
    t1n->setCore( t1 );
    t1n->addChild( b1n );
    endEditCP(t1n);

    cam_trans = t1;

    // light
    
//#define OSG_HLIGHT

    NodePtr dlight = Node::create();
#ifdef OSG_HLIGHT
    DirectionalLightPtr dl = DirectionalLight::create();
#else
    GroupPtr dl = Group::create();
#endif

    beginEditCP(dlight);
    dlight->setCore( dl );
    endEditCP(dlight);
    
#ifdef OSG_HLIGHT
    beginEditCP(dl);
    dl->setAmbient( .2, .2, .2, 1 );
    dl->setDiffuse( .8, .8, .8, 1 );
    dl->setDirection(0,0,1);
    dl->setBeacon( b1n);
    endEditCP(dl);
#endif

    // root
    root = Node::create();
    GroupPtr gr1 = Group::create();
    beginEditCP(root);
    root->setCore( gr1 );
    root->addChild( t1n );
    root->addChild( dlight );
    endEditCP(root);

    // Load the file

    NodePtr file = NullFC;
    
/*
    if ( argc > 1 )
        file = SceneFileHandler::the().read(argv[1]);
    
    if ( file == NullFC )
    {
        cerr << "Couldn't load file, ignoring" << endl;
        file = makeTorus( .5, 2, 16, 16 );
    }
*/

    VRMLLoader *pFile = new VRMLLoader;

    pFile->scanFile(argv[1], 0);

    VRMLToOSGAction                      aVRMLToOSG;

    FieldContainerPtr           pFC         = NullFC;
    VRMLBindings::NodeBinderPtr pNodeBinder = NULL;

    fprintf(stderr, "Resnode %p\n", pFile->getFileTree());
    
    aVRMLToOSG.setNameNodeMap(pFile->getNameNodeMap());
    aVRMLToOSG.setDataTransferMode(VRMLToOSGAction::SwapData);
    aVRMLToOSG.apply(pFile->getFileTree());

/*    
    pNodeBinder = (pFile->getFileTree())->getBinder();
    
    if(pNodeBinder != NULL)
    {
        pFC = pNodeBinder->getFCPtr();  
        
        if(pFC != NullFC)
        {
            file = NodePtr::dcast(pFC);
        }
        else
        {
            fprintf(stderr, "FCPtr NULL\n");
        }
    }
    else
    {
        fprintf(stderr, "Binder NULL\n");
    }
    */

    file = aVRMLToOSG.getRoot();

    if(file == NullFC)
        return 0;
 
    file->updateVolume();

    Vec3f min,max;
    file->getVolume().getBounds( min, max );
    
    cout << "Volume: from " << min << " to " << max << endl;

    beginEditCP(dlight);
    dlight->addChild( file );
    endEditCP(dlight);

    cerr << "Tree: " << endl;
//  root->dump();

    // Camera
    
    cam = PerspectiveCamera::create();
    cam->setBeacon( b1n );
    cam->setFov( deg2rad( 90 ) );
    cam->setNear( 0.1 );
    cam->setFar( 10000 );

    // Background
    SolidBackgroundPtr bkgnd = SolidBackground::create();

    // Viewport

    vp = Viewport::create();
    vp->setCamera( cam );
    vp->setBackground( bkgnd );
    vp->setRoot( root );
    vp->setSize( 0,0, 1,1 );

    // Window
    cout << "GLUT winid: " << winid << endl;

    GLUTWindowPtr gwin;

    GLint glvp[4];
    glGetIntegerv( GL_VIEWPORT, glvp );

    gwin = GLUTWindow::create();
    gwin->setId(winid);
    gwin->setSize( glvp[2], glvp[3] );

    win = gwin;

    win->addPort( vp );

    win->init();

    // Action
    
    ract = DrawAction::create();

    // tball

    Vec3f pos(min[0] + ((max[0] - min[0]) * 0.5), 
              min[1] + ((max[1] - min[1]) * 0.5), 
              max[2] + ( max[2] - min[2] ) * 1.5 );

    float scale = (max[2] - min[2] + max[1] - min[1] + max[0] - min[0]) / 6;

    Pnt3f tCenter(min[0] + (max[0] - min[0]) / 2,
                  min[1] + (max[1] - min[1]) / 2,
                  min[2] + (max[2] - min[2]) / 2);

    tball.setMode( Trackball::OSGObject );
    tball.setStartPosition( pos, true );
    tball.setSum( true );
    tball.setTranslationMode( Trackball::OSGFree );
    tball.setTranslationScale(scale);
    tball.setRotationCenter(tCenter);
    // run...

#ifdef PAR_SCHEDULER
    Thread::getCurrent()->getChangeList()->applyTo(1);

    VSC::VSCScheduler::the()->run();
#endif
    
    glutMainLoop();
    
    return 0;
}
示例#12
0
int main(int argc, char **argv)
{
    printf("Press the keys '1', '2' and '3' in order to switch between "
           "the different example objects.\n");
    printf("Press key 'f' to toggle FatBorder rendering.\n");

    osgInit(argc,argv);
    // GLUT init
    glutInit(&argc, argv);
    glutInitWindowSize(800,600);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);

    int winid = glutCreateWindow("OpenSG");

    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutIdleFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutKeyboardFunc(keyboard);
    GLUTWindowPtr gwin = GLUTWindow::create();
    beginEditCP(gwin);
    {
        gwin->setId(winid);
    }
    endEditCP(gwin);
    gwin->init();

    // create the scene
//    NodePtr scene;
    g_scene = makeScene( );

    setModel(0);
//    scene = makeTeapot( );

    if ( g_scene == NullFC )
    {
        std::cerr<<"makeScene returned NullFC, exiting..."<<std::endl;
        return -1;
    }

    // create the SimpleSceneManager helper
    g_mgr = new SimpleSceneManager;

    // create the window and initial camera/viewport
    g_mgr->setWindow( gwin );
    // tell the manager what to manage
    g_mgr->setRoot  ( g_scene );

    // show the whole scene
    g_mgr->showAll();
    g_mgr->redraw();
    SolidBackgroundPtr bgr = SolidBackground::create();
    beginEditCP( bgr );
    bgr->setColor( Color3f( 1.0, 1.0, 1.0 ));
    endEditCP( bgr );
    g_mgr->getWindow()->getPort(0)->setBackground( bgr );

    // GLUT main loop
    glutMainLoop();

    return 0;
}
示例#13
0
int main (int argc, char **argv)
{
  osgInit( argc, argv );
  
  glutInit( &argc, argv );
  glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
  int winID = glutCreateWindow("OpenSG");
  
  glutKeyboardFunc(key);
  glutVisibilityFunc(vis);
  glutReshapeFunc(resize);
  glutDisplayFunc(display);       
  glutMouseFunc(mouse);   
  glutMotionFunc(motion); 
  
  glutIdleFunc(display);
  
  glEnable( GL_DEPTH_TEST );
  glEnable( GL_LIGHTING );
  glEnable( GL_LIGHT0 );
  glClearColor( .1, .6, .2, 1 );
  //glCullFace( GL_BACK );
  //glEnable( GL_CULL_FACE );

  //BEACON
  NodePtr beaconNode = Node::create();
  GroupPtr beaconCore = Group::create();
  beginEditCP( beaconNode );
  beaconNode->setCore( beaconCore );
  endEditCP( beaconNode );

  //TRANSFORM
  NodePtr transNode = Node::create();
  TransformPtr transCore = Transform::create();
  beginEditCP( transNode );
  transNode->setCore( transCore );
  transNode->addChild( beaconNode );
  endEditCP( transNode );
  cam_trans = transCore;
  
  //OBJECT0: Plane
  objects[0] = makeBox( 3,3,2, 2,2,1 );
  calcFaceNormals( GeometryPtr::dcast(objects[0]->getCore()) );
  normals[0] = calcFaceNormalsGeo( GeometryPtr::dcast(objects[0]->getCore()), 0.5 );
  
  //OBJECT1: Sphere
  objects[1] = makeSphere( 2, 2 );
  calcFaceNormals( GeometryPtr::dcast(objects[1]->getCore()) );
  normals[1] = calcFaceNormalsGeo( GeometryPtr::dcast(objects[1]->getCore()), 0.5 );
  
  //OBJECT2: Cone
  objects[2] = makeConicalFrustum( 1.5, 0.75, 2, 8, true, true, true );
  calcFaceNormals( GeometryPtr::dcast(objects[2]->getCore()) );
  normals[2] = calcFaceNormalsGeo( GeometryPtr::dcast(objects[2]->getCore()), 0.5 );
    
  //OBJECT3: Custom Single Indexed Geometry
  objects[3] = Node::create();
  GeometryPtr obj3Core= Geometry::create();
  GeoIndicesUI32Ptr obj3Index = GeoIndicesUI32::create();
  GeoPositions3f::PtrType obj3Pnts = GeoPositions3f::create();
  GeoColors3f::PtrType obj3Colors = GeoColors3f::create();
  GeoPTypesPtr obj3Types = GeoPTypesUI8::create();
  GeoPLengthsPtr obj3Lengths = GeoPLengthsUI32::create();
 
  beginEditCP( obj3Pnts );
  obj3Pnts->addValue( Pnt3f(0, 0,0) );
  obj3Pnts->addValue( Pnt3f(1,-1,0) );
  obj3Pnts->addValue( Pnt3f(1, 1,0) );
  
  obj3Pnts->addValue( Pnt3f(1, 1,0) );
  obj3Pnts->addValue( Pnt3f(1,-1,0) );
  obj3Pnts->addValue( Pnt3f(3,-1.3,0) );
  obj3Pnts->addValue( Pnt3f(3, 1.3,0) );
  
  obj3Pnts->addValue( Pnt3f(3, 1.3,0) );
  obj3Pnts->addValue( Pnt3f(3,-1.3,0) );
  obj3Pnts->addValue( Pnt3f(4, 0,0) );
  endEditCP( obj3Pnts );
  
  beginEditCP( obj3Types );
  //obj3Types->addValue( GL_TRIANGLES );
  //obj3Types->addValue( GL_QUADS );
  //obj3Types->addValue( GL_TRIANGLES );
  obj3Types->addValue( GL_POLYGON );
  endEditCP( obj3Types );
  
  beginEditCP( obj3Lengths );
  //obj3Lengths->addValue( 3 );
  //obj3Lengths->addValue( 4 );
  //obj3Lengths->addValue( 3 );
  
  obj3Lengths->addValue( 6 );
  endEditCP( obj3Lengths );
   
  beginEditCP( obj3Colors );
  for( UInt32 i=0; i<obj3Pnts->getSize(); ++i )
  {
      obj3Colors->addValue( Color3f(.7,.7,.7) );
  }
  endEditCP( obj3Colors );
  
  beginEditCP( obj3Index );
  //for( UInt32 i=0; i<obj3Pnts->getSize(); ++i )
  //{
  // obj3Index->addValue( i );
  //}
  obj3Index->addValue( 0 );
  obj3Index->addValue( 1 );
  obj3Index->addValue( 5 );
  obj3Index->addValue( 9 );
  obj3Index->addValue( 6 );
  obj3Index->addValue( 2 );
  endEditCP( obj3Index );
  
  beginEditCP( obj3Core );
  obj3Core->setIndices( obj3Index );
  obj3Core->setPositions( obj3Pnts );
  obj3Core->setTypes( obj3Types );
  obj3Core->setLengths( obj3Lengths );
  obj3Core->setColors( obj3Colors );
  endEditCP( obj3Core );
  
  beginEditCP( objects[3] );
  objects[3]->setCore( obj3Core );
  endEditCP( objects[3] );
  calcFaceNormals( GeometryPtr::dcast(objects[3]->getCore()) );
  normals[3] = calcFaceNormalsGeo( GeometryPtr::dcast(objects[3]->getCore()), 0.5 );
    
  //ROOT
  root = Node::create();
  GroupPtr rootCore = Group::create();
  beginEditCP(root);
  root->setCore(rootCore);
  root->addChild(transNode);
  root->addChild(objects[0]);
  root->addChild(normals[0]);
  activeObj = root->findChild( objects[0] );
  activeNorm = root->findChild( normals[0] );
  endEditCP(root);
  
  camera = PerspectiveCamera::create();
  camera->setBeacon( beaconNode );
  camera->setFov( 90 );
  camera->setNear( 0.1 );
  camera->setFar( 10000 );
  
  SolidBackgroundPtr background = SolidBackground::create();
  
  viewp = Viewport::create();
  viewp->setCamera( camera );
  viewp->setBackground( background );
  viewp->setRoot( root );
  viewp->setSize( 0,0, 1,1 );
  
  GLint glVP[4];
  glGetIntegerv( GL_VIEWPORT, glVP );
  
  GLUTWindowPtr gwin = GLUTWindow::create();
  gwin->setId(winID);
  gwin->setSize(glVP[2], glVP[3]);
  
  window = gwin;
  window->addPort( viewp );
  window->init();
  
  drAct = DrawAction::create();
  
  Vec3f pos( 0, 0, 3 );
  tball.setMode( Trackball::OSGObject );
  tball.setStartPosition( pos, true );
  tball.setSum( true );
  tball.setTranslationMode( Trackball::OSGFree );
  
  glutMainLoop();
  return 0;
}
示例#14
0
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
    char     *opt;
    NodePtr   scene=NullFC;

    // OSG init
    ChangeList::setReadWriteDefault();
    osgInit(argc,argv);

    // GLUT init
    int winid = setupGLUT(&argc, argv);

    // the connection between this client and the servers
    mwin= SortLastWindow::create();

    // all changes must be enclosed in beginEditCP and endEditCP
    // otherwise the changes will not be transfered over the network.
    beginEditCP(mwin);

    // evaluate params
    for(int a=1 ; a<argc ; ++a)
    {
        if(argv[a][0] == '-')
        {
            switch(argv[a][1])
            {
                case 'm': mwin->setConnectionType("Multicast");
                          cout << "Connection type set to Multicast" << endl;
                          break;
                case 'p': mwin->setConnectionType("SockPipeline");
                          cout << "Connection type set to SockPipeline" << endl;
                          break;
                case 'i': opt = argv[a][2] ? argv[a]+2 : argv[++a];
                          if(opt != argv[argc])
                              mwin->setConnectionInterface(opt);
                          break;
                case 'a': opt = argv[a][2] ? argv[a]+2 : argv[++a];
                          if(opt != argv[argc])
                              mwin->setServiceAddress(opt);
                          break;
                case 'f': opt = argv[a][2] ? argv[a]+2 : argv[++a];
                          if(opt != argv[argc])
                              scene = SceneFileHandler::the().read(
                                  opt,0);
                          break;
                default:  std::cout << argv[0]  
                                    << " -m"
                                    << " -p"
                                    << " -i interface"
                                    << " -f file"
                                   << endLog;
                          return 0;
            }
        }
        else
        {
            printf("%s\n",argv[a]);
            mwin->getServers().push_back(argv[a]);
        }
    }

    // Set the composer to use
    
    mwin->setComposer(PipelineComposer::create());
    
    // window size
    mwin->setSize(800,600);

    // Create/set the client window that will display the result
    
    clientWindow = GLUTWindow::create();
    
    beginEditCP(clientWindow);
    glutReshapeWindow(800,600);
    clientWindow->setId(winid);
    clientWindow->init();
    endEditCP(clientWindow);
    
    clientWindow->resize(800,600);
    
    // Set the client window that will display the result
    mwin->setClientWindow(clientWindow);
    
    // end edit of cluster window
    endEditCP(mwin);

    // create default scene
    if(scene == NullFC)
    {
        scene = makeNodeFor(Group::create());
        beginEditCP(scene);
        scene->addChild(makeTorus(.5, 2, 16, 16));
        scene->addChild(makeCylinder(1, .3, 8, true, true, true));
        endEditCP(scene);
    }
    
    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // tell the manager what to manage
    mgr->setWindow(mwin );
    mgr->setRoot  (scene);

    // show the whole scene
    mgr->showAll();
    
    // initialize window
    mwin->init();
    
    // GLUT main loop
    glutMainLoop();

    return 0;
}
示例#15
0
int main(int argc, char** argv)
{
    std::cout << "osgInit()..." << std::endl;
    osgInit( argc, argv );
    
    std::cout << "glutInit()..." <<  std::endl;
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
    int winID = glutCreateWindow("OpenSG");
    
    glutKeyboardFunc(key);
    glutVisibilityFunc(vis);
    glutReshapeFunc(resize);
    glutDisplayFunc(display);       
    glutMouseFunc(mouse);   
    glutMotionFunc(motion); 
    
    glutIdleFunc(display);
            
    glEnable( GL_DEPTH_TEST );
    glEnable( GL_LIGHTING );
    glEnable( GL_LIGHT0 );
    glClearColor( .3, .3, .8, 1 );
    
    std::cout << "Creating objects..." << std::endl;
    
    //BEACON
    NodePtr beaconNode = Node::create();
    GroupPtr beaconCore = Group::create();
    beginEditCP( beaconNode );
    beaconNode->setCore( beaconCore );
    endEditCP( beaconNode );
    
    /*
    //LIGHT
    NodePtr dlightNode = Node::create();
    DirectionalLightPtr dlightCore = DirectionalLight::create();
    beginEditCP(dlightNode);
    dlightNode->setCore(dlightCore);
    endEditCP(dlightNode);
    
    beginEditCP(dlightCore);
    dlightCore->setAmbient( .3, .3, .3, 1 );
    dlightCore->setDiffuse( .5, .5, .5, 1 );
    dlightCore->setDirection( 0, 0 , 1 );
    dlightCore->setBeacon( beaconNode );
    endEditCP(dlightCore);
    */
        
    //TRANSFORM
    NodePtr transNode = Node::create();
    TransformPtr transCore = Transform::create();
    beginEditCP( transNode );
    transNode->setCore( transCore );
    transNode->addChild( beaconNode );
    endEditCP( transNode );
    cam_trans = transCore;
    
    //LOD
    NodePtr lowDetailNode = makeBox( 1,1,1, 1,1,1 );
    GeometryPtr boxCore = GeometryPtr::dcast(lowDetailNode->getCore());
    SimpleMaterialPtr lowDetailMat = SimpleMaterial::create();
    lowDetailMat->setDiffuse( Color3f( 1,0,0 ) );
    lowDetailMat->setAmbient( Color3f( 1,0,0 ) );
    boxCore->setMaterial( lowDetailMat );
    
    NodePtr     medDetailNode = makeSphere( 1, 1 );
    GeometryPtr medSphereCore = GeometryPtr::dcast(medDetailNode->getCore());
    SimpleMaterialPtr medDetailMat = SimpleMaterial::create();
    medDetailMat->setDiffuse( Color3f( 0,1,0 ) );
    medDetailMat->setAmbient( Color3f( 0,1,0 ) );
    medSphereCore->setMaterial( medDetailMat );
    
    NodePtr highDetailNode = makeSphere( 2, 1 );
    GeometryPtr highSphereCore = GeometryPtr::dcast(highDetailNode->getCore());
    SimpleMaterialPtr highDetailMat = SimpleMaterial::create();
    highDetailMat->setDiffuse( Color3f( 0,0,1 ) );
    highDetailMat->setAmbient( Color3f( 0,0,1 ) );
    highDetailMat->setSpecular( Color3f(1, 1, 1) );
    highDetailMat->setShininess( 10 );
    highSphereCore->setMaterial( highDetailMat );
    
    NodePtr lodNode = Node::create();
    DistanceLODPtr lodNodeCore = DistanceLOD::create();
    beginEditCP(lodNode);
    lodNode->setCore(lodNodeCore);
    lodNode->addChild( highDetailNode );
    lodNode->addChild( medDetailNode );
    lodNode->addChild( lowDetailNode );
    endEditCP(lodNode);
    
    beginEditCP(lodNodeCore);
    lodNodeCore->editSFCenter()->setValue( Pnt3f(0, 0, 2) );
    lodNodeCore->editMFRange()->push_back( 4.0 );
    lodNodeCore->editMFRange()->push_back( 8.0 );
    lodNodeCore->editMFRange()->push_back( 11.0 );
    endEditCP(lodNodeCore);
    
        
    //TRANSFORM LOD
    NodePtr transLODNode = Node::create();
    TransformPtr transLODCore = Transform::create();
    transMat.setTranslate( 1, -1, -1 );
    beginEditCP(transLODCore);
    transLODCore->editSFMatrix()->setValue( transMat );
    endEditCP(transLODCore);
    beginEditCP( transLODNode );
    transLODNode->setCore( transLODCore );
    transLODNode->addChild( lodNode );
    endEditCP( transLODNode );
    
    
        
    //ROOT
    root = Node::create();
    GroupPtr rootCore = Group::create();
    beginEditCP(root);
    root->setCore(rootCore);
    root->addChild(transNode);
    root->addChild(transLODNode);
    endEditCP(root);
    
    
    
    camera = PerspectiveCamera::create();
    beginEditCP(camera);
    camera->setBeacon( beaconNode );
    camera->setFov( deg2rad(90) );
    camera->setNear( 0.1 );
    camera->setFar( 10000 );
    endEditCP(camera);
    
    SolidBackgroundPtr background = SolidBackground::create();
    
    viewp = Viewport::create();
    beginEditCP(viewp);
    viewp->setCamera( camera );
    viewp->setBackground( background );
    viewp->setRoot( root );
    viewp->setSize( 0,0, 1,1 );
    endEditCP(viewp);
    
    GLint glVP[4];
    glGetIntegerv( GL_VIEWPORT, glVP );
    
    GLUTWindowPtr gwin = GLUTWindow::create();
    gwin->setId(winID);
    gwin->setSize(glVP[2], glVP[3]);
    
    window = gwin;
    beginEditCP(window);
    window->addPort( viewp );
    window->init();
    endEditCP(window);
    
    drAct = DrawAction::create();
    
    Vec3f pos( 0, 0, 3 );
    tball.setMode( Trackball::OSGObject );
    tball.setStartPosition( pos, true );
    tball.setSum( true );
    tball.setTranslationMode( Trackball::OSGFree );

    glutMainLoop();
    return 0;
}
示例#16
0
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
	cout << "Testing screen aligned text generation and file-IO." << endl;
	
    if(argc == 1)
    {
        FFATAL(("Need *.txf or *.ttf font file\n"));
        return -1;
    }

    // OSG init
    osgInit(argc, argv);

    // GLUT init
    int             winid = setupGLUT(&argc, argv);

    // the connection between GLUT and OpenSG
    GLUTWindowPtr   gwin = GLUTWindow::create();
    gwin->setId(winid);
    gwin->init();

    PathHandler paths;

    paths.push_backPath(".");

    //paths.push_backPath("/home/elmi/wrk/development/texFont");
    // create the scene
    FontStyle   *fontStyle = FontStyleFactory::the().create( paths, argv[1], 
															 0.25);
	cout << fontStyle->getFontName() << endl;

    // create the scene
    NodePtr pTorus = makeTorus( 0.02, 0.55, 16, 16);
	ChunkMaterialPtr mat = ChunkMaterial::create();

    MaterialChunkPtr pmc = MaterialChunk::create();
    pmc->setDiffuse( Color4f( 1,0,0,0.5 ) );
    pmc->setAmbient( Color4f( 0,1,0,0.5 ) );
    pmc->setSpecular( Color4f( 0,0,1,0.5 ) );
	pmc->setLit( true );
    pmc->setShininess( 20 );

	beginEditCP(mat);
	{
	mat->addChunk( pmc );
	}
	endEditCP(mat);

    scene = Node::create();
	GroupPtr group = Group::create();
    beginEditCP( scene );
    {
        scene->setCore( group );
	}
    endEditCP( scene );

	SharedFontStylePtr sfs = SharedFontStyle::create(); 
	sfs->setContainedFontStyle( fontStyle );

	for( int x=0; x<100; x += 20 )
	{
		for( int y=0; y<100; y += 20 )
		{
			for( int z=0; z<100; z += 20 )
			{
				ScreenAlignedTextPtr scaText = ScreenAlignedText::create();
				if( scaText == NullFC )
				{
					exit (2);
				}
				SharedFontStyleWrapperPtr pFSWrapper = SharedFontStyleWrapper::create();
				pFSWrapper->setFStyleContainer( sfs );
				ostringstream cString;
				cString << '(' 
						<< x 
						<< ',' 
						<< y
						<< ','
						<< z
						<< ')'
						<< endl;

				beginEditCP(scaText);
				{
					scaText->setPosition( Vec3f ( x, y, z ) );
					scaText->setFont( pFSWrapper );
					scaText->setVerticalLineDistance( 0.20 );
					scaText->setAlignment( 0 );
					scaText->editMFText()->push_back( cString.str() );
					scaText->setMaterial( mat );
				}
				endEditCP(scaText);
				NodePtr pTextNode = Node::create();
				beginEditCP( pTextNode );
				{
					pTextNode->setCore( scaText );
				}
				beginEditCP( scene );
				{
					scene->addChild( pTextNode );
				}
				endEditCP( scene );	
				cout << "Erzeugt : " 
					 << cString.str() 
					 << endl;
			}
		}
    }

	//NodePtr pCopied = scene;

#if 1
	{
		ofstream outFileStream( "/tmp/text.osg" );

		if( !outFileStream )
		{
			cerr << "cannot open file" << endl;
			exit(2);
		}
		//FILE *pFile = fopen( "isolinien.osg","w" );
		//BINWriter writer( pFile );
		OSGWriter writer( outFileStream );
		writer.write( scene );
	}
#endif

#if 0
	VRMLWriteAction *pWriter = VRMLWriteAction::create();
	scene->dump();
	pWriter->open("allesscheisse.wrl");
	pWriter->write( scene);
	pWriter->close();
	delete pWriter;
#endif

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // tell the manager what to manage
    mgr->setWindow(gwin);
    mgr->setRoot( scene );

    // show the whole scene
    mgr->showAll();

    // GLUT main loop
    glutMainLoop();

    return 0;
}
示例#17
0
int main (int argc, char **argv)
{
    osgInit(argc,argv);

    // GLUT init

    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    int winid = glutCreateWindow("OpenSG");
    glutKeyboardFunc(key);
    glutVisibilityFunc(vis);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);

    glutIdleFunc(display);

    // glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );

    glEnable( GL_DEPTH_TEST );
    glEnable( GL_LIGHTING );
    glEnable( GL_LIGHT0 );

    // OSG

    SceneFileHandler::the().print();

    // create the graph

    // beacon for camera and light
    NodePtr b1n = Node::create();
    GroupPtr b1 = Group::create();
    beginEditCP(b1n);
    b1n->setCore( b1 );
    endEditCP(b1n);

    // transformation
    NodePtr t1n = Node::create();
    TransformPtr t1 = Transform::create();
    beginEditCP(t1n);
    t1n->setCore( t1 );
    t1n->addChild( b1n );
    endEditCP(t1n);

    cam_trans = t1;

    // light

    NodePtr dlight = Node::create();
    DirectionalLightPtr dl = DirectionalLight::create();

    beginEditCP(dlight);
    dlight->setCore( dl );
    endEditCP(dlight);

    beginEditCP(dl);
    dl->setAmbient( .3, .3, .3, 1 );
    dl->setDiffuse( 1, 1, 1, 1 );
    dl->setDirection(0,0,1);
    dl->setBeacon( b1n);
    endEditCP(dl);

    // root
    root = Node::create();
    GroupPtr gr1 = Group::create();
    beginEditCP(root);
    root->setCore( gr1 );
    root->addChild( t1n );
    root->addChild( dlight );
    endEditCP(root);

    // Load the file

    NodePtr file = NullFC;

    if ( argc > 1 )
        file = SceneFileHandler::the().read(argv[1]);

    if ( file == NullFC )
    {
        std::cerr << "Couldn't load file, ignoring" << std::endl;
        file = makeTorus( .5, 2, 16, 16 );
    }

    file->updateVolume();

    Vec3f min,max;
    file->getVolume().getBounds( min, max );

    std::cout << "Volume: from " << min << " to " << max << std::endl;

    beginEditCP(dlight);
    dlight->addChild( file );
    endEditCP(dlight);

    std::cerr << "Tree: " << std::endl;
//  root->dump();

    // Camera

    cam = PerspectiveCamera::create();
    cam->setBeacon( b1n );
    cam->setFov( deg2rad( 90 ) );
    cam->setNear( 0.1 );
    cam->setFar( 10000 );

    // Background
    SolidBackgroundPtr bkgnd = SolidBackground::create();

    // Foreground
    GrabForegroundPtr fgnd = GrabForeground::create();

    image = Image::create();
    beginEditCP(image);
    image->set(Image::OSG_RGB_PF, 1);
    endEditCP(image);

    fgnd->setImage(image);

    // Viewport

    vp = Viewport::create();
    vp->setCamera( cam );
    vp->setBackground( bkgnd );
    vp->editMFForegrounds()->push_back( fgnd );
    vp->setRoot( root );
    vp->setSize( 0,0, 1,1 );

    // Window
    std::cout << "GLUT winid: " << winid << std::endl;

    GLUTWindowPtr gwin;

    GLint glvp[4];
    glGetIntegerv( GL_VIEWPORT, glvp );

    gwin = GLUTWindow::create();
    gwin->setId(winid);
    gwin->setSize( glvp[2], glvp[3] );

    win = gwin;

    win->addPort( vp );

    win->init();

    // Action

    ract = DrawAction::create();

    // tball

    Vec3f pos( 0, 0, max[2] + ( max[2] - min[2] ) * 1.5 );

    tball.setMode( Trackball::OSGObject );
    tball.setStartPosition( pos, true );
    tball.setSum( true );
    tball.setTranslationMode( Trackball::OSGFree );

    // run...

    glutMainLoop();

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

    // GLUT init
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);

    int winid = glutCreateWindow("OpenSG CGFX Shader");

    // the connection between GLUT and OpenSG
    _gwin = GLUTWindow::create();
    _gwin->setId(winid);
    _gwin->setSize( 800, 800 );
    _gwin->init();

    // init callbacks
    glutSetWindow(winid);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutIdleFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutKeyboardFunc(keyboard);

    const char *effectFile = "BumpGlossedShiny.fx";

    if(argc > 1)
    {
        effectFile = argv[1];
    }

    _cgfxmat = CGFXMaterial::create();
    beginEditCP(_cgfxmat);
        _cgfxmat->setEffectFile(effectFile);
        // this multipass technique leads to a render bug, I have no idea what's wrong :-(
        //_cgfxmat->setTechnique(1);
    endEditCP(_cgfxmat);

    ChunkMaterialPtr mat2 = ChunkMaterial::create();
    MaterialChunkPtr matc = MaterialChunk::create();
    beginEditCP(matc);
        matc->setDiffuse(Color4f(1, 0, 0, 1));
    endEditCP(matc);
    beginEditCP(mat2);
        mat2->addChunk(matc);
        //mat2->addChunk(texc);
    endEditCP(mat2);

    // create root node
    _scene = Node::create();

    GeometryPtr geo1 = makeLatLongSphereGeo(50, 50, 1.0f);
    
    OSG::calcVertexTangents(geo1, 0, Geometry::TexCoords1FieldId, Geometry::TexCoords2FieldId);

    beginEditCP( geo1, Geometry::MaterialFieldMask);
        geo1->setMaterial(_cgfxmat);
    endEditCP(geo1, Geometry::MaterialFieldMask);

    NodePtr sphere1 = Node::create();
    beginEditCP(sphere1, Node::CoreFieldMask);
        sphere1->setCore(geo1);
    endEditCP(sphere1, Node::CoreFieldMask);

    TransformPtr trans1 = Transform::create();
    beginEditCP(trans1);
        trans1->getMatrix().setTranslate(-2 , 0, 0);
    endEditCP(trans1);
    NodePtr transn1 = Node::create();
    beginEditCP(transn1);
        transn1->setCore(trans1);
        transn1->addChild(sphere1);
    beginEditCP(transn1);

    //
    GeometryPtr geo2 = makeLatLongSphereGeo(50, 50, 1.0f);
    
    beginEditCP( geo2, Geometry::MaterialFieldMask);
        geo2->setMaterial(mat2);
    endEditCP(geo2, Geometry::MaterialFieldMask);

    NodePtr sphere2 = Node::create();
    beginEditCP(sphere2, Node::CoreFieldMask);
        sphere2->setCore(geo2);
    endEditCP(sphere2, Node::CoreFieldMask);

    TransformPtr trans2 = Transform::create();
    beginEditCP(trans2);
        trans2->getMatrix().setTranslate(2 , 0, 0);
    endEditCP(trans2);
    NodePtr transn2 = Node::create();
    beginEditCP(transn2);
        transn2->setCore(trans2);
        transn2->addChild(sphere2);
    beginEditCP(transn2);

    beginEditCP(_scene);
        _scene->setCore(Group::create());
        _scene->addChild(transn1);
        _scene->addChild(transn2);
    endEditCP(_scene);

    // create the SimpleSceneManager
    _mgr = new SimpleSceneManager;

    // tell the manager what to manage
    _mgr->setWindow(_gwin);

    _mgr->setRoot(_scene);

    // show the whole scene
    _mgr->showAll();

    // create a gradient background.
    GradientBackgroundPtr gback = GradientBackground::create();
    beginEditCP(gback, GradientBackground::LineFieldMask);
        gback->clearLines();
        gback->addLine(Color3f(0.7, 0.7, 0.8), 0);
        gback->addLine(Color3f(0.0, 0.1, 0.3), 1);
    endEditCP(gback, GradientBackground::LineFieldMask);

    WindowPtr win = _mgr->getWindow();
    beginEditCP(win);
        for(int i=0;i<win->getPort().size();++i)
        {
            ViewportPtr vp = win->getPort()[i];
            beginEditCP(vp);
                vp->setBackground(gback);
            endEditCP(vp);
        }
    endEditCP(win);


    // GLUT main loop
    glutMainLoop();

    return 0;
}
示例#19
0
int main (int argc, char **argv)
{
    osgInit(argc,argv);

    // GLUT init

    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    int winid = glutCreateWindow("OpenSG");
    glutKeyboardFunc(key);
    glutVisibilityFunc(vis);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);

    glutIdleFunc(display);


    if ( argc > 1 && isdigit(argv[1][0]) )
    {
        nhviewports = atoi( argv[1] );
        argv++;
        argc--;
    }
    if ( argc > 1 && isdigit(argv[1][0]) )
    {
        nvviewports = atoi( argv[1] );
        argv++;
        argc--;
    }
    else
        nvviewports = nhviewports;

    // glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );

    glEnable( GL_DEPTH_TEST );
    glEnable( GL_LIGHTING );
    glEnable( GL_LIGHT0 );

    // OSG

    SceneFileHandler::the().print();

    // create the graph

    // beacon for camera and light
    NodePtr b1n = Node::create();
    GroupPtr b1 = Group::create();
    beginEditCP(b1n);
    b1n->setCore( b1 );
    endEditCP(b1n);

    // transformation
    NodePtr t1n = Node::create();
    TransformPtr t1 = Transform::create();
    beginEditCP(t1n);
    t1n->setCore( t1 );
    t1n->addChild( b1n );
    endEditCP(t1n);

    cam_trans = t1;

    // light

    NodePtr dlight = Node::create();
    DirectionalLightPtr dl = DirectionalLight::create();

    beginEditCP(dlight);
    dlight->setCore( dl );
    endEditCP(dlight);

    beginEditCP(dl);
    dl->setAmbient( .3, .3, .3, 1 );
    dl->setDiffuse( 1, 1, 1, 1 );
    dl->setDirection(0,0,1);
    dl->setBeacon( b1n);
    endEditCP(dl);

    // root
    root = Node::create();
    GroupPtr gr1 = Group::create();
    beginEditCP(root);
    root->setCore( gr1 );
    root->addChild( t1n );
    root->addChild( dlight );
    endEditCP(root);

    // Load the file

    NodePtr file = NullFC;

    if ( argc > 1 )
        file = SceneFileHandler::the().read(argv[1]);

    if ( file == NullFC )
    {
        std::cerr << "Couldn't load file, ignoring" << std::endl;
        file = makeTorus( .5, 2, 16, 16 );
        file = makeBox( 1,1,1, 1,1,1 );
    }

    file->updateVolume();

    Vec3f min,max;
    file->getVolume().getBounds( min, max );

    std::cout << "Volume: from " << min << " to " << max << std::endl;

    beginEditCP(dlight);
    dlight->addChild( file );
    endEditCP(dlight);

    std::cerr << "Tree: " << std::endl;
    root->dump();

    // Camera

    cam = PerspectiveCamera::create();
    cam->setBeacon( b1n );
    cam->setFov( deg2rad( 90 ) );
    cam->setNear( 0.1 );
    cam->setFar( 100 );

    // Background
#if 1 // doesn't work right now
    SkyBackgroundPtr sbkgnd = SkyBackground::create();


    sbkgnd->editMFSkyColor()->push_back(Color4f(1, 0, 0,0.5));
    sbkgnd->editMFSkyAngle()->push_back(Pi / 2);
    sbkgnd->editMFSkyColor()->push_back(Color4f(0, 1, 0,0.5));
    sbkgnd->editMFSkyAngle()->push_back(Pi);
    sbkgnd->editMFSkyColor()->push_back(Color4f(0, 0, 1,0.5));

#else
    SolidBackgroundPtr sbkgnd = SolidBackground::create();
    sbkgnd->setColor( Color3f(.5, .5, 1) );
#endif

    // Window
    std::cout << "GLUT winid: " << winid << std::endl;

    GLUTWindowPtr gwin;

    GLint glvp[4];
    glGetIntegerv( GL_VIEWPORT, glvp );

    gwin = GLUTWindow::create();
    gwin->setId(winid);
    gwin->setSize( glvp[2], glvp[3] );

    win = gwin;

    // Viewports & Decorators

    vp = new ViewportPtr [ nhviewports * nvviewports ];
    deco = new TileCameraDecoratorPtr [ nhviewports * nvviewports ];

    for ( int i = 0; i < nhviewports; i++ )
    {
        for ( int j = 0; j < nvviewports; j++ )
        {
            int ind = i * nvviewports + j;
            vp[ind] = Viewport::create();
            vp[ind]->setBackground( sbkgnd );
            vp[ind]->setRoot( root );
            vp[ind]->setSize(   1./nhviewports * i,1./nvviewports * j,
                                1./nhviewports * (i+1),1./nvviewports * (j+1) );

            deco[ind] = TileCameraDecorator::create();
            deco[ind]->setDecoratee( cam );
            deco[ind]->setSize( 1./nhviewports * i,1./nvviewports * j,
                                1./nhviewports * (i+1),1./nvviewports * (j+1) );

            deco[ind]->setFullSize( 800, 800 );

            vp[ind]->setCamera( deco[ind] );
            // for debugging: vp[ind]->setCamera( cam );

            win->addPort( vp[ind] );
        }
    }

    win->init();

#if 0
    // Test write, to check generic access

    ofstream outFileStream( "test.osg" );
    if( !outFileStream )
    {
        std::cerr << "Can not open output stream to file" << std::endl;
        return -1;
    }

    OSGWriter writer( outFileStream, 4 );
    writer.write( win );


#endif

    // Action

    ract = DrawAction::create();
    ract->setFrustumCulling( false );

    // tball

    Vec3f pos( 0, 0, max[2] + ( max[2] - min[2] ) * 1.5 );

    tball.setMode( Trackball::OSGObject );
    tball.setStartPosition( pos, true );
    tball.setSum( true );
    tball.setTranslationMode( Trackball::OSGFree );

    // run...

    glutMainLoop();

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

    // GLUT init
    int             winid = setupGLUT(&argc, argv);

    // the connection between GLUT and OpenSG
    GLUTWindowPtr   gwin = GLUTWindow::create();
    gwin->setId(winid);
    gwin->init();

    PathHandler paths;
    paths.push_backPath(".");

    // create the scene
    // build a special txf-font with only a little set of characters
    FontStyle   *fontStyle = FontStyleFactory::the().create(paths, argv[1], 1);
    assert(fontStyle);
    //((TTFontStyle *) fontStyle)->createTXFMap((UChar8 *) ". fps0123456789");
    ((TTFontStyle *) fontStyle)->createTXFMap();

    // write it somewhere
#if 1
    std::ofstream    target;
    target.open("statistics.txf");
    fontStyle->dump(target);
    target.close();
#else
    ostrstream  target;
    fontStyle->dump(target);
#endif
#if 1
    std::ifstream    source;
    source.open("statistics.txf");
#else
#if 0
    // Hack, to get the stuff into memory
    int     bufSize = 100000;
    char    *buffer = new char[bufSize];
    int     numRead;
    FILE    *in = fopen("statistics.txf", "r");

    numRead = fread(buffer, 1, bufSize, in);

    fclose(in);

    istrstream  source(buffer, numRead);
#else
    istrstream  source(target.str(), target.pcount());
#endif
#endif
    TXFFont     *font = new TXFFont("test.txf", source);
    font->initFont();

    fontText.setSize(1);
    font->createInstance(&fontText);

    fontText.setJustifyMajor(MIDDLE_JT);

    lineVec.push_back("0000.00 fps");

    // TXF-Style Texture+Geometry
    n = Node::create();
    txfGeo = Geometry::create();

    ImagePtr  pTxfImg = Image::create();

    if(fontText.fillTXFGeo(*txfGeo, true, lineVec))
    {
        fontText.fillTXFImage(pTxfImg);

        SimpleTexturedMaterialPtr   mat = SimpleTexturedMaterial::create();
        beginEditCP(mat);
        {
            mat->setImage(pTxfImg);
        }

        endEditCP(mat);
        txfGeo->setMaterial(mat);
        beginEditCP(n, Node::CoreFieldMask);
        {
            n->setCore(txfGeo);
        }
    }

    scene = Node::create();

    // add a transformation to make it move
    trans = Transform::create();
    beginEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);
    {
        scene->setCore(trans);
        scene->addChild(n);
    }

    endEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // tell the manager what to manage
    mgr->setWindow(gwin);
    mgr->setRoot(scene);

    // show the whole scene
    mgr->showAll();

    // GLUT main loop
    glutMainLoop();

    return 0;
}