void display(void)
{
#if 0
    Matrix m1, m2, m3;
    Quaternion q1;

    tball.getRotation().getValue(m3);

    q1.setValue(m3);

    m1.setRotate(q1);
    
    m2.setTranslate( tball.getPosition() );
    
    m1.mult( m2 );

    if(move_obj == true)
    {
        scene_trans->editSFMatrix()->setValue( m1 );
    }
    else
    {
        cam_trans->editSFMatrix()->setValue( m1 );
    }
#endif

    cam_trans->editSFMatrix()->setValue(tball.getFullTrackballMatrix());

#if 0
    fprintf(stderr, "%f %f %f\n", 
            cam_trans->getMatrix()[3][0],
            cam_trans->getMatrix()[3][1],
            cam_trans->getMatrix()[3][2]);
#endif

    OSG::Real32 t = glutGet(GLUT_ELAPSED_TIME);

    for(OSG::UInt32 i = 0; i < 6; ++i)
    {
        if(pAnimTrs[i] != NULL)
        {
            pAnimTrs[i]->editRotation().setValueAsAxisDeg(
                0.f, 1.f, 0.f, 
                t / 50.f);
        }
    }

    OSG::commitChanges();

//    fprintf(stderr, "Frame start\n");
//    fprintf(stderr, "============================================\n");
    

    win->render(rentravact);
}
void display(void)
{
    OSG::Real32 time = glutGet(GLUT_ELAPSED_TIME );

    //create the Quaternion the describes the rotation of
    //the planet around the sun
    OSG::Quaternion planetRot = OSG::Quaternion(OSG::Vec3f(0,1,0),
                                time/float(1000));

    //now the rotation of the moon around the planet
    //the division by 12 speeds up the rotation by 12 compared to the
    //planet rotation
    OSG::Quaternion moonRot = OSG::Quaternion(OSG::Vec3f(0,1,0),
                              time/float(1000/12));

    //generate the Matrices
    OSG::Matrix p,m,t1,r1,t2,r2;

    t1.setTransform(OSG::Vec3f(20,0,0));
    r1.setTransform(planetRot);
    r1.mult(t1);
    p.setValue(r1);

    t2.setTransform(OSG::Vec3f(8,0,0));
    r2.setTransform(moonRot);
    r2.mult(t2);
    r1.mult(r2);
    m.setValue(r1);

    planetTransform->setMatrix(p);
    moonTransform  ->setMatrix(m);

    mgr->redraw();
}
void display(void)
{
    OSG::Matrix m1;
    
    m1 = tball.getFullTrackballMatrix();

    cam_trans->editSFMatrix()->setValue(m1);

    OSG::commitChanges();

    win->render(rentravact);
}
void MyOSGQGLWidget::paintGL(void)
{
    OSG::Matrix m1, m2, m3;
    OSG::Quaternion q1;

    tball.getRotation().getValue(m3);
    q1.setValue(m3);
    m1.setRotate(q1);
    m2.setTranslate( tball.getPosition() );
    m1.mult( m2 );
    cam_trans->setMatrix( m1 );

    OSG::commitChanges();

    osgWin->render(ract);   // draw the viewports     
}
void redraw ( void )
{
    OSG::Matrix m1, m2, m3;
    OSG::Quaternion q1;

    tball.getRotation().getValue(m3);
    q1.setValue(m3);
    m1.setRotate(q1);
    m2.setTranslate( tball.getPosition() );
    m1.mult( m2 );
    cam_trans->editSFMatrix()->setValue( m1 );

    OSG::Thread::getCurrentChangeList()->commitChanges();

    win->render(ract);
}
OSG::NodeRecPtr createScenegraph(void)
{
    //create sun, planet & moon geometry

    OSG::GeometryRecPtr sun    = OSG::makeSphereGeo(3, 6);
    OSG::NodeRecPtr     planet = OSG::makeSphere   (3, 3);
    OSG::NodeRecPtr     moon   = OSG::makeSphere   (2, 1);

    //the root node will be the sun
    OSG::NodeRecPtr root = OSG::Node::create();
    root->setCore(sun);

    OSG::NodeRecPtr planetTransformNode = OSG::Node::create();
    OSG::NodeRecPtr moonTransformNode   = OSG::Node::create();

    // these were declared globally
    planetTransform = OSG::Transform::create();
    moonTransform   = OSG::Transform::create();

    // Now we need to fill it with live
    // We want to have the planet some distance away from the sun,
    // but initial with no rotation. The same aplies to the moon
    OSG::Matrix m,n;

    m.setIdentity();
    n.setIdentity();

    m.setTranslate(20, 0, 0);
    n.setTranslate( 8, 0, 0);

    planetTransform->setMatrix(m);
    moonTransform  ->setMatrix(n);

    //Insert the cores into the apropiate nodes and add the geometry
    planetTransformNode->setCore (planetTransform);
    planetTransformNode->addChild(planet         );

    moonTransformNode->setCore (moonTransform);
    moonTransformNode->addChild(moon         );

    //add the planet to the sun
    root->addChild(planetTransformNode);
    root->addChild(moonTransformNode  );

    //now we are done
    return OSG::NodeTransitPtr(root);
}
void display(void)
{
    OSG::Matrix m1, m2, m3;
    OSG::Quaternion q1;

    tball.getRotation().getValue(m3);

    q1.setValue(m3);

    m1.setRotate(q1);
    
//    std::cout << "TBROT" << std::endl << tball.getRotation() << endl;
//    std::cout << "M3" << std::endl << m3 << std::endl;
//    std::cout << "Q1" << std::endl << q1 << std::endl;
//    std::cout << "M1" << std::endl << m1 << std::endl;

//  m1.setRotate( tball.getRotation() );
    m2.setTranslate( tball.getPosition() );
    
//std::cout << "Pos: " << tball.getPosition() << ", Rot: " << tball.getRotation() << std::endl;

//    std::cout << tball.getRotation() << std::endl;

    m1.mult( m2 );

//    std::cerr << m1 << std::endl;
    
    m1 = tball.getFullTrackballMatrix();

    if(move_obj == true)
    {
        scene_trans->editSFMatrix()->setValue( m1 );
    }
    else
    {
        cam_trans->editSFMatrix()->setValue( m1 );
    }

    OSG::commitChangesAndClear();

    win->render(rentravact);

    if(dumpImg == true)
    {
        vpFBO->setTravMask(oldTravMask);

        pTexBuffer                   ->setReadBack               (false);
        vpFBO->getFrameBufferObject()->setPostProcessOnDeactivate(false);

        pImg->write("/tmp/test.png");

        dumpImg = false;
    }

    if(dumpImg_RB == true)
    {
        pRenBuffer->getImage()->write("/tmp/test1.png");

        dumpImg_RB = false;

        win->subPortByObj(vpFBO_RB);

        vpFBO_RB   = NULL;
        pRenBuffer = NULL;

        win->runFrameExit();

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


//    win->render(renact);

//    std::cerr << "------------- AR START --------------" << std::endl;

//    Thread::getCurrentChangeList()->dump();
}
int doMain (int argc, char **argv)
{
    OSG::osgInit(argc,argv);
    
    // GLUT init

    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
    glutInitWindowSize(800, 800);
    

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

    // OSG

    OSG::SceneFileHandler::the()->print();

    // create the graph

    // beacon for camera and light  
    OSG::NodeUnrecPtr  b1n = OSG::Node::create();
    OSG::GroupUnrecPtr b1  = OSG::Group::create();

    fprintf(stderr, "Create b1n %p %d %d \n",
            b1n.get(),
            b1n->getRefCount(),
            b1n->getWeakRefCount());

    b1n->setCore( b1 );

    // transformation
    OSG::NodeUnrecPtr      t1n = OSG::Node::create();
    OSG::TransformUnrecPtr t1  = OSG::Transform::create();

    t1n->setCore (t1 );
    t1n->addChild(b1n);

    fprintf(stderr, "Create t1n %p %d %d \n",
            t1n.get(),
            t1n->getRefCount(),
            t1n->getWeakRefCount());

    cam_trans = t1;

    // light
    
    OSG::NodeUnrecPtr             dlight = OSG::Node::create();
    OSG::DirectionalLightUnrecPtr dl     = OSG::DirectionalLight::create();

    {
        dlight->setCore(dl);
        
        dl->setAmbient( .3f, .3f, .3f, 1 );
        dl->setDiffuse( .8f, .8f, .8f, .8f );
        dl->setDirection(0,0,1);
        dl->setBeacon( b1n);
    }

    fprintf(stderr, "Create dlight %p %d %d \n",
            dlight.get(),
            dlight->getRefCount(),
            dlight->getWeakRefCount());

    hdrroot = OSG::Node::create();
    
    hdrroot->editVolume().setInfinite();
    hdrroot->editVolume().setStatic  ();

    hdrroot->setCore(OSG::Group::create());

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

    OSG::GroupUnrecPtr gr1 = OSG::Group::create();

    root->setCore(gr1);

    
    hdrroot->addChild(root);

    root->addChild(t1n   );
    root->addChild(dlight);

    fprintf(stderr, "Create root %p %d %d \n",
            root.get(),
            root->getRefCount(),
            root->getWeakRefCount());

    // Load the file

    OSG::NodeUnrecPtr file = NULL;
    
    if(argc > 1)
    {
        file = OSG::SceneFileHandler::the()->read(argv[1], NULL);
    }

    if(file == NULL)
    {
        std::cerr << "Couldn't load file, ignoring" << std::endl;

//        file = makeBox(2.f, 2.f, 2.f, 2, 2, 2);
        file = OSG::makeSphere(4, 2.0);
    }

    OSG::NodeUnrecPtr pCubeRoot            = OSG::Node::create();
    OSG::CubeMapGeneratorUnrecPtr pCubeGen = OSG::CubeMapGenerator::create();

    pCubeRoot->addChild(file);
    pCubeRoot->setCore(pCubeGen);
//    pCubeRoot->setCore(Group::create());

    OSG::NodeUnrecPtr         pCubeSceneRoot = OSG::Node::create();
    OSG::VisitSubTreeUnrecPtr pCubeVisit     = OSG::VisitSubTree::create();

    pCubeSceneRoot->setCore(pCubeVisit);
    pCubeVisit->setSubTreeRoot(root);

    pCubeGen->setRoot         (pCubeSceneRoot);
    pCubeGen->setTextureFormat(GL_RGB32F_ARB );
    pCubeGen->setSize         (512, 
                               512           );
    pCubeGen->setTexUnit      (3);

    // Cubemap Background
    OSG::SolidBackgroundUnrecPtr cubeBkgnd = OSG::SolidBackground::create();
    {
        cubeBkgnd->setColor(OSG::Color3f(0.5f, 0.3f, 0.3f));
    }

    pCubeGen->setBackground(cubeBkgnd);


    OSG::NodeUnrecPtr pAnimRoot = setupAnim();

            scene_trans = OSG::Transform::create();
    OSG::NodeUnrecPtr sceneTrN    = OSG::Node::create();

    scene_trans->editMatrix()[3][2] = -50.f;

    sceneTrN->setCore (scene_trans);
    sceneTrN->addChild(pCubeRoot  );
    sceneTrN->addChild(pAnimRoot  );

    OSG::Thread::getCurrentChangeList()->commitChanges();

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


    dlight->addChild(sceneTrN);

    // Camera
    
    cam = OSG::PerspectiveCamera::create();
    {
        cam->setBeacon( b1n );
        cam->setFov( OSG::osgDegree2Rad( 90 ) );
        cam->setNear( 0.1f );
        cam->setFar( 100000 );
    }

    // Background
    OSG::SolidBackgroundUnrecPtr bkgnd = OSG::SolidBackground::create();
    {
        bkgnd->setColor(OSG::Color3f(0.3f, 0.3f, 0.3f));
    }

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


    // Window
    OSG::GLUTWindowUnrecPtr gwin;

    GLint glvp[4];

    glGetIntegerv(GL_VIEWPORT, glvp);

    gwin = OSG::GLUTWindow::create();
    {
        gwin->setGlutId(winid);
        gwin->setSize( glvp[2], glvp[3] );
        
        win = gwin;

        win->addPort( vp );

        win->init();
    }

    // Action
    rentravact = OSG::RenderAction::create();

    rentravact->setVolumeDrawing(true);
//    rentravact->setFrustumCulling(false);

    // tball
    OSG::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;

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

    fprintf(stderr, "Startpos : %f %f %f\n", pos[0], pos[1], pos[2]);

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

    fprintf(stderr, "Create b1n %p %d %d \n",
            b1n.get(),
            b1n->getRefCount(),
            b1n->getWeakRefCount());

    fprintf(stderr, "Create t1n %p %d %d \n",
            t1n.get(),
            t1n->getRefCount(),
            t1n->getWeakRefCount());

    fprintf(stderr, "Create dlight %p %d %d \n",
            dlight.get(),
            dlight->getRefCount(),
            dlight->getWeakRefCount());

    fprintf(stderr, "Create hdrroot %p %d %d \n",
            hdrroot.get(),
            hdrroot->getRefCount(),
            hdrroot->getWeakRefCount());

    fprintf(stderr, "Create root %p %d %d \n",
            root.get(),
            root->getRefCount(),
            root->getWeakRefCount());

    return 0;
}
OSG::NodeTransitPtr createScenegraph(void)
{
    // At first we load all needed models from file
    OSG::NodeRecPtr w_high   = 
        OSG::SceneFileHandler::the()->read("Data/woman_high.wrl");

    OSG::NodeRecPtr w_medium = 
        OSG::SceneFileHandler::the()->read("Data/woman_medium.wrl");

    OSG::NodeRecPtr w_low    = 
        OSG::SceneFileHandler::the()->read("Data/woman_low.wrl");
    
    // we check the result
    if((w_high == NULL) || (w_medium == NULL)|| (w_low == NULL))
    {
        std::cout << "It was not possible to load all needed models from file"
                << std::endl;
        return OSG::NodeTransitPtr();
    }
    
    // now the LOD core
    OSG::DistanceLODRecPtr lod = OSG::DistanceLOD::create();
    lod->editSFCenter()->setValue(OSG::Pnt3f(0,0,0));
    lod->editMFRange()->push_back(200);
    lod->editMFRange()->push_back(500);
    
    // the node containing the LOD core. The three models will be
    // added as its children
    OSG::NodeRecPtr lodNode = OSG::Node::create();
    lodNode->setCore(lod);
    lodNode->addChild(w_high);
    lodNode->addChild(w_medium);
    lodNode->addChild(w_low);
    
    // create the node with switch core ********************
    OSG::SwitchRecPtr sw = OSG::Switch::create();
    //Notice: the first choice is 0
    sw->setChoice(0);
    
    OSG::NodeRecPtr switchNode = OSG::Node::create();
    switchNode->setCore(sw);
    switchNode->addChild(lodNode);
    
    //end switch creation **********************************
    
    OSG::NodeRecPtr root = OSG::Node::create();
    root->setCore(OSG::Group::create());
    root->addChild(switchNode);
    
    // we know want to extract the mesh geometry out of the graph
    // it is sufficent to pass the model only as root for searching
    OSG::NodeRecPtr     womanGeometry = checkName(w_high);
    OSG::GeometryRecPtr geo = 
        dynamic_cast<OSG::Geometry *>(womanGeometry->getCore());
    
    //new node with "old" geometry core referenced
    OSG::NodeRecPtr woman = OSG::Node::create();
    woman->setCore(geo);
    
    //translate it a bit to see both women
    OSG::NodeRecPtr      womanTrans = OSG::Node     ::create();
    OSG::TransformRecPtr t          = OSG::Transform::create();
    OSG::Matrix m;
    m.setIdentity();
    m.setTranslate(OSG::Vec3f(0,0,200));
    t->setMatrix(m);
        
    womanTrans->setCore(t);
    womanTrans->addChild(woman);
    
    //add it to the root
    root->addChild(womanTrans);
    
    return OSG::NodeTransitPtr(root);
}
void updateScene(const std::string &filename, OSG::Image::PixelFormat compressTo = OSG::Image::OSG_INVALID_PF)
{
    // Try to create the new image
    OSG::ImageRecPtr imagePtr = 
        OSG::ImageFileHandler::the()->read(filename.c_str());

    if (imagePtr == NULL)
        return;

    if(compressTo != OSG::Image::OSG_INVALID_PF)
    {
        imagePtr->reformat(compressTo);
    }

    // Update information on the screen
    OSG::StatStringElem *statElem = 
        statfg->editCollector()->getElem(textureFormatDesc);

    switch (imagePtr->getPixelFormat())
    {
        case OSG::Image::OSG_A_PF:
            statElem->set("OSG_A_PF");
            break;
        case OSG::Image::OSG_I_PF:
            statElem->set("OSG_I_PF");
            break;
        case OSG::Image::OSG_L_PF:
            statElem->set("OSG_L_PF");
            break;
        case OSG::Image::OSG_LA_PF:
            statElem->set("OSG_LA_PF");
            break;
        case OSG::Image::OSG_RGB_PF:
            statElem->set("OSG_RGB_PF");
            break;
        case OSG::Image::OSG_RGBA_PF:
            statElem->set("OSG_RGBA_PF");
            break;
        case OSG::Image::OSG_BGR_PF:
            statElem->set("OSG_BGRA_PF");
            break;
        case OSG::Image::OSG_BGRA_PF:
            statElem->set("OSG_BGRA_PF");
            break;
        case OSG::Image::OSG_RGB_DXT1:
            statElem->set("OSG_RGB_DXT1");
            break;
        case OSG::Image::OSG_RGBA_DXT1:
            statElem->set("OSG_RGBA_DXT1");
            break;
        case OSG::Image::OSG_RGBA_DXT3:
            statElem->set("OSG_RGBA_DXT3");
            break;
        case OSG::Image::OSG_RGBA_DXT5:
            statElem->set("OSG_RGBA_DXT5");
            break;
        default:
            statElem->set("???");
            break;
    }
    statElem = statfg->editCollector()->getElem(textureDataTypeDesc);
    switch (imagePtr->getDataType())
    {
        case OSG::Image::OSG_UINT8_IMAGEDATA:
            statElem->set("OSG_UINT8_IMAGEDATA");
            break;
        case OSG::Image::OSG_UINT16_IMAGEDATA:
            statElem->set("OSG_UINT16_IMAGEDATA");
            break;
        case OSG::Image::OSG_UINT32_IMAGEDATA:
            statElem->set("OSG_UINT32_IMAGEDATA");
            break;
        case OSG::Image::OSG_FLOAT16_IMAGEDATA:
            statElem->set("OSG_FLOAT16_IMAGEDATA");
            break;
        case OSG::Image::OSG_FLOAT32_IMAGEDATA:
            statElem->set("OSG_FLOAT32_IMAGEDATA");
            break;
        case OSG::Image::OSG_INT16_IMAGEDATA:
            statElem->set("OSG_INT16_IMAGEDATA");
            break;
        case OSG::Image::OSG_INT32_IMAGEDATA:
            statElem->set("OSG_INT32_IMAGEDATA");
            break;
        default:
            statElem->set("???");
            break;
    }
    ostringstream os;
    os << imagePtr->getWidth() << 'x' << imagePtr->getHeight() << 'x' << imagePtr->getDepth();
    statfg->editCollector()->getElem(textureSizeDesc)->set(os.str());
    statfg->editCollector()->getElem(textureDimensionDesc)->set(imagePtr->getDimension());
    statfg->editCollector()->getElem(textureBPPDesc)->set(imagePtr->getBpp());
    statfg->editCollector()->getElem(textureMipMapCountDesc)->set(imagePtr->getMipMapCount());
    statfg->editCollector()->getElem(textureFrameCountDesc)->set(imagePtr->getFrameCount());

    // Put it all together into a Geometry NodeCore.
    OSG::GeometryRecPtr geo = OSG::makePlaneGeo(imagePtr->getWidth(), imagePtr->getHeight(), 1, 1);
    OSG::NodeRecPtr imageNode = OSG::Node::create();
    imageNode->setCore(geo);
    OSG::NodeRecPtr transNodePtr = OSG::Node::create();
    OSG::TransformRecPtr transPtr = OSG::Transform::create();
    OSG::Matrix transMatrix;
    transMatrix.setTranslate(0.f, 0.f, -1.f);
    transPtr->setMatrix(transMatrix);
    transNodePtr->setCore(transPtr);
    transNodePtr->addChild(imageNode);

    OSG::TextureObjChunkRecPtr texObjChunk = OSG::TextureObjChunk::create();
    texObjChunk->setImage(imagePtr);
    texObjChunk->setWrapS(GL_CLAMP);
    texObjChunk->setWrapT(GL_CLAMP);
    texObjChunk->setMagFilter(GL_NEAREST);
    texObjChunk->setMinFilter(GL_NEAREST);
    OSG::TextureEnvChunkRecPtr texEnvChunk = OSG::TextureEnvChunk::create();
    texEnvChunk->setEnvMode(GL_MODULATE);

    OSG::MaterialChunkRecPtr matChunk = OSG::MaterialChunk::create();
    matChunk->setAmbient(OSG::Color4f(1.f, 1.f, 1.f, 1.f));
    matChunk->setDiffuse(OSG::Color4f(1.f, 1.f, 1.f, 1.f));
    matChunk->setEmission(OSG::Color4f(0.f, 0.f, 0.f, 1.f));
    matChunk->setSpecular(OSG::Color4f(0.f, 0.f, 0.f, 1.f));
    matChunk->setShininess(0);

    OSG::ChunkMaterialRecPtr m = OSG::ChunkMaterial::create();
    m->addChunk(texObjChunk);
    m->addChunk(texEnvChunk);
    m->addChunk(matChunk);

    geo->setMaterial(m);

    scene->clearChildren();
    scene->addChild(transNodePtr);

    if(compressTo != OSG::Image::OSG_INVALID_PF)
    {
        OSG::SceneFileHandler::the()->write(scene->getChild(0), 
                                            "/tmp/comp.osb");
        OSG::SceneFileHandler::the()->write(scene->getChild(0), 
                                            "/tmp/comp.osg");
    }

}
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;
}
void key(unsigned char key, int /*x*/, int /*y*/)
{
	switch ( key )
	{
        case 'l':
        {
            loadAnim();
            break;
        }
        case 'c':
        {
            FILE *file=fopen(animName.c_str(),"w");
            fclose(file);
            animOri.clear();
            animPos.clear();
            frameCount = 0;
            animTime = 0;
            break;
        }
        case 's':
        {
            FILE *file=fopen(animName.c_str(),"a");
            OSG::Matrix m=cam_trans->getMatrix();
            OSG::Quaternion q(m);
            OSG::Real32 ax,ay,az,r;
            animPos.push_back(OSG::Vec3f(m[3][0],
                                         m[3][1],
                                         m[3][2]));
            animOri.push_back(q);
            q.getValueAsAxisRad(ax,ay,az,r);
            fprintf(file,"%f %f %f %f,%f %f %f\n",ax,ay,az,r,
                    m[3][0],
                    m[3][1],
                    m[3][2]);
            fclose(file);
            frameCount = 0;
            animTime = 0;
            break;
        }
        case 'S':
        {
            FILE *file=fopen((animName+".wrl").c_str(),"w");
            std::vector<OSG::Quaternion>::iterator qit;
            
            fprintf(file,"DEF OriInter OrientationInterpolator {\n\tkey [");
            for(size_t i = 0; i < animOri.size(); ++i)
            {               
                fprintf(file, "%f", i / OSG::Real32(animOri.size() - 1) );
                if(i < animOri.size() - 1)
                    fprintf(file,", ");
            }
            fprintf(file,"]\n\tkeyValue [");
            for(qit = animOri.begin(); qit != animOri.end(); ++qit)
            {
                OSG::Real32 ax,ay,az,r;
                (*qit).getValueAsAxisRad(ax,ay,az,r);
                
                fprintf(file, "%f %f %f %f", ax, ay, az, r );
                if(qit < animOri.end() - 1)
                    fprintf(file,", ");
            }
            fprintf(file,"]\n}\n\n");

            std::vector<OSG::Vec3f>::iterator vit;
            
            fprintf(file,"DEF PosInter PositionInterpolator {\n\tkey [");
            for(size_t i = 0; i < animPos.size(); ++i)
            {               
                fprintf(file, "%f", i / OSG::Real32(animPos.size() - 1) );
                if(i < animPos.size() - 1)
                    fprintf(file,", ");
            }
            fprintf(file,"]\n\tkeyValue [");
            for(vit = animPos.begin(); vit != animPos.end(); ++vit)
            {
                OSG::Vec3f v = *vit;
                
                fprintf(file, "%f %f %f, ", v[0], v[1], v[2] );
            }
            fprintf(file,"]\n}\n\n");

            fclose(file);
            break;
        }
        case 'j':
            if(sortfirst!=NULL)
            {
                sortfirst->setCompression("JPEG");
            }
            break;
        case 'r':
            if(sortfirst!=NULL)
            {
                sortfirst->setCompression("RLE");
            }
            break;
        case 'n':
            if(sortfirst!=NULL)
            {
                sortfirst->editCompression().erase();
            }
            break;
        case 'i':
            showInfo = !showInfo;
            break;
        case 'w':
            if(polygonChunk->getFrontMode() == GL_FILL)
                polygonChunk->setFrontMode(GL_LINE);
            else
                polygonChunk->setFrontMode(GL_FILL);

            if(polygonChunk->getBackMode() == GL_FILL)
                polygonChunk->setBackMode(GL_LINE);
            else
                polygonChunk->setBackMode(GL_FILL);
            break;
        case 'a':
            if(animate)
            {
                glutIdleFunc(NULL);       
                animate=false;
            }
            else
            {
                glutIdleFunc(display);       
                animate=true;
            }
            frameCount = 0;
            animTime = 0;
            break;
        case 'd':
            // remove tree
            while(root->getNChildren())
            {
                root->subChild(0u);
            }
            break;
        case '+':
            _dsFactor += 0.01f;
            if(_dsFactor > 1.0f)
                _dsFactor = 1.0f;
            setHEyeWallParameter(_dsFactor, _enablecc);
            break;
        case '-':
            _dsFactor -= 0.01f;
            if(_dsFactor <= 0.0f)
                _dsFactor = 0.01f;
            setHEyeWallParameter(_dsFactor, _enablecc);
            break;
        case 'f':
            if(_enablecc)
                _enablecc = false;
            else
                _enablecc = true;
            setHEyeWallParameter(_dsFactor, _enablecc);
            break;
        case 'B':
            if(bkgnd->getColor()[0] == 0.0)
                bkgnd->setColor( OSG::Color3f(1,1,1) );
            else
                bkgnd->setColor( OSG::Color3f(0,0,0) );
            break;
        case 27:	// should kill the clients here
            // exit
            cleanup();
            OSG::osgExit(); 
            exit(0);
	}
	
	glutPostRedisplay();
}
void display(void)
{
    OSG::Time t;

//    std::cout << glutGet(GLUT_WINDOW_WIDTH) << std::endl;

    t=-OSG::getSystemTime();

    if(animate && animPos.size()>1)
    {
        if(animLength>0)
            animTime = frameCount * (animPos.size())/float(animLength);

        OSG::UInt32 i=OSG::UInt32(animTime);
        OSG::Real32 a=animTime-i;

        OSG::Vec3f v;
        OSG::Quaternion q;
        if(i+1 < animPos.size())
        {
            v = animPos[i] + (animPos[i+1] - animPos[i]) * a; 
            q = OSG::Quaternion::slerp(animOri[i],animOri[i+1],a);
        }
        else
        {
            v = animPos[i];
            q = animOri[i];
        }
        cam_trans->editMatrix().setTranslate(v[0],v[1],v[2]);
        cam_trans->editMatrix().setRotate(q);
    }
    else
    {
        cam_trans->editSFMatrix()->setValue( tball.getFullTrackballMatrix() );
    }

    try
    {
        OSG::Thread::getCurrentChangeList()->commitChanges();
#if 0
        clusterWindow->activate();	
        clusterWindow->frameInit();	
        clusterWindow->renderAllViewports(ract);	
#endif
        clusterWindow->renderNoFinish(ract);
#if 0
        if(showInfo)
        {
            displayInfo(10,90);
/*
            char text[1024];
            sprintf(text,"FPS:        %12.1f",1.0/frame_time);
            showText(10,70,text);
            sprintf(text,"Positions:  %12d",sum_positions);
            showText(10,50,text);
            sprintf(text,"Triangles:  %12d",sum_triangles);
            showText(10,30,text);
            sprintf(text,"Geometries: %12d",sum_geometries);
            showText(10,10,text);
*/
        }
#endif
#if 0
        clusterWindow->swap();	
        clusterWindow->frameExit();	
#endif
        clusterWindow->frameFinish();
        // clear changelist from prototypes
        OSG::Thread::getCurrentChangeList()->clear();
	}
    catch(OSG_STDEXCEPTION_NAMESPACE::exception &e)
    {
        std::cout << e.what() << std::endl;
        cleanup();
        exit(0);
    }
    
    t+=OSG::getSystemTime();
    frame_time = t;

    if(animate && animPos.size()>1)
    {
        OSG::Vec3f v;

        printf("Frame %8.3f %8.5f %8.3f\n",
               animTime,
               t,1/t);

        frameCount++;
        if(frameCount == animLength)
        {
            animTime = 0;
            frameCount = 0;

            if(animLoops > 0)
            {
                animLoops--;
                if(!animLoops) 
                {
                    cleanup();
                    exit(0);
                }
            }
        }

    }
}