void motion(int x, int y)
{
    OSG::Real32 w = clientWindow->getWidth(), h = clientWindow->getHeight();


    OSG::Real32 a = -2. * ( lastx / w - .5 ),
                b = -2. * ( .5 - lasty / h ),
                c = -2. * ( x / w - .5 ),
                d = -2. * ( .5 - y / h );

    if ( mouseb & ( 1 << GLUT_LEFT_BUTTON ) )
    {
        tball.updateRotation( a, b, c, d );
    }
    else if ( mouseb & ( 1 << GLUT_MIDDLE_BUTTON ) )
    {
        tball.updatePosition( a, b, c, d );
    }
    else if ( mouseb & ( 1 << GLUT_RIGHT_BUTTON ) )
    {
        tball.updatePositionNeg( a, b, c, d );
    }
    lastx = x;
    lasty = y;
	glutPostRedisplay();
}
int main(int argc, char **argv)
{
    OSG::osgInit(argc,argv);
    
    {
        int winid = setupGLUT(&argc, argv);
        OSG::GLUTWindowRecPtr gwin = OSG::GLUTWindow::create();
        gwin->setGlutId(winid);
        gwin->init();
    
        scene =createScenegraph();
    
        mgr = new OSG::SimpleSceneManager;
        mgr->setWindow(gwin );
        mgr->setRoot  (scene);
        mgr->showAll();
        
        OSG::Navigator * nav = mgr->getNavigator();
        nav->setFrom(nav->getFrom()+OSG::Vec3f(0,50,0));
        
        OSG::commitChanges();
    }
    
    glutMainLoop();

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

    {
        int winid = setupGLUT(&argc, argv);
        OSG::GLUTWindowRecPtr gwin = OSG::GLUTWindow::create();
        gwin->setGlutId(winid);
        gwin->init();

        if (argc > 1)
            scene = createScenegraph(argv[1]);
        else
            scene = createScenegraph("Data/brick_quads.wrl");

        mgr = new OSG::SimpleSceneManager;
        mgr->setWindow(gwin );
        mgr->setRoot  (scene);
        mgr->showAll();

        OSG::commitChanges();
    }

    glutMainLoop();

    return 0;
}
// Initialize GLUT & OpenSG and set up the scene
int doMain(int argc, char **argv)
{
    std::cout << "start a cluster server with './testClusterServer -w pipe0'\n"
                 "press 'c' to connect to the servers.\n"
                 "press 'd' to disconnect from the servers.\n"
                 "press 'n' to delete current scene.\n"
                 "press 't' to create a torus.\n"
                 "press 'l' to load scene 'tie.wrl'.\n"
              << std::endl;
    
    // OSG init
    OSG::osgInit(argc,argv);

    OSG::VTKPolyDataMapper::getClassType().dump();

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

    // the connection between GLUT and OpenSG

    _client_win = OSG::GLUTWindow::create();

    _client_win->setGlutId(winid);
    _client_win->init();
    _client_win->setSize(300,300);
    
    for(OSG::Int32 i=0;i<argc-1;++i)
    {
        if(argv[i+1] != NULL)
            _pipenames.push_back(argv[i+1]);
    }

    if(_pipenames.empty())
        _pipenames.push_back("pipe0");
    
    _root = OSG::Node::create();
    
    _root->setCore(OSG::Group::create());
    
    // create default scene
//    NodePtr scene = makeTorus(.5, 2, 16, 16);
    OSG::NodeUnrecPtr scene = initVTK();

    _root->addChild(scene);

    // create the SimpleSceneManager helper
    _mgr = OSG::SimpleSceneManager::create();

    // tell the manager what to manage
    _mgr->setWindow(_client_win );
    _mgr->setRoot  (_root);

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

    return 0;
}
void key(unsigned char key, int /*x*/, int /*y*/)
{
	switch ( key )
	{
        case 'd':
            window->getPort(0)->getRoot()->dump();
            break;
        case 's':
            OSG::SceneFileHandler::the()->write(
                window->getPort(0)->getRoot(),"server.osg");
            cleanup();
            exit(0);
            break;
	}
}
void reshape( int width, int height )
{
    winWidth  = width;
    winHeight = height;
    std::cout << "reshape " << width << " " << height << std::endl;
	window->resize( width, height );
}
void reshape( int width, int height )
{
    printf("reshape %d %d\n",width,height);
    glViewport(0, 0, width, height);

	clientWindow->resize( width, height );

	glutPostRedisplay();
}
int main(int argc,char **argv)
{
    int winid;

    // initialize Glut
    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGB |GLUT_DEPTH | GLUT_DOUBLE);

    if(!argv[1])
    {
        std::cout << "No name was given!" << std::endl;
        return -1;
    }
    
    // init OpenSG
    OSG::osgInit(argc, argv);

    winid = glutCreateWindow(argv[1]);
    glutDisplayFunc(display);
    glutIdleFunc(display);
    glutReshapeFunc(reshape);
    glutSetCursor(GLUT_CURSOR_NONE);

    ract = OSG::RenderAction::create();

    window = OSG::GLUTWindow::create();
    window->setGlutId(winid);
    window->init();

    window->resize(512, 512);

    //create a new server that will be connected via multicast
    //argv[1] is the name of the server (at least it should be...)
    server = new OSG::ClusterServer(window, argv[1], "StreamSock", "");
    server->start();

    glutMainLoop();

    return 0;
}
void display()
{
    if(!running)
    {
        server->start();
        running=true;
        glutShowWindow();
    }
    /*! ignore rendering in zero sized windows */
    if(!winWidth || !winHeight)
        return;
    try
    {                                                       
        OSG::FrameHandler::the()->frame();
        OSG::commitChanges();
        server->render(ract);
        // clear changelist from prototypes
        OSG::Thread::getCurrentChangeList()->clear();
    } 
    catch(OSG_STDEXCEPTION_NAMESPACE::exception &e)
    {
        if(exitOnError)
        {
            SLOG << e.what() << std::endl;
            printf("Exit on error %s",e.what());
            try
            {
                cleanup();
            }

            catch(...)
            {
            }

            exit(0);
        }
        else
        {
            window->clearPorts();
            // try to restart server
            try
            {
                server->stop();
            }
            catch(...)
            {
            }
            running=false;
            glutHideWindow();
        }
    }
}
// react to size changes
void reshape(int w, int h)
{
    if(glutGetWindow() == mainwinid)
    {
        mgr->resize(w,h);
        glutPostRedisplay();
    }
    else if(glutGetWindow() == debugwinid)
    {
        debugwin->resize(w,h);
        glutPostRedisplay();       
    }
}
int main(int argc, char **argv)
{
    OSG::osgInit(argc,argv);
    
    {
        int winid = setupGLUT(&argc, argv);
        OSG::GLUTWindowRecPtr gwin = OSG::GLUTWindow::create();
        gwin->setGlutId(winid);
        gwin->init();
    
        scene = createScenegraph();
    
        mgr = OSG::SimpleSceneManager::create();
        mgr->setWindow(gwin );
        mgr->setRoot  (scene);
        mgr->showAll();
        
        OSG::commitChanges();
    }
    
    glutMainLoop();

    return 0;
}
static void connectCluster(void)
{
    if(_cluster_win != NULL)
        return;

    OSG::Viewport *clientvp = _client_win->getPort(0);
    
    // create the viewports for the cluster just a simple one ...
    OSG::ViewportUnrecPtr vp = OSG::Viewport::create();

    vp->setCamera    (_mgr->getCamera());
    vp->setBackground(clientvp->getBackground());
    vp->setRoot      (clientvp->getRoot());
    vp->setSize      (0,0, 1,1);

    // the connection between this client and the servers
    _cluster_win = OSG::MultiDisplayWindow::create();

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

    for(OSG::UInt32 i=0;i<_pipenames.size();++i)
        _cluster_win->editMFServers()->push_back(_pipenames[i]);
    // dummy size for navigator
    _cluster_win->setSize(300,300);
    _cluster_win->addPort(vp);

    OSG::Thread::getCurrentChangeList()->commitChangesAndClear();
    OSG::Thread::getCurrentChangeList()->fillFromCurrentState();
    OSG::Thread::getCurrentChangeList()->dump();
    // create from the current state a changelist.

    // initialize window
    _cluster_win->init();

    // apply changelist to the servers
    _cluster_win->render((OSG::RenderAction *) _mgr->getRenderAction());

    // clear changelist
    OSG::Thread::getCurrentChangeList()->clear();

    glutPostRedisplay();
}
int main(int argc, char *argv[])
{
    // Init the OpenSG subsystem
    OSG::osgInit(argc, argv);

    {
        // We create a GLUT Window (that is almost the same for most applications)
        int winid = setupGLUT(&argc, argv);
        OSG::GLUTWindowRecPtr gwin = OSG::GLUTWindow::create();
        gwin->setGlutId(winid);
        gwin->init();

        // Create the face
        std::string family = "SANS";
        OSG::TextFace::Style style = OSG::TextFace::STYLE_PLAIN;
        OSG::TextTXFParam txfParam;
        txfParam.size = 46;
        txfParam.gap = 1;
        txfParam.setCharacters("Hello World!");
        txfParam.textureWidth = 0;
        OSG::TextTXFFaceRefPtr face =
            OSG::TextTXFFace::create(family, style, txfParam);
        if (face == 0)
        {
            std::cerr << "ERROR: Cannot create face object!" << std::endl;
            return -1;
        }

        // Lay out one single line of text
        std::string text = "Hello World!"; // Use UTF-8 encoding!
        OSG::TextLayoutParam layoutParam;
        layoutParam.horizontal = true;
        layoutParam.leftToRight = true;
        layoutParam.topToBottom = true;
        layoutParam.majorAlignment = OSG::TextLayoutParam::ALIGN_FIRST;
        layoutParam.minorAlignment = OSG::TextLayoutParam::ALIGN_FIRST;
        layoutParam.spacing = 1.f;
        layoutParam.length.push_back(0.f);
        layoutParam.maxExtend = 0.f;
        OSG::TextLayoutResult layoutResult;
        face->layout(text, layoutParam, layoutResult);

        // Create the text geometry
        OSG::Real32 scale = 1.f;
        OSG::NodeRecPtr scene = face->makeNode(layoutResult, scale);

        // Get the texture that contains the characters of the font
        OSG::ImageRecPtr image = face->getTexture();

        // Create the texture that will hold the image
        OSG::SimpleTexturedMaterialRecPtr tex =
            OSG::SimpleTexturedMaterial::create();
        tex->setImage(image);
        tex->setEnvMode(GL_MODULATE);
        tex->setDiffuse(OSG::Color3f(1, 0, 0));

        // Assign the texture to the geometry
        OSG::GeometryRecPtr geo =
            dynamic_cast<OSG::Geometry *>(scene->getCore());
        geo->setMaterial(tex);

        // Create and setup the SSM
        mgr = new OSG::SimpleSceneManager;
        mgr->setWindow(gwin);
        mgr->setRoot(scene);

        // Create a blue background
        OSG::SolidBackgroundRecPtr bg = OSG::SolidBackground::create();
        bg->setColor(OSG::Color3f(0.1, 0.1, 0.5));

        gwin->getPort(0)->setBackground(bg);

        mgr->showAll();

        OSG::commitChanges();
    }

    // Give Control to the GLUT Main Loop
    glutMainLoop();

    return 0;
}
void reshape(int width, int height)
{
    window->resize(width, height);
}
int doMain(int argc,char **argv)
{
    int                      i;
    char                    *opt;
    std::vector<std::string> filenames;
    std::vector<std::string> servers;
    std::string              connectionType = "StreamSock";
    std::string              connectionParameters;
    int                      rows=1;
    int                      cols=-1;
    char                     type='M';
    bool                     clientRendering=true;
    bool                     compose=false;

    std::string              composerType="";
    std::string              autostart;
    
    for(i=1;i<argc;i++)
    {
        if(strlen(argv[i])>1 && argv[i][0]=='-')
        {
            switch(argv[i][1])
            {
                case 'o':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    connectionParameters = opt;
                    printf("connectionParameters: '%s'\n", connectionParameters.c_str());
                    break;
                case 'A':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    autostart = opt;
                    break;
                case 'D':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    if(sscanf(opt,"%f,%f,%f",&ca,&cb,&cc)!=3)
                    {
                        std::cout << "Copy opton -D x,y,z" << std::endl;
                        return 1;
                    }
                    break;
                case 'b':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    serviceInterface.assign(opt);
                    serviceInterfaceValid = true;
                    break;
                case 'B':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    serviceAddress.assign(opt);
                    serviceAddressValid = true;
                    break;
                case 'f':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    filenames.push_back(opt);
                    printf("<%s>\n",opt);
                    break;
                case 'm':
                    connectionType="Multicast";
                    break;
                case 'r':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    if(sscanf(opt,"%d,%d",&rows,&cols) != 2)
                        sscanf(opt,"%d",&rows);
                    break;
                case 't':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    subtilesize=atoi(opt);
                    break;
#ifdef FRAMEINTERLEAVE
                case 'i':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    interleave=atoi(opt);
                    break;
#endif
                case 'C':
                    compose=true;
                    break;
                case 'F':
                    type='F';
                    break;
                case 'X':
                    type='X';
                    break;
                case 'P':
                    type='P';
                    break;
                case 'L':
                {
                    type='L';
                    int lpos=2;
                    while(argv[i][lpos])
                    {
                        if(argv[i][lpos] == 'B') 
                            composerType = "BinarySwapComposer";
                        if(argv[i][lpos] == 'P')
                            composerType = "PipelineComposer";
                        if(argv[i][lpos] == 'S')
                            composerType = "SepiaComposer";
                        if(argv[i][lpos] == 'p')
                            pipelinedBufferRead = true;
                        ++lpos;
                    }
                    break;
                }
                case 'M':
                    type='M';
                    break;
                case 'I':
                    type='I';
                    break;
                case 's':
                    stereoMode=1;
                    break;
                case 'c':
                    stereoMode=2;
                    break;
                case 'S':
                    info=true;
                    break;
                case 'e':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    sscanf(opt,"%f",&eyedistance);
                    break;
                case 'z':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    sscanf(opt,"%f",&zeroparallax);
                    break;
                case 'd':
                    clientRendering=false;
                    break;
                case 'v':
                    multiport=true;
                    break;
                case 'x':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    sscanf(opt,"%d",&serverx);
                    break;
                case 'y':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    sscanf(opt,"%d",&servery);
                    break;
                case 'a':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    animName=opt;
                    loadAnim();
                    animate=true;
                    break;
                case 'l':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    if(sscanf(opt,"%d,%d",&animLoops,&animLength) != 2)
                    {
                        animLength = 30;
                        if(sscanf(opt,"%d",&animLoops) != 1)
                        {
                            animLoops = -1;
                        }
                    }
                    break;
                case 'g':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    if(sscanf(opt,"%d,%d,%d,%d",
                              &winwidth,&winheight,&winx,&winy) != 4)
                        sscanf(opt,"%d,%d",&winwidth,&winheight);
                    break;
                case 'G':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    connectionDestination = opt;
                    break;
                case 'i':
                    opt = argv[i][2] ? argv[i]+2 : argv[++i];
                    connectionInterface = opt;
                    break;
                default:
                    std::cout << argv[0] 
                              << "-ffile -m -rrows[,cols] -C -M"
                              << std::endl;
                    std::cout << "-m  use multicast" << std::endl
                              << "-G  multicast group" << std::endl
                              << "-i  interface" << std::endl
                              << "-b  service interface" << std::endl
                              << "-M  multi display" << std::endl
#ifdef FRAMEINTERLEAVE
                              << "-I  frame interleave" << std::endl
#endif
                              << "-r  number of display rows" << std::endl
                              << "-C  compose" << std::endl
                              << "-F  sort-first" << std::endl
                              << "-L  sort-last" << std::endl
                              << "-h  this msg" << std::endl
                              << "-s  stereo" << std::endl
                              << "-c  red/cyan stereo" << std::endl
                              << "-e  eye distance" << std::endl
                              << "-z  zero parallax" << std::endl
                              << "-d  disable client rendering"<<std::endl
                              << "-v  use two viewports" << std::endl
                              << "-x  server x resolution" << std::endl
                              << "-y  server y resolution" << std::endl
                              << "-t  subtile size for img composition" << std::endl
                              << "-D  x,y,z duplicate geometry" << std::endl
                              << "-A  Autostart command" << std::endl
                              << "-o  connection parameter string e.g. \"TTL=8\"" << std::endl;
                    return 0;
            }
        }
        else
        {
            servers.push_back(argv[i]);
        }
    }

    OSG::ChangeList::setReadWriteDefault(true);
    OSG::osgInit(argc, argv);
    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
    if(winx >=0 && winy >=0)
        glutInitWindowPosition(winx,winy);
    glutInitWindowSize(winwidth,winheight);
    winid = glutCreateWindow("OpenSG Cluster Client");
    glutKeyboardFunc(key);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);     
    if(animate)
        glutIdleFunc(display);       
    glutMouseFunc(mouse);   
    glutMotionFunc(motion); 
    ract = OSG::RenderAction::create();
#ifdef OSG_OLD_RENDER_ACTION
    ract->setSortTrans(true);
    ract->setZWriteTrans(true);
    ract->setLocalLights(true);
    ract->setCorrectTwoSidedLighting(true);
#endif

    // clear changelist from prototypes
    OSG::Thread::getCurrentChangeList()->clear();
    
    // create cluster window
    switch(type)
    {
        case 'M': 
            multidisplay=OSG::MultiDisplayWindow::create();
            clusterWindow=multidisplay;
            break;
        case 'X': 
            balancedmultidisplay=OSG::BalancedMultiWindow::create();
            clusterWindow=balancedmultidisplay;
            break;
        case 'F':
            sortfirst=OSG::SortFirstWindow::create();
            if(compose)
                sortfirst->setCompose(true);
            else
                sortfirst->setCompose(false);
            clusterWindow=sortfirst;
            break;
        case 'L':
            sortlast=OSG::SortLastWindow::create();
            if(!composerType.empty())
            {
                OSG::FieldContainerUnrecPtr fcPtr = 
                    OSG::FieldContainerFactory::the()->
                    createContainer(composerType.c_str());
                OSG::ImageComposer *icPtr = 
                    dynamic_cast<OSG::ImageComposer *>(fcPtr.get());
                
                if(icPtr != NULL)
                {
                    if(dynamic_cast<OSG::PipelineComposer *>(icPtr) != NULL)
                    {
                        if(subtilesize>0)
                            dynamic_cast<OSG::PipelineComposer *>(icPtr)->setTileSize(subtilesize);
                        dynamic_cast<OSG::PipelineComposer *>(icPtr)->setPipelined(pipelinedBufferRead);
                    }
                    if(dynamic_cast<OSG::BinarySwapComposer *>(icPtr) != NULL)
                    {
                        if(subtilesize>0)
                            dynamic_cast<OSG::BinarySwapComposer *>(icPtr)->setTileSize(subtilesize);
                    }
                    icPtr->setStatistics(info);
//                        icPtr->setShort(false);
                    sortlast->setComposer(icPtr);
                }
            }
            clusterWindow=sortlast;
            break;
#ifdef FRAMEINTERLEAVE
        case 'I':
            frameinterleave=OSG::FrameInterleaveWindow::create();
            clusterWindow=frameinterleave;
            if(compose)
                frameinterleave->setCompose(true);
            else
                frameinterleave->setCompose(false);
            break;
#endif
        case 'P':
            sortfirst=OSG::SortFirstWindow::create();
            sortfirst->setCompose(false);
            clusterWindow=sortfirst;
            break;
    }
    
    if(!autostart.empty())
        clusterWindow->editMFAutostart()->push_back(autostart);
    
    for(i=0 ; i<int(servers.size()) ; ++i)
        clusterWindow->editMFServers()->push_back(servers[i]);
    if(cols < 0)
        cols = clusterWindow->getMFServers()->size32() / rows;
    switch(type)
    {
        case 'M': 
            multidisplay->setHServers(cols);
            multidisplay->setVServers(rows);
            break;
        case 'X': 
            balancedmultidisplay->setHServers(cols);
            balancedmultidisplay->setVServers(rows);
//                    balancedmultidisplay->setShowBalancing(true);
//            balancedmultidisplay->setShowBalancing(info);
            break;
    }
#ifdef FRAMEINTERLEAVE
    clusterWindow->setInterleave(interleave);
#endif
        
    // create client window
    clientWindow=OSG::GLUTWindow::create();
//        glutReshapeWindow(800,600);
    glutReshapeWindow(winwidth,winheight);
    clientWindow->setGlutId(winid);
    clientWindow->init();
    
    // init scene graph
    init(filenames);
    
    // init client
    clusterWindow->setConnectionType(connectionType);
    // needs to be called before init()!
    clusterWindow->setConnectionParams(connectionParameters);
    if(clientRendering)
    {
        clusterWindow->setClientWindow(clientWindow);
    }
    clusterWindow->setConnectionDestination(connectionDestination);
    clusterWindow->setConnectionInterface(connectionInterface);
    clusterWindow->init();
    if(serverx > 0)
        clusterWindow->resize(serverx,servery);
    else
        clusterWindow->resize(winwidth,winheight);
    clientWindow->resize(winwidth,winheight);

//    OSG::FieldContainerFactory::the()->dump();

    OSG::commitChanges();

    glutMainLoop();

    return 0;
}
int main(int argc, char **argv)
{
    OSG::osgInit(argc,argv);
    
    if(argc > 1 && !strcmp(argv[1],"-s"))
    {
        show = false;
        argv++;
        argc--;
    }
    
    if(argc > 1 && !strcmp(argv[1],"-d"))
    {
        debug = true;
        argv++;
        argc--;
    }

    
    if(argc > 1)
    {
        scene = OSG::Node::create();
        OSG::GroupUnrecPtr g = OSG::Group::create();
        
        scene->setCore(g);
        
        for(OSG::UInt16 i = 1; i < argc; ++i)
            scene->addChild(OSG::SceneFileHandler::the()->read(argv[i]));
    }
    else
    {
        scene = OSG::makeTorus(.5, 3, 16, 16);
    }

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

    glutInitWindowSize(1024, 768);
    mainwinid = glutCreateWindow("OpenSG");
    
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutIdleFunc(idle);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutKeyboardFunc(keyboard);

    OSG::GLUTWindowUnrecPtr mainwin=OSG::GLUTWindow::create();
    mainwin->setGlutId(mainwinid);
    mainwin->init();
    
    // create the SimpleSceneManager helper
    mgr = OSG::SimpleSceneManager::create();

    // create the window and initial camera/viewport
    mgr->setWindow(mainwin);
    // tell the manager what to manage
    mgr->setRoot  (scene);

    OSG::commitChanges();

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

    mgr->setUseTraversalAction(true);

    tact      = OSG::RenderAction::create();
#ifdef OSG_OLD_RENDER_ACTION
    act       = OSG::RenderAction::create();
#endif
    debugact  = OSG::RenderAction::create();
    tact->setOcclusionCulling(true);


    // Open the debug window
    if(debug)
    {
        OSG::traverse(scene, initMask);

        glutInitWindowSize(800, 400);
        debugwinid = glutCreateWindow("OpenSG Occlusion Debugging");

        glutReshapeFunc(reshape);
        glutDisplayFunc(display);
        glutIdleFunc(display);
        glutKeyboardFunc(keyboard);

        debugwin=OSG::GLUTWindow::create();
        debugwin->setGlutId(debugwinid);
        debugwin->init();       
        
        OSG::ViewportUnrecPtr vp = mainwin->getPort(0);
        
        OSG::ViewportUnrecPtr newvp = OSG::Viewport::create();        
        newvp->setLeft(0);
        newvp->setRight(0.5);
        newvp->setBottom(0);
        newvp->setTop(1);
        newvp->setRoot(vp->getRoot());
        newvp->setCamera(vp->getCamera());
        newvp->setBackground(vp->getBackground());
        newvp->setTravMask(0x1);
        debugwin->addPort(newvp);
        
        newvp = OSG::Viewport::create();        
        newvp->setLeft(0.5);
        newvp->setRight(1);
        newvp->setBottom(0);
        newvp->setTop(1);
        newvp->setRoot(vp->getRoot());
        newvp->setCamera(vp->getCamera());
        newvp->setBackground(vp->getBackground());
        newvp->setTravMask(0x2);
        debugwin->addPort(newvp);
        
        tact->setOcclusionCullingDebug(true);
        tact->setOcclusionDebugMasks(0x1, 0x2, 0x4);
    }

    // add the statistics forground
    
    statfg = OSG::SimpleStatisticsForeground::create();
    
    statfg->setSize(25);
    statfg->setColor(OSG::Color4f(0,1,0,0.7f));

    statfg->addElement(OSG::RenderAction::statDrawTime, 
                       "Draw FPS: %r.3f");
    statfg->addElement(OSG::RenderAction::statNMatrices, 
                       "Matrix Changes: %d");
    statfg->addElement(OSG::RenderAction::statNStates, 
                       "State Changes: %d");
                       
    statfg->addElement(OSG::RenderPartition::statCullTestedNodes, 
                       "Cull-tested Nodes: %d");
    statfg->addElement(OSG::RenderPartition::statCulledNodes, 
                       "Culled Nodes: %d");

    statfg->addElement(OSG::OcclusionCullingTreeBuilder::statNOccNodes, 
                       "Nodes in DrawTree: %d");
    statfg->addElement(OSG::OcclusionCullingTreeBuilder::statNOccTests, 
                       "Occ Tests: %d");
    statfg->addElement(OSG::OcclusionCullingTreeBuilder::statNOccInvisible, 
                       "Invisible Nodes: %d");
    statfg->addElement(OSG::OcclusionCullingTreeBuilder::statNOccSuccessTestPer, 
                       "OCC Success rate: %per%%");
    statfg->addElement(OSG::OcclusionCullingTreeBuilder::statNOccTriangles, 
                       "Triangles culled: %d");
   
    collector = statfg->getCollector();

    tact->setStatCollector(collector);
#ifdef OSG_OLD_RENDER_ACTION
    act ->setStatCollector(collector);
#endif

    mgr->setAction(tact);
#ifdef OSG_OLD_RENDER_ACTION
    mgr->setAction( act);
#endif

    //tact->setOcclusionCullingMinimumFeatureSize(15);
    //tact->setOcclusionCullingVisibilityThreshold(15);
    //tact->setScreenLODCoverageThreshold(0.005);
    
    if(show)
    {
        mainwin->getPort(0)->addForeground(statfg);
    }

#ifdef OSG_WITH_NVPERFSDK
    NVPMRESULT status;

    status = NVPMInit();
    if (status != NVPM_OK) {
        FFATAL(("NVPerfSDK failed to initialize - no GPU data will be available"));
    }
    else
    {
        nvDataProvider->add("gpu_idle");
        nvDataProvider->add("pixel_shader_busy");
        nvDataProvider->add("vertex_shader_busy");
        nvDataProvider->add("shader_waits_for_texture");
        if (!nvDataProvider->add("OGL FPS")) 
            FLOG(("nvDataProvider::add: 'OGL FPS' failed!\n"));
        
        statfg->addElement(GPUIdleStat);
        statfg->addElement(PSBusyStat);
        statfg->addElement(VSBusyStat);
        statfg->addElement(TextureWaitStat);
        statfg->addElement(OGLFPSStat);        
    }
#endif
    
    // GLUT main loop
    glutMainLoop();

    return 0;
}
int main(int argc, char *argv[])
{
    // Init the OpenSG subsystem
    OSG::osgInit(argc, argv);

    {
        // We create a GLUT Window (that is almost the same for most applications)
        int winid = setupGLUT(&argc, argv);
        OSG::GLUTWindowRecPtr gwin = OSG::GLUTWindow::create();
        gwin->setGlutId(winid);
        gwin->init();
    
        // Create the face
        std::string family = "SANS";
        OSG::TextFace::Style style = OSG::TextFace::STYLE_PLAIN;
        OSG::UInt32 size = 32;
        OSG::TextPixmapFaceRefPtr face = 
            OSG::TextPixmapFace::create(family, style, size);
        if (face == 0)
        {
            std::cerr << "ERROR: Cannot create face object!" << std::endl;
            return -1;
        }
    
        // Lay out one single line of text
        std::string text = "Hello World!"; // Use UTF-8 encoding!
        OSG::TextLayoutParam layoutParam;
        layoutParam.horizontal = true;
        layoutParam.leftToRight = true;
        layoutParam.topToBottom = true;
        layoutParam.majorAlignment = OSG::TextLayoutParam::ALIGN_FIRST;
        layoutParam.minorAlignment = OSG::TextLayoutParam::ALIGN_FIRST;
        layoutParam.spacing = 1.f;
        layoutParam.length.push_back(0.f);
        layoutParam.maxExtend = 0.f;
        OSG::TextLayoutResult layoutResult;
        face->layout(text, layoutParam, layoutResult);
    
        // Render the text into an OpenSG image
        OSG::Vec2f offset;
        OSG::UInt32 border = 1;
        OSG::ImageRecPtr imagePtr = face->makeImage(layoutResult, offset, border);
        
        // Create the geometry which we will assign the texture to
        OSG::Real32 width = imagePtr->getWidth();
        OSG::Real32 height = imagePtr->getHeight();
        OSG::NodeRecPtr plane = OSG::makePlane(width, height, 1, 1);
    
        // Create the texture that will hold the image
        OSG::SimpleTexturedMaterialRecPtr tex = 
            OSG::SimpleTexturedMaterial::create();
        tex->setImage(imagePtr);
        tex->setEnvMode(GL_MODULATE);
        tex->setDiffuse(OSG::Color3f(1, 0, 0));
    
        // Assign the texture to the geometry
        OSG::GeometryRecPtr geo =
            dynamic_cast<OSG::Geometry *>(plane->getCore());
        geo->setMaterial(tex);
    
        // Transform the geometry so that the origin of the text is at
        // the origin of the world coordinate system
        OSG::NodeRecPtr scene = OSG::Node::create();
        OSG::TransformRecPtr transformPtr = OSG::Transform::create();
        OSG::Matrix m;
        m.setTranslate(offset.x() + width / 2, offset.y() - height / 2, 0);
        transformPtr->setMatrix(m);
        
        scene->setCore(transformPtr);
        scene->addChild(plane);
        
        // Create and setup the SSM
        mgr = new OSG::SimpleSceneManager;
        mgr->setWindow(gwin);
        mgr->setRoot(scene);
    
        // Create a blue background
        OSG::SolidBackgroundRecPtr bg = OSG::SolidBackground::create();
        bg->setColor(OSG::Color3f(0.1, 0.1, 0.5));
        
        gwin->getPort(0)->setBackground(bg);
        
        mgr->showAll();
        
        OSG::commitChanges();
    }

    // Give Control to the GLUT Main Loop
    glutMainLoop();

    return 0;
}
// redraw the window
void display(void)
{   
    if(glutGetWindow() == mainwinid)
    {
#ifdef OSG_WITH_NVPERFSDK
        if(nvDataProvider->nCounters())
        {
            nvDataProvider->sample();

            OSG::Char8 str[40];
            
            for(int i = 0; nvStatElems[i] != NULL; ++i)
            {
                if(collector != NULL)
                {
                    sprintf(str, "%s: %f", nvStatElems[i]->getDescription().c_str(),
                            nvDataProvider->value(i)); 

                    OSG::StatStringElem *e = dynamic_cast<OSG::StatStringElem*>(
                        collector->getElem(*nvStatElems[i]));  

                    e->set(str);
                }
            }
        }
        
        if(runExperiment)
        {
            int nCount;
            
            const char *expCounters[] = { 
                "2D Bottleneck", "2D SOL", 
                "IDX Bottleneck", "IDX SOL", 
                "GEOM Bottleneck", "GEOM SOL", 
                "ZCULL Bottleneck", "ZCULL SOL", 
                "TEX Bottleneck", "TEX SOL", 
                "ROP Bottleneck", "ROP SOL", 
                "SHD Bottleneck", "SHD SOL", 
                "FB Bottleneck", "FB SOL", 
                "GPU Bottleneck", // Needs to be last 
                NULL };
            
            for(int i = 0; expCounters[i] != NULL; ++i)
            {
                NVPMAddCounterByName(const_cast<char *>(expCounters[i]));
            }
            
            NVPMBeginExperiment(&nCount);
            
            FLOG(("NVPerfKitSDK: Running %d passes\n", nCount));
            
            for(int i = 0; i < nCount; i++)
            {
                NVPMBeginPass(i);
                mgr->redraw();
                NVPMEndPass(i);
            }
            NVPMEndExperiment();
            
            UINT64 value, cycles;
            
            for(int i = 0; expCounters[i] != NULL; ++i)
            {
                NVPMGetCounterValueByName(const_cast<char *>(expCounters[i]), 0, &value, &cycles);
                FLOG(("%s: %lld value, %lld cycles (%.4f%%)\n", 
                        expCounters[i], value, cycles, value * 100. / cycles));
            }
            
            char buffer[1000] = "";
            
            NVPMGetGPUBottleneckName(value, buffer);

            FLOG(("GPU Bottleneck: '%s'\n", buffer));

            for(int i = 0; expCounters[i] != NULL; ++i)
            {
                //NVPMRemoveCounterByName(expCounters[i]);               
            }
            
            runExperiment = false;
        }
#endif
        mgr->redraw();
    }
    else if(glutGetWindow() == debugwinid)
    {
        // Use RenderAction to prevent new occlusion culling on debug output
        debugwin->render(debugact);
    }
}
Example #19
0
int main(int argc,char **argv)
{
    const char    *name          ="ClusterServer";
    const char    *connectionType="StreamSock";
//     const char    *connectionType="Multicast";
    bool           fullscreen     =true;
    std::string    address        ="";
    int            width=-1,height=300,x=0,y=0;
    bool           doStereo=false;
    char           *str;

    for(int i = 1 ; i < argc ; ++i)
    {
        if(argv[i][0] == '-')
        {
            switch(argv[i][1])
            {
                case 'm':
                    connectionType="Multicast";
                    break;
                case 's':
                    doStereo=true;
                    break;
                case 'w':
                    fullscreen=false;
                    break;
                case 'e':
                    exitOnError=true;
                    break;
                case 'a':
                    address=&(argv[i][2]);
                    break;
                case 'g':
                    if(argv[i][2] != '\0')
                        str=argv[i]+2;
                    else
                        str=argv[++i];
                    if(sscanf(str,"%d,%d,%d,%d",
                              &width,&height,&x,&y)!=4)
                    {
                        SWARNING << "Wrong args in -g. Use -gw,h,x,y" 
                                 << std::endl;
                        cleanup();
                        exit(0);
                    }
                    break;
                case 'p':
                    if(argv[i][2] != '\0')
                        servicePort=atoi(argv[i]+2);
                    else
                        servicePort=atoi(argv[++i]);
                    break;
                case 'j':
                    if(argv[i][2] != '\0')
                        serviceGroup=argv[i]+2;
                    else
                        serviceGroup=argv[++i];
                    break;
                case 'h':
                    std::cout << argv[0] 
                              << "-m "
                              << "-s "
                              << "-w "
                              << "-e "
                              << "-g w,h,x,y "
                              << "-a Address "
                              << "-j group "
                              << "-p servicePort "
                              << std::endl;
                    std::cout << "-m         use multicast" << std::endl;
                    std::cout << "-s         enable stereo" << std::endl;
                    std::cout << "-w         no fullscreen" << std::endl;
                    std::cout << "-e         exit after closed connection" 
                              << std::endl;
                    std::cout << "-g         geometry" << std::endl;
                    std::cout << "-a Address Server network address"
                              << std::endl;
                    std::cout << "-m Address wait for requests on "
                              << "multicast group" << std::endl;
                    std::cout << "-p port    wait for requests on port"
                              << std::endl;
                    return 0;
            }
        }
        else
        {
            name=argv[i];
        }
    }

    try
    {
        OSG::osgInit            (argc, argv);
        OSG::ClusterServer::init(argc, argv);

        glutInit(&argc, argv);

        if(doStereo)
            glutInitDisplayMode( GLUT_STEREO | 
                                 GLUT_RGB | 
                                 GLUT_DEPTH | 
                                 GLUT_DOUBLE);
        else
            glutInitDisplayMode( GLUT_RGB | 
                                 GLUT_DEPTH | 
                                 GLUT_DOUBLE);
        glutInitWindowPosition(x,y);
        if(width>0)
            glutInitWindowSize(width,height);
        winid = glutCreateWindow("OpenSG Cluster Client");
        if(fullscreen)
            glutFullScreen();
        /*
          else
          glutReshapeWindow(300,300);
        */
        if(width>0)
            glutReshapeWindow(width,height);
        glutPositionWindow(x, y);

        glutPopWindow();
        glutDisplayFunc(display);       
        glutIdleFunc(display);       
        glutKeyboardFunc(key);
        glutReshapeFunc(reshape);       
        glutSetWindowTitle(name);
        // switch off cursor
        glutSetCursor(GLUT_CURSOR_NONE);
        glEnable( GL_LIGHTING );
        glEnable( GL_LIGHT0 );
        glEnable( GL_DEPTH_TEST );
        glEnable( GL_NORMALIZE );
        ract = OSG::RenderAction::create();
//        ract->setFrustumCulling(false);
        window     = OSG::GLUTWindow::create();
        window->setGlutId(winid);
        window->init();
        server     = new OSG::ClusterServer(window,
                                            name,
                                            connectionType,
                                            address,
                                            servicePort,
                                            serviceGroup);
        server->start();
        running=true;
        glutMainLoop();
    } 
    catch(OSG_STDEXCEPTION_NAMESPACE::exception &e)
    {
        SLOG << e.what() << std::endl;
        delete server;
        cleanup();
        OSG::osgExit(); 
    }
    return 0;
}
/*! Simple show text function
 */
void displayInfo(int x, int y)
{
  int len, i;
#ifdef WIN32
#ifdef OSG_WIN32_CL
  void *font = (void *) 2;
#else
  void *font = 2;
#endif
#else
#ifdef OSG_DEBUG_OLD_C_CASTS
  void *font = glutBitmap9By15;
#else
  void *font = GLUT_BITMAP_9_BY_15;
#endif
#endif

  char text[1024];
  sprintf(text,
          "FPS:        %12.1f\n"
          "Positions:  %12u\n"
          "Triangles:  %12u\n"
          "Geometries: %12u",
          1.0/frame_time,
          sum_positions,
          sum_triangles,
          sum_geometries);

  glPushAttrib(GL_ALL_ATTRIB_BITS);
  glDisable(GL_LIGHTING);
  glEnable(GL_COLOR_MATERIAL);
  glPushMatrix();
  glLoadIdentity();
  glMatrixMode(GL_PROJECTION);
  glPushMatrix();
  glLoadIdentity();
  gluOrtho2D(0,clientWindow->getWidth(),0,clientWindow->getHeight());
  glDisable(GL_DEPTH_TEST);  
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);

  int x1=x-5;
  int x2=x1+24*9+10;
  int y1=y+14;
  int y2=y1-4*20;
  glBegin(GL_QUADS);
  glColor4f(.1f, .1f, .7f, .5f);
  glVertex2i(x1,y1);
  glVertex2i(x1,y2);
  glVertex2i(x2,y2);
  glVertex2i(x2,y1);
  glEnd();
  glBegin(GL_LINE_LOOP);
  glColor3f(1.0, 1.0, 0.0);
  glVertex2i(x1,y1);
  glVertex2i(x1,y2);
  glVertex2i(x2,y2);
  glVertex2i(x2,y1);
  glEnd();

  glColor3f(1.0, 1.0, 0.0);
  glRasterPos2f(x, y);
  len = int(strlen(text));
  for (i = 0; i < len; i++) {
      if(text[i] == '\n')
      {
          y-=20;
          glRasterPos2f(x, y);
      }
      else
          glutBitmapCharacter(font, text[i]);
  }
  glPopMatrix();
  glMatrixMode(GL_MODELVIEW);
  glPopMatrix();
  glPopAttrib();
}