void ComplexSceneManager::frame(void)
{
#if 0
    setCurrTime(getSystemTime());
    
    if(osgAbs(_sfStartTime.getValue()) < 0.00001)
    {
        setStartTime(_sfCurrTime.getValue());
        
        setLastTime(0.f);
    }
    
    _sfCurrTime.getValue() -= _sfStartTime.getValue();

    if(_sfPaused.getValue() == false)
    {
        SFTime *pSFTimeStamp = editSFTimeStamp();

        if(_sfConstantTime.getValue() == true)
        {
            pSFTimeStamp->getValue() += _sfConstantTimeStep.getValue();

            if(pSFTimeStamp->getValue() < 0.)
                pSFTimeStamp->setValue(0.0);
        }
        else
        {
            pSFTimeStamp->getValue() += 
                (_sfCurrTime.getValue() - _sfLastTime.getValue()) * 
                _sfTimeScale.getValue();
            
            if(pSFTimeStamp->getValue() < 0.)
                pSFTimeStamp->setValue(0.0);
        }
    }
    
    setLastTime(_sfCurrTime.getValue());

    SystemTime = _sfTimeStamp.getValue();

    ++(editSFFrameCount()->getValue());

    if(_sfSensorTask.getValue() != NULL)
    {
        _sfSensorTask.getValue()->frame(_sfTimeStamp.getValue (), 
                                        _sfFrameCount.getValue());
    }
#endif

    if(_sfDumpFrameStart.getValue() == true)
    {
        fprintf(stderr, "=================================================\n");
        fprintf(stderr, "Render Frame\n");
        fprintf(stderr, "=================================================\n");
    }

    FrameHandler::the()->frame();

    SystemTime = FrameHandler::the()->getTimeStamp();

    commitChanges();

    if(_sfDrawManager.getValue() != NULL)
    {
        _sfDrawManager.getValue()->frame(FrameHandler::the()->getTimeStamp(), 
                                         FrameHandler::the()->getFrameCount());
    }
}
void PlaneMoveManipulator::onCreate(const PlaneMoveManipulator* source)
{
    // Skip direct parent, don't want the default geometry creation
    Transform::onCreate(source);

    SimpleMaterialUnrecPtr pMat = SimpleMaterial::create();
    pMat->setDiffuse(Color3f(.5, .5, .5));
    pMat->setLit    (false              );
    setMaterialX(pMat);

    pMat = SimpleMaterial::create();
    pMat->setDiffuse(Color3f(0, 1, 0));
    pMat->setLit    (false           );
    LineChunkUnrecPtr lc = LineChunk::create();
    lc->setWidth(3);
    pMat->addChunk(lc);
    setMaterialY(pMat);

    pMat = SimpleMaterial::create();
    pMat->setDiffuse(Color3f(0., 0., 1.));
    pMat->setLit    (true               );
    setMaterialZ(pMat);

//    SimpleMaterial *simpleMat;
//    Geometry       *geo;

    setExternalUpdateHandler(NULL);

    // add a name attachment
    NameUnrecPtr nameN = Name::create();
    nameN->editFieldPtr()->setValue("XYManipulator");
    addAttachment(nameN);

    // make the axis line. Not really a handle, but easier to manage this way.
       
    GeoBuilder b;
    
    b.vertex(Pnt3f(0,0,0));
    b.vertex(Pnt3f(0,getLength()[1],0));
    
    b.line(0, 1);
    
    GeometryUnrecPtr g = b.getGeometry();
    
    g->setMaterial(getMaterialY());
    
    NodeUnrecPtr pNode = makeNodeFor(g);
    setTransYNode(pNode);

    // make the plane handle

    pNode = Node::create();
    setTransXNode(pNode);

    g = makePlaneGeo(getLength()[0] / 2.f, getLength()[2] / 2.f, 1, 1);
    g->setMaterial(getMaterialX());   
    pNode = makeNodeFor(g);
    
    OSG::ComponentTransformUnrecPtr transHandleXC = ComponentTransform::create();

    setHandleXNode(pNode);

    getTransXNode()->setCore (transHandleXC   );
    getTransXNode()->addChild(getHandleXNode());

    transHandleXC->setTranslation(Vec3f(0, getLength()[1], 0));
    transHandleXC->setRotation   (Quaternion(Vec3f(1, 0, 0), osgDegree2Rad(90)));

    //
    // make the rotate handle

    pNode = Node::create();
    setTransZNode(pNode);

    g = makeCylinderGeo(0.05f, 0.1f, 16, true, true, true);
    g->setMaterial(getMaterialZ());   
    pNode = makeNodeFor(g);
    
    OSG::ComponentTransformUnrecPtr transHandleZC = ComponentTransform::create();

    setHandleZNode(pNode);

    getTransZNode()->setCore (transHandleZC   );
    getTransZNode()->addChild(getHandleZNode());

    transHandleZC->setTranslation(Vec3f(0, getLength()[1], 0));

    commitChanges();
}
Exemplo n.º 3
0
void PCSSShadowMap::render(DrawEnv *pEnv)
{
    Window  *win = pEnv->getWindow();
    initialize(win);

    if(!_useGLSL || !_useShadowExt)
        _shadowVP->Viewport::render(pEnv->getAction());
    else
    {
        glPushAttrib(GL_ENABLE_BIT);

        if(!_initTexturesDone)
            initTextures(win);

        if(_useFBO)
        {
            if(!initFBO(pEnv))
                printf("ERROR with FBOBJECT\n");
        }

        GLfloat globalAmbient[] =
        {
            0.0, 0.0, 0.0, 1.0
        };
        glLightModelfv(GL_LIGHT_MODEL_AMBIENT, globalAmbient);
        _firstRun = 1;

#if 0
        for(UInt32 i = 0;i < _shadowVP->_lights.size();i++)
        {
            {
                _shadowVP->_texChunks[i]->setMinFilter(GL_NEAREST);
                _shadowVP->_texChunks[i]->setMagFilter(GL_NEAREST);
            }
        }
#endif

        if(_shadowVP->getPixelWidth() != _width ||
           _shadowVP->getPixelHeight() != _height)
        {
            _width = _shadowVP->getPixelWidth();
            _height = _shadowVP->getPixelHeight();

            if(_useNPOTTextures)
            {
                _colorMapImage->set(GL_RGB, _width, _height);

                _shadowFactorMapImage->set(GL_RGB, _width, _height);

                reInit(pEnv);
            }
            else
            {
                if(_width > _height)
                    _widthHeightPOT = osgNextPower2(_width - 1);
                else
                    _widthHeightPOT = osgNextPower2(_height - 1);

                _colorMapImage->set(GL_RGB, _widthHeightPOT, _widthHeightPOT);

                _shadowFactorMapImage->set(GL_RGB, _widthHeightPOT,
                                           _widthHeightPOT);
            }
        }

        commitChanges();

        if(_shadowVP->getMapAutoUpdate())
        {
#ifdef USE_FBO_FOR_COLOR_AND_FACTOR_MAP
            if(_useFBO && _useNPOTTextures)
                createColorMapFBO(pEnv);
            else
#endif
                createColorMap(pEnv);

            //deactivate transparent Nodes
            for(UInt32 t = 0;t < _shadowVP->_transparent.size();++t)
                _shadowVP->_transparent[t]->setTravMask(0);

            if(_useFBO)
                createShadowMapsFBO(pEnv);
            else
                createShadowMaps(pEnv);

            // switch on all transparent geos
            for(UInt32 t = 0;t < _shadowVP->_transparent.size();++t)
                _shadowVP->_transparent[t]->setTravMask(TypeTraits<UInt32>::BitsSet);

            for(UInt32 i = 0;i < _shadowVP->_lights.size();i++)
            {
                if(_shadowVP->_lightStates[i] != 0)
                {
                    if(_shadowVP->getGlobalShadowIntensity() != 0.0 ||
                       _shadowVP->_lights[i].second->getShadowIntensity() != 0.0)
                    {
#ifdef USE_FBO_FOR_COLOR_AND_FACTOR_MAP
                        if(_useFBO && _useNPOTTextures)
                            createShadowFactorMapFBO(pEnv, i);
                        else
#endif
                            createShadowFactorMap(pEnv, i);
                        //_firstRun = 0;
                    }
                }
            }
        }
        else
        {
            if(_shadowVP->_trigger_update)
            {
#ifdef USE_FBO_FOR_COLOR_AND_FACTOR_MAP
                if(_useFBO && _useNPOTTextures)
                    createColorMapFBO(pEnv);
                else
#endif
                    createColorMap(pEnv);

                //deactivate transparent Nodes
                for(UInt32 t = 0;t < _shadowVP->_transparent.size();++t)
                    _shadowVP->_transparent[t]->setTravMask(0);

                if(_useFBO)
                    createShadowMapsFBO(pEnv);
                else
                    createShadowMaps(pEnv);

                // switch on all transparent geos
                for(UInt32 t = 0;t < _shadowVP->_transparent.size();++t)
                    _shadowVP->_transparent[t]->setTravMask(TypeTraits<UInt32>::BitsSet);

                for(UInt32 i = 0;i < _shadowVP->_lights.size();i++)
                {
                    if(_shadowVP->_lightStates[i] != 0)
                    {
                        if(_shadowVP->getGlobalShadowIntensity() != 0.0 ||
                           _shadowVP->_lights[i].second->getShadowIntensity() != 0.0)
                        {
#ifdef USE_FBO_FOR_COLOR_AND_FACTOR_MAP
                            if(_useFBO && _useNPOTTextures)
                                createShadowFactorMapFBO(pEnv, i);
                            else
#endif
                                createShadowFactorMap(pEnv, i);
                        }
                    }
                }
                _shadowVP->_trigger_update = false;
            }
        }

        drawCombineMap(pEnv);

        glPopAttrib();
        // render the foregrounds.
        for(UInt16 i = 0;i < _shadowVP->getMFForegrounds()->size();++i)
        {
            _shadowVP->getForegrounds(i)->draw(pEnv, _shadowVP);
        }
    }
}
void ShaderShadowMapEngine::handlePointLightEnter(
    PointLight *pointL, RenderAction *ract, SSMEngineData *data)
{
    RenderPartition *parentPart = ract->getActivePartition();

    Matrix matEyeToWorld(parentPart->getCameraToWorld());
    Matrix matLightProj;

    Real32 lightNear;
    Real32 lightFar;

    calcPointLightRange(pointL, 0.001f,
                        parentPart->getNear(), parentPart->getFar(),
                        lightNear,             lightFar             );

    MatrixPerspective(matLightProj, Pi / 4.f, 1.f,
                      lightNear, lightFar         );

    Matrix matWorldToLight;
    Matrix matEyeToLight;

    calcPointLightMatrices(matWorldToLight, matEyeToLight,
                           pointL,          matEyeToWorld );

    updatePointLightShadowTexImage  (data);
    updatePointLightShadowTexBuffers(data);
    updatePointLightRenderTargets   (data);

    Int32 shadowTexUnit = (this->getForceTextureUnit() > 0) ?
                           this->getForceTextureUnit()      : 7;

    ShaderProgram *shadowFP = this->getShadowFragmentProgram();

    if(shadowFP == NULL)
    {
        ShaderProgramUnrecPtr newShadowFP = ShaderProgram::createLocal();
        newShadowFP->setShaderType(GL_FRAGMENT_SHADER);
        newShadowFP->setProgram   (_pointFPCode      );

        newShadowFP->addUniformVariable("SSME_matEyeToLight", matEyeToLight);
        newShadowFP->addUniformVariable("SSME_matLightProj",  matLightProj );
        newShadowFP->addUniformVariable("SSME_texShadow",     shadowTexUnit);

        this->setShadowFragmentProgram(newShadowFP);
        shadowFP = newShadowFP;
    }
    else
    {
        shadowFP->updateUniformVariable("SSME_matEyeToLight", matEyeToLight);
        shadowFP->updateUniformVariable("SSME_matLightProj",  matLightProj );
    }

    commitChanges();

    // schedule rendering of cube faces
    for(UInt16 i = 0; i < 6; ++i)
    {
        Matrix matWorldToLightFace(matWorldToLight);
        matWorldToLightFace.multLeft(_matCubeFaceInv[i]);

        this->pushPartition(ract);
        {
            RenderPartition   *part   = ract->getActivePartition( );
            Window            *win    = ract->getWindow         ( );
            FrameBufferObject *target = data->getRenderTargets  (i);
            Background        *back   = data->getBackground     ( );

            part->setRenderTarget(target);
            part->setWindow      (win   );

            part->calcViewportDimension(0.f, 0.f, 1.f, 1.f,
                                        target->getWidth (),
                                        target->getHeight() );

            part->setupProjection(matLightProj, Matrix::identity());
            part->setupViewing   (matWorldToLightFace             );

            part->setNear        (parentPart->getNear());
            part->setFar         (parentPart->getFar ());

            part->calcFrustum    (                     );

            part->setBackground  (back                 );

            // force material for shadow map generation
            part->overrideMaterial(data->getLightPassMaterials(0),
                                   ract->getActNode           ( ) );

            this->recurseFrom(ract, pointL);
            ract->useNodeList(false       );

            // undo override
            part->overrideMaterial(NULL,
                                   ract->getActNode           ( ) );
        }
        this->popPartition(ract);
    }
}
void ShaderShadowMapEngine::handleSpotLightEnter(
    SpotLight *spotL, RenderAction *ract, SSMEngineData *data)
{
    RenderPartition *parentPart    = ract->getActivePartition();
//    Real             cosSpotCutOff = osgCos(spotL->getSpotCutOff());

    Matrix matEyeToWorld  (parentPart->getCameraToWorld());
    Matrix matWorldToLight;
    Matrix matEyeToLight;

    calcSpotLightMatrices(matWorldToLight, matEyeToLight, 
                          spotL,           matEyeToWorld );

    Real32  lightNear;
    Real32  lightFar;

    calcPointLightRange(spotL, 0.001f,
                        parentPart->getNear(), parentPart->getFar(),
                        lightNear,             lightFar             );

    if(getShadowNear() != 0.f)
    {
        lightNear = getShadowNear();
    }

    if(getShadowFar() != 0.f)
    {
        lightFar  = getShadowFar();
    }

    Matrix matLightProj;
    Matrix matLightProjTrans;

    MatrixPerspective(matLightProj, 
                      spotL->getSpotCutOff(), 1.f,
                      lightNear, lightFar         );
    
    updateShadowTexImage  (data);
    updateShadowTexBuffers(data);
    updateRenderTargets   (data);

    Int32          shadowTexUnit = (this->getForceTextureUnit() > 0) ?
                                    this->getForceTextureUnit()      : 7;
    ShaderProgram *shadowFP      = this->getShadowFragmentProgram();

    if(shadowFP == NULL)
    {
        ShaderProgramUnrecPtr newShadowFP = ShaderProgram::createLocal();
        newShadowFP->setShaderType(GL_FRAGMENT_SHADER);
        newShadowFP->setProgram   (_spotFPCode       );

        newShadowFP->addUniformVariable("SSME_matEyeToLight", matEyeToLight);
        newShadowFP->addUniformVariable("SSME_matLightProj",  matLightProj );
        newShadowFP->addUniformVariable("SSME_texShadow",     shadowTexUnit);

        this->setShadowFragmentProgram(newShadowFP);
        shadowFP = newShadowFP;
    }
    else
    {
        shadowFP->updateUniformVariable("SSME_matEyeToLight", matEyeToLight);
        shadowFP->updateUniformVariable("SSME_matLightProj",  matLightProj );
    }

    commitChanges();

    this->pushPartition(ract);
    {
        RenderPartition   *part   = ract->getActivePartition( );
        Window            *win    = ract->getWindow         ( );
        FrameBufferObject *target = data->getRenderTargets  (0);
        Background        *back   = data->getBackground     ( );

        part->setRenderTarget(target);
        part->setWindow      (win   );

        part->calcViewportDimension(0.f, 0.f, 1.f, 1.f,
                                    target->getWidth (),
                                    target->getHeight() );

        part->setupProjection(matLightProj, matLightProjTrans);
        part->setupViewing   (matWorldToLight                );

        part->setNear        (parentPart->getNear());
        part->setFar         (parentPart->getFar ());

        part->calcFrustum    (                     );

        part->setBackground  (back                 );

        // force material for shadow map generation
        part->overrideMaterial(data->getLightPassMaterials(0),
                               ract->getActNode           ( ) );

        this->recurseFrom(ract, spotL);
        ract->useNodeList(false      );

        // undo override
        part->overrideMaterial(NULL,
                               ract->getActNode           ( ) );
    }
    this->popPartition(ract);
}
Exemplo n.º 6
0
void GroupWisePrivacyDialog::slotOk()
{
	if ( m_dirty )
		commitChanges();
	KDialog::accept();
}
void DrawableStatsAttachment::validate(void)
{
    commitChanges();

    // Still valid? Do nothing.
    if(getValid())
        return;

    AttachmentContainer *cont =
        dynamic_cast<AttachmentContainer *>(this->getParents(0));

    // Called on a non-AttachmentContainer?
    if(cont == NULL)
        return;

    reset();

    // Drawable?
    Drawable *g = dynamic_cast<Drawable *>(cont);

    if(g != NULL)
    {
        //calc(g);
        g->fill(this);
    }

    // Node?
    Node *n = dynamic_cast<Node *>(cont);
    if(n != NULL)
    {
        // Validate the core
        Drawable *g = dynamic_cast<Drawable *>(n->getCore());
        if(g != NULL)
        {
            DrawableStatsAttachmentUnrecPtr s = get(g);

            if(s == NULL)
            {
                s = DrawableStatsAttachment::addTo(g);
            }

            s->validate();

            *this += s;
            setValid(false); // Not done yet.
        }

        // Validate all the children
        for(UInt32 i = 0; i < n->getNChildren(); ++i)
        {
            Node *c = n->getChild(i);

            DrawableStatsAttachmentUnrecPtr s = get(c);

            if(s == NULL)
            {
                s = DrawableStatsAttachment::addTo(c);
            }

            s->validate();

            *this += s;
            setValid(false); // Not done yet.
        }
    }
    setValid(true); // Done!
}
Exemplo n.º 8
0
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);
    
    {
        // Set up Window
        WindowEventProducerRecPtr TutorialWindow = createNativeWindow();
        TutorialWindow->initWindow();

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

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

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

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

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

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

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

        ButtonRefPtr ExampleButton = OSG::Button::create();
        ExampleButton->setMinSize(Vec2f(50, 25));
        ExampleButton->setMaxSize(Vec2f(200, 100));
        ExampleButton->setPreferredSize(Vec2f(100, 50));
        ExampleButton->setText("Button 1");

        // Create an ActionListener and assign it to ExampleButton
        // This Class is defined above, and will cause the output
        // window to display "Button 1 Action" when pressed
        ExampleButton->connectActionPerformed(boost::bind(actionPerformed, _1));

        //Toggle Button
        ToggleButtonRefPtr ExampleToggleButton = OSG::ToggleButton::create();
        ExampleToggleButton->setSelected(false);
        ExampleToggleButton->setText("ToggleMe");


        //Text Field
        TextFieldRefPtr ExampleTextField = OSG::TextField::create();
        
        //Password Field
        PasswordFieldRefPtr ExamplePasswordField = OSG::PasswordField::create();

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

        //Panel
        PanelRecPtr ExamplePanel = Panel::create();
        ExamplePanel->setPreferredSize(Vec2f(200.0f,200.0f));
        ExamplePanel->setLayout(MainLayout);
        ExamplePanel->pushToChildren(ExampleTextField);
        ExamplePanel->pushToChildren(ExamplePasswordField);

        //Text Field 2
        TextFieldRefPtr ExampleTextField2 = OSG::TextField::create();

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

        InternalWindowRefPtr MainInternalWindow = OSG::InternalWindow::create();
        MainInternalWindow->pushToChildren(ExampleButton);
        MainInternalWindow->pushToChildren(ExampleToggleButton);
        MainInternalWindow->pushToChildren(ExamplePanel);
        MainInternalWindow->pushToChildren(ExampleTextField2);

        MainInternalWindow->setLayout(MainLayout);
        MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
        MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
        MainInternalWindow->setScalingInDrawingSurface(Vec2f(0.5f,0.5f));
        MainInternalWindow->setDrawTitlebar(false);
        MainInternalWindow->setResizable(false);

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

        TutorialDrawingSurface->openWindow(MainInternalWindow);

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

        TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);

        sceneManager.setRoot(scene);

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

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

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


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

        commitChanges();

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

    osgExit();

    return 0;
}
void OcclusionCullingTreeBuilder::draw(DrawEnv             &denv,
                                       RenderPartitionBase *part)
{
#if 1 //CHECK_ENV_ACTION
    //std::cout << "Frame Start" << std::endl;
    Window* win = denv.getWindow();

    if(_sortMode == ModeAdaptiveBucket)
    {
        // Merge all the buckets to a tree
        for(UInt32 i = 0; i < _numBuckets; ++i)
        {
            if(_buckets[i] != NULL)
            {
                _pRoot->addChild(_buckets[i]);
            }
        }
    }

    if(!win->hasExtension(_extOcclusionQuery))
    {
        // Don't have it, just draw the whole tree.
        SLOG << "Missing OCC GL extensions!!" << endLog;

        _uiActiveMatrix = 0;
        Inherited::drawNode(_pRoot, denv, part);

        return;
    }

//SETUP
// done in add, action should never change
//    _ract = dynamic_cast<RenderAction*>(denv.getAction());

    if(!_ract)
    {
        FFATAL(("OcclusionCullingTreeBuilder::draw: Action in denv is not a "
                "RenderAction!\n"));
        return;
    }

    _uiActiveMatrix = 0;
    Real32 screenCoveredPercentage = 0.f;
    if(_ract->getOcclusionCullingQueryBufferSize() != _numTestSamples || !_occInitialized)
    {
        _numTestSamples = _ract->getOcclusionCullingQueryBufferSize();
        //std::cout << "Buf size: " << _numTestSamples << std::endl;
        _testSamples.resize(_numTestSamples);
        //std::cout << "Performing OCC on " << _numNodes << " nodes." << std::endl;

        GenQueryT genquer = reinterpret_cast<GenQueryT>(
            win->getFunction(_funcGenQueriesARB));
        genquer(_numTestSamples, &(_testSamples.front()));
        _occInitialized = true;
    }

    if(!_isOccStateCreated)
    {
        _isOccStateCreated = true;

        // register an exit function to clean up the State object
        addPreFactoryExitFunction(&releaseTestingState);

        // Create an empty state to render test nodes.
        _testingStatePtr = State::create();

        DepthChunkUnrecPtr dc = DepthChunk::create();
        dc->setReadOnly(true);
        _testingStatePtr->addChunk(dc);

        ColorMaskChunkUnrecPtr cc = ColorMaskChunk::create();
        cc->setMaskR(false);
        cc->setMaskG(false);
        cc->setMaskB(false);
        cc->setMaskA(false);
        _testingStatePtr->addChunk(cc);

        PolygonChunkUnrecPtr pc = PolygonChunk::create();
        pc->setCullFace(GL_BACK);
        _testingStatePtr->addChunk(pc);

        commitChanges();
    }

    //glGenQueriesARB(_numNodes, queries);
    //std::cout << "Calculated Pixels" << std::endl;

    _vpWidth  = denv.getPixelWidth();
    _vpHeight = denv.getPixelHeight();

    _worldToScreen = denv.getVPWorldToScreen();

    _testingState = &*_testingStatePtr;


    _minFeatureSize = _ract->getOcclusionCullingMinimumFeatureSize();
    _visPixelThreshold = _ract->getOcclusionCullingVisibilityThreshold();
    _coveredProbThreshold = _ract->getOcclusionCullingCoveredThreshold();
    _minTriangleCount = _ract->getOcclusionCullingMinimumTriangleCount();
    _inTesting = false;

    _currSample = 0;
//DRAW / TEST / RE-DRAW ON BUFFER FULL
    testNode(_pRoot, denv, part, screenCoveredPercentage);

    StatCollector *sc = _ract->getStatCollector();
    if(sc != NULL)
        sc->getElem(statNOccNodes)->add(_numNodes);
    _numNodes=0;
    _uiActiveMatrix = 0;

    leaveTesting(denv, part);

//RESULTS / RE-DRAW
    while( !_testPendingNodes.empty() )
    {
        drawTestResults(denv, part);
    }

    //std::cout << "Calc Pixels" << std::endl;


    if(sc != NULL)
    {
        Real32 percentage =
            Real32(sc->getElem(statNOccInvisible)->get()) /
            Real32(sc->getElem(statNOccTests)->get());
        sc->getElem(statNOccSuccessTestPer)->set(percentage);
    }

    //std::cout << "Real pixels " << std::endl;
    //std::cout << std::endl;

   // screen_covered_percentage = 1.0;
   // drawNode(_pRoot, denv, part, screen_covered_percentage);
    _numNodes=0;
    _currSample = 0;
    //std::cout << "Frame End" << std::endl;
#endif
}
ActionBase::ResultE CubeMapGenerator::renderEnter(Action *action)
{
    static Matrix transforms[] = 
    { 
        Matrix( 1,  0,  0,  0,
                0, -1,  0,  0,
                0,  0, -1,  0,
                0,  0,  0,  1),
        
        Matrix(-1,  0,  0,  0,
                0, -1,  0,  0,
                0,  0,  1,  0,
                0,  0,  0,  1),
        
        Matrix( 1,  0,  0,  0,
                0,  0, -1,  0,
                0,  1,  0,  0,
                0,  0,  0,  1),
        
        Matrix( 1,  0,  0,  0,
                0,  0,  1,  0,
                0, -1,  0,  0,
                0,  0,  0,  1),
        
        Matrix( 0,  0, -1,  0,
                0, -1,  0,  0,
               -1,  0,  0,  0,
                0,  0,  0,  1),
        
        Matrix( 0,  0,  1,  0,
                0, -1,  0,  0,
                1,  0,  0,  0,
                0,  0,  0,  1)
    };

    RenderAction *a = dynamic_cast<RenderAction *>(action);

    Action::ResultE  returnValue = Action::Continue;

    Background      *pBack    = a->getBackground();

    Viewport        *pPort    = a->getViewport();

    Node            *pActNode = a->getActNode();

    CubeMapGeneratorStageData *pData = 
        a->getData<CubeMapGeneratorStageData *>(_iDataSlotId);

    if(pData == NULL)
    {
        pData = this->initData(a);
    }

    TraversalValidator::ValidationStatus eStatus = this->validateOnEnter(a);

    if(eStatus == TraversalValidator::Run)
    {
        this->beginPartitionGroup(a);
        {
            FrameBufferObject *pTarget  = this->getRenderTarget();
                
            if(pTarget == NULL)
            {
                pTarget  = pData->getRenderTarget();
            }

            Pnt3f oOrigin;

            if(this->getOriginMode() == CubeMapGenerator::UseStoredValue)
            {
                oOrigin = this->getOrigin();
            }
            else if(this->getOriginMode() == CubeMapGenerator::UseBeacon)
            {
                fprintf(stderr, "CubemapGen::UseBeacon NYI\n");
            }
            else if(this->getOriginMode() == 
                                       CubeMapGenerator::UseCurrentVolumeCenter)
            {
                BoxVolume oWorldVol;

                commitChanges();

                pActNode->updateVolume();
                
                pActNode->getWorldVolume(oWorldVol);
                
                oWorldVol.getCenter(oOrigin);
            }
            else if(this->getOriginMode() == 
                                       CubeMapGenerator::UseParentsVolumeCenter)
            {
                fprintf(stderr, "CubemapGen::UseParentsCenter NYI\n");
            }

            Camera *pCam = pData->getCamera();

            pActNode->setTravMask(0);

            for(UInt32 i = 0; i < 6; ++i)
            {
                this->pushPartition(a);
                {
                    RenderPartition   *pPart    = a->getActivePartition();
                
                    pPart->setVolumeDrawing(false);

                    pPart->setRenderTarget(pTarget       );
                    pPart->setWindow      (a->getWindow());

                    pPart->calcViewportDimension(0,
                                                 0,
                                                 1,
                                                 1,
                                                 this->getWidth (),
                                                 this->getHeight());
                
                    Matrix m, t;
            
                    // set the projection
                    pCam->getProjection          (m, 
                                                  pPart->getViewportWidth (), 
                                                  pPart->getViewportHeight());
                
                    pCam->getProjectionTranslation(t, 
                                                   pPart->getViewportWidth (), 
                                                   pPart->getViewportHeight());
                
                    pPart->setupProjection(m, t);
            
                    m = transforms[i];
            
                    m[3][0] = oOrigin[0];
                    m[3][1] = oOrigin[1];
                    m[3][2] = oOrigin[2];

                    m.invert();

                    pPart->setupViewing(m);
            
                    pPart->setNear     (pCam->getNear());
                    pPart->setFar      (pCam->getFar ());
                    
                    pPart->calcFrustum();
                
                    if(this->getBackground() == NULL)
                    {
                        pPart->setBackground(pBack);
                    }
                    else
                    {
                        pPart->setBackground(this->getBackground());
                    }
                
                    if(this->getRoot() != NULL)
                    {
                        this->recurse(a, this->getRoot());
                    }
                    else
                    {
                        this->recurse(a, pPort->getRoot());
                    }

                    pPart->setDrawBuffer(GL_COLOR_ATTACHMENT0_EXT + i);

#ifdef OSG_DEBUGX
                    std::string szMessage("CubeX\n");
                    pPart->setDebugString(szMessage          );
#endif
                }
                this->popPartition(a);
            }

            pActNode->setTravMask(~0);
        }
        this->endPartitionGroup(a);
    }

    OSG_ASSERT(pActNode == a->getActNode());

    returnValue = Inherited::renderEnter(action);

    action->useNodeList(false);

    return returnValue;
}
Action::ResultE
AnimBindAction::bindFields(AttachmentContainer *attCon)
{
    AnimTargetAttachment *targetAtt = getTargetAtt(attCon);

    if(targetAtt == NULL)
        return Action::Continue;

    Animation       *anim  = getAnim();
    DataSourceMapIt  dsIt  = _dsMap.begin();
    DataSourceMapIt  dsEnd = _dsMap.end  ();

    while(dsIt != dsEnd)
    {
        if(dsIt->first.find(targetAtt->getTargetId()) != 0)
        {
            ++dsIt;
            continue;
        }

        std::string targetId;
        std::string subTargetId;

        splitTargetId(dsIt->first, targetId, subTargetId);

        if(targetId != targetAtt->getTargetId())
        {
            ++dsIt;
            continue;
        }

        SINFO << "AnimBindAction::bindFields: binding source '"
              << dsIt->first << "' to '" << targetId << "' - '"
              << subTargetId << "'" << std::endl;

        FieldDescriptionBase *fDesc =
            attCon->getType().getFieldDesc(subTargetId.c_str());

        if(fDesc == NULL)
        {
            SWARNING << "AnimBindAction::bindFields: no Field for "
                     << "subTargetId [" << subTargetId << "] found."
                     << std::endl;
            ++dsIt;
            continue;
        }

        // create channel
        AnimChannelUnrecPtr channel = dsIt->second->createChannel();
        anim->editMFChannels()->push_back(channel);

         // create blender
        UInt32 fId = fDesc->getFieldId();

        if(targetAtt->getMFBlenders()->size() <= fId)
            targetAtt->editMFBlenders()->resize(fId + 1, NULL);

        AnimBlenderUnrecPtr blender = targetAtt->getBlenders(fId);

        if(blender == NULL)
        {
            blender = dsIt->second->createBlender();
            targetAtt->editMFBlenders()->replace(fId, blender);
        }

        // on create all fields are marked as changed - this causes
        // the blender to write to its destination even though
        // it has no valid input data - avoid it by committing before
        // connecting the blender to its dest
        commitChanges();

        blender->addChannel(channel                 );
        blender->connectTo (attCon, fDesc->getName());

        // remove bound data source from map
        DataSourceMapIt eraseIt = dsIt;
        ++dsIt;
        _dsMap.erase(eraseIt);
    }

    if(_dsMap.empty() == true)
    {
        return Action::Quit;
    }
    else
    {
        return Action::Continue;
    }
}
void TrapezoidalShadowMapEngine::handleSpotLightEnter(
    SpotLight *spotL, RenderAction *ract, TSMEngineData *data)
{
    RenderPartition *parentPart = ract->getActivePartition();

    Matrixr matEyeToWorld(parentPart->getCameraToWorld());
    Matrixr matWorldToLight;
    Matrixr matEyeToLight;

    Inherited::calcSpotLightMatrices(matWorldToLight, matEyeToLight,
                                     spotL,           matEyeToWorld );

    Matrixr matLightProj;
    Matrixr matLightFull(matWorldToLight);

    Real    shadowNear = (getShadowNear() != 0.f ? 
                          getShadowNear()       : 
                          parentPart->getNear()  );
    Real    shadowFar  = (getShadowFar () != 0.f ?
                          getShadowFar ()       :
                          parentPart->getFar()   );

    Inherited::calcPointLightRange(
        spotL, 0.01f,
        shadowNear, shadowFar, shadowNear, shadowFar);

    MatrixPerspective(matLightProj,
                      spotL->getSpotCutOff(), 1.f,
                      shadowNear, shadowFar       );

    matLightFull.multLeft(matLightProj);

    Inherited::updateShadowTexImage  (data);
    Inherited::updateShadowTexBuffers(data);
    Inherited::updateRenderTargets   (data);

    const FrustumVolume &eyeFrust   = parentPart->getFrustum();
          FrustumVolume  lightFrust;
          Matrixr        matNT;

    lightFrust.setPlanes(matLightFull);

    bool matNTValid = calcTrapezoidalTransform(matNT,
                                               matEyeToWorld, matLightFull,
                                               eyeFrust,      lightFrust   );

    if(matNTValid == false)
        return;

//    Real           cosSpotCutOff = osgCos(spotL->getSpotCutOff());

    Int32          shadowTexUnit = (this->getForceTextureUnit() >= 0) ?
                                    this->getForceTextureUnit()       : 7;
    ShaderProgram *shadowFP      = this->getShadowFragmentProgram();

    if(shadowFP == NULL)
    {
        ShaderProgramUnrecPtr newShadowFP = ShaderProgram::createLocal();
        newShadowFP->setShaderType(GL_FRAGMENT_SHADER);
        newShadowFP->setProgram   (_spotFPCode       );

        newShadowFP->addUniformVariable("TSME_matEyeToLight", matEyeToLight);
        newShadowFP->addUniformVariable("TSME_matLightProj",  matLightProj );
        newShadowFP->addUniformVariable("TSME_matNT",         matNT        );
        newShadowFP->addUniformVariable("TSME_texShadow",     shadowTexUnit);
        newShadowFP->addUniformVariable("TSME_texShadowSizeInv",
                                        Vec2f(1.f / getWidth (), 
                                              1.f / getHeight() )          );

        this->setShadowFragmentProgram(newShadowFP);
        shadowFP = newShadowFP;
    }
    else
    {
        shadowFP->updateUniformVariable("TSME_matEyeToLight", matEyeToLight);
        shadowFP->updateUniformVariable("TSME_matLightProj",  matLightProj );
        shadowFP->updateUniformVariable("TSME_matNT",         matNT        );
    }

    updateLightPassMaterial(data, 0, matNT);

    commitChanges();
    
    this->pushPartition(ract);
    {
        RenderPartition   *part   = ract->getActivePartition( );
        Window            *win    = ract->getWindow         ( );
        FrameBufferObject *target = data->getRenderTargets  (0);
        Background        *back   = data->getBackground     ( );

        part->setRenderTarget(target);
        part->setWindow      (win   );

        part->calcViewportDimension(0.f, 0.f, 1.f, 1.f,
                                    target->getWidth (),
                                    target->getHeight() );

        part->setupProjection(matLightProj, Matrixr::identity());
        part->setupViewing   (matWorldToLight                  );
        
        part->setNear        (parentPart->getNear());
        part->setFar         (parentPart->getFar ());

        part->setFrustum     (lightFrust           );

        part->setBackground  (back                 );

        part->overrideMaterial(data->getLightPassMaterials(0),
                               ract->getActNode           ( ) );

        this->recurseFrom(ract, spotL);
        ract->useNodeList(false      );

        part->overrideMaterial(NULL,
                               ract->getActNode           ( ) );
    }
    this->popPartition(ract);
}
void TrapezoidalShadowMapEngine::handlePointLightEnter(
    PointLight *pointL, RenderAction *ract, TSMEngineData *data)
{
    RenderPartition *parentPart = ract->getActivePartition();
    
    Matrixr matEyeToWorld(parentPart->getCameraToWorld());  
    Matrixr matLightProj;

    Real    shadowNear = (getShadowNear() != 0.f ? 
                          getShadowNear()       : 
                          parentPart->getNear()  );
    Real    shadowFar  = (getShadowFar () != 0.f ?
                          getShadowFar ()       :
                          parentPart->getFar()   );

    Inherited::calcPointLightRange(
        pointL, 0.01f,
        shadowNear, shadowFar, shadowNear, shadowFar);

    MatrixPerspective(matLightProj, Pi / 4.f, 1.f,
                      shadowNear, shadowFar       );
    
    Matrixr   matWorldToLight;
    Matrixr   matEyeToLight;
    MFMatrixr mfMatNT;

    mfMatNT.resize(6);

    Inherited::calcPointLightMatrices(matWorldToLight, matEyeToLight,
                                      pointL,          matEyeToWorld );

    Inherited::updatePointLightShadowTexImage  (data);
    Inherited::updatePointLightShadowTexBuffers(data);
    Inherited::updatePointLightRenderTargets   (data);

    Int32          shadowTexUnit = (this->getForceTextureUnit() >= 0) ?
                                    this->getForceTextureUnit()       : 7;
    ShaderProgram *shadowFP      = this->getShadowFragmentProgram();

    if(shadowFP == NULL)
    {
        ShaderProgramUnrecPtr newShadowFP = ShaderProgram::createLocal();
        newShadowFP->setShaderType(GL_FRAGMENT_SHADER);
        newShadowFP->setProgram   (_pointFPCode      );
        
        newShadowFP->addUniformVariable("TSME_matEyeToLight", matEyeToLight);
        newShadowFP->addUniformVariable("TSME_matLightProj",  matLightProj );
        newShadowFP->addUniformVariable("TSME_matNT",         mfMatNT      );
        newShadowFP->addUniformVariable("TSME_texShadow",     shadowTexUnit);
        newShadowFP->addUniformVariable("TSME_texShadowSizeInv",
                                        Vec2f(1.f / getWidth (), 
                                              1.f / getHeight() )          );
        
        this->setShadowFragmentProgram(newShadowFP);
        shadowFP = newShadowFP;
    }
    else
    {
        shadowFP->updateUniformVariable("TSME_matEyeToLight", matEyeToLight);
        shadowFP->updateUniformVariable("TSME_matLightProj",  matLightProj );
    }

    const FrustumVolume &eyeFrust = parentPart->getFrustum();

    for(UInt16 faceIdx = 0; faceIdx < 6; ++faceIdx)
    {
        Matrixr matWorldToLightFace (matWorldToLight         );
        matWorldToLightFace.multLeft(_matCubeFaceInv[faceIdx]);

        Matrixr matLightFull(matWorldToLightFace);
        matLightFull.multLeft(matLightProj);

        FrustumVolume lightFrust;
        Matrixr       matNT;

        lightFrust.setPlanes(matLightFull);

        bool matNTValid = 
            calcTrapezoidalTransform(mfMatNT[faceIdx],
                                     matEyeToWorld,    matLightFull,
                                     eyeFrust,         lightFrust   );

        if(matNTValid == false)
        {
            // setup a minimal partition to clear the cube face

            commitChanges();

            this->pushPartition(ract,
                                RenderPartition::CopyNothing,
                                RenderPartition::SimpleCallback);
            {
                RenderPartition   *part   = ract->getActivePartition(       );
                Window            *win    = ract->getWindow         (       );
                FrameBufferObject *target = data->getRenderTargets  (faceIdx);
                Background        *back   = data->getBackground     (       );

                part->setSetupMode(RenderPartition::ViewportSetup  |
                                   RenderPartition::BackgroundSetup );

                part->setRenderTarget(target);
                part->setWindow      (win   );

                part->calcViewportDimension(0.f, 0.f, 1.f, 1.f,
                                            target->getWidth (),
                                            target->getHeight() );
                
                part->setBackground(back);

                RenderPartition::SimpleDrawCallback emptyCubeFaceDraw =
                    boost::bind(
                        &TrapezoidalShadowMapEngine::emptyCubeFaceDrawFunc,
                        this, _1);

                part->dropFunctor(emptyCubeFaceDraw);
            }
            this->popPartition(ract);
        }
        else
        {
            updateLightPassMaterial(data, faceIdx, mfMatNT[faceIdx]);
        
            commitChanges();

            this->pushPartition(ract);
            {
                RenderPartition   *part   = ract->getActivePartition(       );
                Window            *win    = ract->getWindow         (       );
                FrameBufferObject *target = data->getRenderTargets  (faceIdx);
                Background        *back   = data->getBackground     (       );

                part->setRenderTarget(target);
                part->setWindow      (win   );

                part->calcViewportDimension(0.f, 0.f, 1.f, 1.f,
                                            target->getWidth (),
                                            target->getHeight() );

                part->setupProjection(matLightProj, Matrixr::identity());
                part->setupViewing   (matWorldToLightFace              );

                part->setNear        (parentPart->getNear());
                part->setFar         (parentPart->getFar ());
            
                part->setFrustum     (lightFrust           );
                
                part->setBackground  (back                 );

                part->overrideMaterial(data->getLightPassMaterials(faceIdx),
                                       ract->getActNode           (       ) );

                this->recurseFrom(ract, pointL);
                ract->useNodeList(false       );

                part->overrideMaterial(NULL,
                                       ract->getActNode           (       ) );
            }
            this->popPartition(ract);
        }
    }

    shadowFP->updateUniformVariable("TSME_matNT", mfMatNT);
}
Exemplo n.º 14
0
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);
    {
        // Set up Window
        WindowEventProducerRecPtr TutorialWindow = createNativeWindow();

        //Initialize Window
        TutorialWindow->initWindow();

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

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

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

        //Shader Chunk
        SimpleSHLChunkUnrecPtr TheSHLChunk = SimpleSHLChunk::create();
        TheSHLChunk->setVertexProgram(createSHLVertexProg());
        TheSHLChunk->setFragmentProgram(createSHLFragProg());
        //TheSHLChunk->addUniformVariable("Color1",Vec4f(0.0f,1.0f,0.0f,1.0f));
        //TheSHLChunk->addUniformVariable("Color2",Vec4f(1.0f,1.0f,1.0f,1.0f));

        //Shader Parameter Chunk
        SimpleSHLVariableChunkUnrecPtr SHLParameters = SimpleSHLVariableChunk::create();
        //Color Parameter
        SHLParameters->addUniformVariable("Color1",Vec4f(0.0f,1.0f,0.0f,1.0f));
        SHLParameters->addUniformVariable("Color2",Vec4f(1.0f,1.0f,1.0f,1.0f));

        ChunkMaterialUnrecPtr ShaderMaterial = ChunkMaterial::create();
        ShaderMaterial->addChunk(TheSHLChunk);
        ShaderMaterial->addChunk(SHLParameters);

        //Torus Node
        GeometryUnrecPtr TorusGeometry = makeTorusGeo(5.0f,20.0f, 32,32);

        TorusGeometry->setMaterial(ShaderMaterial);

        NodeUnrecPtr TorusNode = Node::create();
        TorusNode->setCore(TorusGeometry);

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

        sceneManager.setRoot(scene);

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

        //Create the Animations

        ShaderVariableVec4fUnrecPtr Color1Parameter;
        ShaderVariableVec4fUnrecPtr Color2Parameter;

        Color1Parameter = dynamic_cast<ShaderVariableVec4f*>(const_cast<ShaderVariable*>(SHLParameters->getVariables()->getVariable("Color1")));
        Color2Parameter = dynamic_cast<ShaderVariableVec4f*>(const_cast<ShaderVariable*>(SHLParameters->getVariables()->getVariable("Color2")));
        commitChanges();

        AnimationUnrecPtr TheAnimation = setupAnimation(Color1Parameter, "value");
        TheAnimation->attachUpdateProducer(TutorialWindow);
        TheAnimation->start();

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

        //Main Loop
        TutorialWindow->mainLoop();
    }

    osgExit();

    return 0;
}
Exemplo n.º 15
0
// SHUFFLE all these functions around, the order is just plain stupid
void BookmarkInfoWidget::showBookmark(const KBookmark &bk)
{
    // Fast exit if already shown, otherwise editing a title leads to a command after each keypress
    if (m_bk == bk)
        return;

    commitChanges();
    m_bk = bk;

    if (m_bk.isNull()) {
        // all read only and blank

        m_title_le->setReadOnly(true);
        m_title_le->setText(QString());

        m_url_le->setReadOnly(true);
        m_url_le->setText(QString());

        m_comment_le->setReadOnly(true);
        m_comment_le->setText(QString());

        m_visitdate_le->setReadOnly(true);
        m_visitdate_le->setText(QString());

        m_credate_le->setReadOnly(true);
        m_credate_le->setText(QString());

        m_visitcount_le->setReadOnly(true);
        m_visitcount_le->setText(QString());

        return;
    }

    // read/write fields
    m_title_le->setReadOnly( (bk.isSeparator()|| !bk.hasParent() )? true : false);
    if (bk.fullText() != m_title_le->text())
        m_title_le->setText(bk.fullText());

    m_url_le->setReadOnly(bk.isGroup() || bk.isSeparator());
    if (bk.isGroup()) {
         m_url_le->setText(QString());
    }
    else {
        // Update the text if and only if the text represents a different URL to that
        // of the current bookmark - the old method, "m_url_le->text() != bk.url().pathOrUrl()",
        // created difficulties due to the ambiguity of converting URLs to text. (#172647)
        if (QUrl::fromUserInput(m_url_le->text()) != bk.url()) {
            const int cursorPosition = m_url_le->cursorPosition();
            m_url_le->setText(bk.url().url(QUrl::PreferLocalFile));
            m_url_le->setCursorPosition(cursorPosition);
        }
    }

    m_comment_le->setReadOnly((bk.isSeparator()|| !bk.hasParent()) ? true : false );
    QString commentText = bk.description();
    if (m_comment_le->text() != commentText) {
        const int cursorPosition = m_comment_le->cursorPosition();
        m_comment_le->setText(commentText);
        m_comment_le->setCursorPosition(cursorPosition);
    }

    // readonly fields
    updateStatus();

}
Exemplo n.º 16
0
void Manipulator::onCreate(const Manipulator* source)
{
    Inherited::onCreate(source);

    SimpleMaterialUnrecPtr pMat;

//    SimpleMaterial *simpleMat;
    Geometry       *geo;

    setExternalUpdateHandler(NULL);

    // add a name attachment
    NameUnrecPtr nameN = Name::create();
    nameN->editFieldPtr()->setValue("XManipulator");
    addAttachment(nameN);

    // make the axis lines
    NodeUnrecPtr pNode = makeCoordAxis(getLength()[0], 2.0, false);
    setAxisLinesN(pNode);

    // make the red x-axis transform and handle

    pNode = Node::create();
    setTransXNode(pNode);
    OSG::ComponentTransformUnrecPtr transHandleXC = ComponentTransform::create();

    pNode = makeHandleGeo();
    setHandleXNode(pNode);
    pMat = SimpleMaterial::create();
    setMaterialX  (pMat );

    getTransXNode()->setCore (transHandleXC   );
    getTransXNode()->addChild(getHandleXNode());

    transHandleXC->setTranslation(Vec3f(getLength()[0], 0, 0)                   );
    transHandleXC->setRotation   (Quaternion(Vec3f(0, 0, 1), osgDegree2Rad(-90)));

    pMat->setDiffuse(Color3f(1, 0, 0));
    pMat->setLit    (true            );

    geo = dynamic_cast<Geometry *>(getHandleXNode()->getCore());
    geo->setMaterial(pMat);

    //
    // make the green y-axis transform and handle

    pNode = Node::create();
    setTransYNode(pNode);
    OSG::ComponentTransformUnrecPtr transHandleYC = ComponentTransform::create();
    pNode = makeHandleGeo();
    setHandleYNode(pNode);
    pMat = SimpleMaterial::create();
    setMaterialY(pMat);

    getTransYNode()->setCore (transHandleYC   );
    getTransYNode()->addChild(getHandleYNode());

    transHandleYC->setTranslation(Vec3f(0, getLength()[1], 0)                    );
//    transHandleYC->setRotation   ( Quaternion(Vec3f(0, 0, 1), osgDegree2Rad(-90)));

    pMat->setDiffuse(Color3f(0, 1, 0));
    pMat->setLit    (true            );

    geo = dynamic_cast<Geometry *>(getHandleYNode()->getCore());
    geo->setMaterial(pMat);

    //
    // make the blue z-axis transform and handle

    pNode = Node::create();
    setTransZNode(pNode);
    OSG::ComponentTransformUnrecPtr transHandleZC = ComponentTransform::create();
    pNode = makeHandleGeo();
    setHandleZNode(pNode);
    pMat = SimpleMaterial::create();
    setMaterialZ  (pMat);

    getTransZNode()->setCore (transHandleZC   );
    getTransZNode()->addChild(getHandleZNode());

    transHandleZC->setTranslation(Vec3f(0, 0, getLength()[2])                  );
    transHandleZC->setRotation   (Quaternion(Vec3f(1, 0, 0), osgDegree2Rad(90)));

    pMat->setDiffuse(Color3f(0, 0, 1));
    pMat->setLit    (true            );

    geo = dynamic_cast<Geometry *>(getHandleZNode()->getCore());
    geo->setMaterial(pMat);

    //
    // make the yellow pivot transform and handle

    pNode = Node::create();
    setPivotNode(pNode);
    OSG::ComponentTransformUnrecPtr transHandlePivotC = ComponentTransform::create();
    pNode = makeSphere(2, 0.05f);
    setHandlePNode(pNode);
    pMat = SimpleMaterial::create();
    setMaterialPivot  (pMat);

    getPivotNode()->setCore (transHandlePivotC   );
    getPivotNode()->addChild(getHandlePNode());

    transHandlePivotC->setTranslation(Vec3f(0, 0, 0));

    pMat->setDiffuse(Color3f(1, 1, 0));
    pMat->setLit    (true            );

    geo = dynamic_cast<Geometry *>(getHandlePNode()->getCore());
    geo->setMaterial(pMat);

    if (!getEnablePivot())
    {
        getPivotNode()->setTravMask(0x0);
    }

    commitChanges();
}
Exemplo n.º 17
0
static void display(void)
{
    commitChanges();
    mgr->redraw();
}
// 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);

    if(argc >= 2)
        scene = SceneFileHandler::the()->read(argv[1]);
    else
        scene = SceneFileHandler::the()->read("Data/tie.wrl");
    
    if(scene == NULL)
        scene = makeTorus(0.3, 4, 16, 64);

    // init material
    phong_chunk = createPhongShaderMaterial();
    
    // get all the Materials of the current scene
    getAllMaterials(scene, materials);

    // add the phong material chunk to every found material
    for(int i = 0; i < materials.size(); ++i)
    {
        (materials[i])->addChunk(phong_chunk);
    }
    phong_active = true;

    // open a new scope, because the pointers below should go out of scope
    // before entering glutMainLoop.
    // Otherwise OpenSG will complain about objects being alive after shutdown.
    {
        // the connection between GLUT and OpenSG
        GLUTWindowRefPtr gwin = GLUTWindow::create();
        gwin->setGlutId(winid);
        gwin->init     (     );
        
        // create the SimpleSceneManager helper
        _mgr = new SimpleSceneManager;
        
        // tell the manager what to manage
        _mgr->setWindow      (gwin );
        _mgr->setRoot        (scene);
        _mgr->turnHeadlightOn(     );
        
        commitChanges();
        
        // show the whole scene
        _mgr->showAll();
        
        // create a gradient background.
        GradientBackgroundRefPtr gbg = GradientBackground::create();
        gbg->clearLines();
        gbg->addLine(Color3f(0.7, 0.7, 0.8), 0);
        gbg->addLine(Color3f(0.0, 0.1, 0.3), 1);
        
        //set gradient background
        ViewportRefPtr vp = gwin->getPort(0);
        vp->setBackground(gbg);
        
        commitChanges();
    }

    // GLUT main loop
    glutMainLoop();

    return 0;
}
Exemplo n.º 19
0
// Initialize OpenSG and set up the scene
int main(int argc, char **argv)
{
    //Set the number of aspects
    ThreadManager::setNumAspects(2);
    ChangeList::setReadWriteDefault(true);

    // OSG init
    osgInit(argc,argv);

    {
        // Set up Window
        TutorialWindow = createNativeWindow();
        TutorialWindow->setUseCallbackForDraw(true);
        TutorialWindow->setUseCallbackForReshape(true);

        //Initialize Window
        TutorialWindow->initWindow();


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

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

        //Attach to events
        TutorialWindow->connectMousePressed(boost::bind(mousePressed, _1, &sceneManager));
        TutorialWindow->connectMouseReleased(boost::bind(mouseReleased, _1, &sceneManager));
        TutorialWindow->connectMouseMoved(boost::bind(mouseMoved, _1, &sceneManager));
        TutorialWindow->connectMouseDragged(boost::bind(mouseDragged, _1, &sceneManager));
        
        //Torus Material
        MaterialRecPtr TheTorusMaterial = SimpleMaterial::create();
        dynamic_pointer_cast<SimpleMaterial>(TheTorusMaterial)->setAmbient(Color3f(0.2,0.2,0.2));
        dynamic_pointer_cast<SimpleMaterial>(TheTorusMaterial)->setDiffuse(Color3f(0.7,0.7,0.7));
        dynamic_pointer_cast<SimpleMaterial>(TheTorusMaterial)->setSpecular(Color3f(0.7,0.7,0.7));
        dynamic_pointer_cast<SimpleMaterial>(TheTorusMaterial)->setShininess(100.0f);

        //Torus Geometry
        GeometryRecPtr TorusGeometry = makeTorusGeo(.5, 2, 32, 32);
        TorusGeometry->setMaterial(TheTorusMaterial);
        
        NodeRecPtr TorusGeometryNode = Node::create();
        TorusGeometryNode->setCore(TorusGeometry);

        //Make Torus Node
        NodeRecPtr TorusNode = Node::create();
        TransformRecPtr TorusNodeTrans = Transform::create();
        setName(TorusNodeTrans, std::string("TorusNodeTransformationCore"));

        TorusNode->setCore(TorusNodeTrans);
        TorusNode->addChild(TorusGeometryNode);

        //Make Main Scene Node
        NodeRecPtr scene = Node::create();
        ComponentTransformRecPtr Trans = ComponentTransform::create();
        setName(Trans, std::string("MainTransformationCore"));

        scene->setCore(Trans);
        scene->addChild(TorusNode);

        AnimationRecPtr TheAnimation = setupAnimation(TorusNodeTrans, TutorialWindow);

        TutorialWindow->connectKeyPressed(boost::bind(keyPressed, _1, TheAnimation.get(), TutorialWindow.get()));
        
        TheAnimation->connectAnimationStarted(boost::bind(animationStarted, _1));
        TheAnimation->connectAnimationStopped(boost::bind(animationStopped, _1));
        TheAnimation->connectAnimationPaused(boost::bind(animationPaused, _1));
        TheAnimation->connectAnimationUnpaused(boost::bind(animationUnpaused, _1));
        TheAnimation->connectAnimationEnded(boost::bind(animationEnded, _1));
        TheAnimation->connectAnimationCycled(boost::bind(animationCycled, _1));

        commitChanges();

        // tell the manager what to manage
        sceneManager.setRoot  (scene);

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

        Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
        Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
        TutorialWindow->openWindow(WinPos,
                WinSize,
                "OpenSG 01Animation Window");
        
        // store a pointer to the application thread
        ApplicationThread = dynamic_cast<OSG::Thread *>(OSG::ThreadManager::getAppThread());
        
        //create the thread that will run generation of new matrices
        RenderThread =
            OSG::dynamic_pointer_cast<OSG::Thread>(
                OSG::ThreadManager::the()->getThread("render", true));
        
        //Start the render thread on aspect 1
        RenderThread->runFunction(draw, 1, static_cast<void *>(&sceneManager));

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

        //Stop the render thread
        RenderThread->terminate();
    }

    osgExit();

    return 0;
}
Exemplo n.º 20
0
/*!\fn void FieldAnimation::setAnimatedField(FieldContainerUnrecPtr TheContainer, const std::string& FieldName)
 *
 * \brief Attach to the SingleField of a #OSG::FieldContainer.
 *
 * If TheContainer is NULL or there is no SingleField by the
 * given name on the container, then no changes are made.
 *
 * \param TheContainer The container to attach to.
 * \param FieldName The name of the field on the given container to attach
 * to.
 */
void FieldAnimation::setAnimatedField(FieldContainerUnrecPtr TheContainer, const std::string& FieldName)
{
    setFieldName( FieldName );
    setContainer( TheContainer );
    commitChanges();
}
void ColorDisplayFilter::process(DisplayFilterStageData *pData)
{
    SimpleSHLChunk *pShader = pData->getColorFilterShader();

    if(pShader == NULL || this->getFilterShader() != pShader)
    {
        pShader = this->getFilterShader();

        OSG_ASSERT(pShader != NULL);
        
        ChunkMaterial *pCMat = pData->getBaseMaterial();

        OSG_ASSERT(pCMat != NULL);

        pCMat->addChunk(pShader);

        commitChanges();

        pData->setColorFilterShader(pShader);
    }



    TextureObjChunk *pColTex = pData->getColorFilterTexture();

    if(pData->getInitColTableFrom() != this)
    {
        if(pColTex == NULL)
        {
            TextureObjChunkUnrecPtr pTex = TextureObjChunk::createLocal();

            pTex->setMinFilter(GL_LINEAR            );
            pTex->setMagFilter(GL_LINEAR            );
            pTex->setWrapS    (GL_CLAMP_TO_EDGE     );
            pTex->setWrapT    (GL_CLAMP_TO_EDGE     );
            pTex->setWrapR    (GL_CLAMP_TO_EDGE     );

            pData->setColorFilterTexture(pTex);

            ChunkMaterial *pCMat = pData->getBaseMaterial();
            
            OSG_ASSERT(pCMat != NULL);
            
            pCMat->addChunk(pTex, 1);

            pColTex = pTex;
        }

        pData->setInitColTableFrom(this);

        pColTex->setImage(this->getTableImage());

        commitChanges();
    }

    OSG_ASSERT(pShader != NULL);
    OSG_ASSERT(pColTex != NULL);

    pShader->setIgnore(false);
    pColTex->setIgnore(false);
}
Exemplo n.º 22
0
/*!\fn void FieldAnimation::setAnimatedField(FieldContainerUnrecPtr TheContainer, UInt32 FieldID)
 *
 * \brief Attach to the SingleField of a #OSG::FieldContainer.
 *
 * If TheContainer is NULL or there is no SingleField with the
 * given FieldID on the container, then no changes are made.
 *
 * \param TheContainer The container to attach to.
 * \param FieldID The ID of the field on the given container to attach
 * to.
 */
void FieldAnimation::setAnimatedField(FieldContainerUnrecPtr TheContainer, UInt32 FieldID)
{
    setFieldId( FieldID );
    setContainer( TheContainer );
    commitChanges();
}
void ShaderShadowMapEngine::handleDirectionalLightEnter(
    DirectionalLight *dirL, RenderAction *ract, SSMEngineData *data)
{
    RenderPartition *parentPart = ract      ->getActivePartition();
    FrustumVolume    camFrust   = parentPart->getFrustum        ();

    Matrix matEyeToWorld  (parentPart->getCameraToWorld());
    Matrix matWorldToLight;
    Matrix matEyeToLight;

    calcDirectionalLightMatrices(matWorldToLight, matEyeToLight,
                                 dirL,            matEyeToWorld );

    // place light camera outside the scene bounding box:
    //  - project camera frustum and scene bounding box into a
    //    coordinate system where the directional light shines
    //    along the -z axis.
    //  - compute 2 AABBs that contain the projected frustum and
    //    scene BB
    //  - width and height of the ortho projection are determined from
    //    the frustum AABB, while near and far are determined by the
    //    scene AABB (offscreen objects cast shadows into the view volume)
          Pnt3f      camVerts  [10];
          Pnt3f      sceneVerts[10];
    const Matrix    &matSceneToWorld = ract->topMatrix ();
          BoxVolume  sceneBB         = ract->getActNode()->getVolume();

    camFrust.getCorners(camVerts  [0], camVerts  [1],
                        camVerts  [2], camVerts  [3],
                        camVerts  [4], camVerts  [5],
                        camVerts  [6], camVerts  [7] );
    sceneBB .getCorners(sceneVerts[0], sceneVerts[1],
                        sceneVerts[2], sceneVerts[3],
                        sceneVerts[4], sceneVerts[5],
                        sceneVerts[6], sceneVerts[7] );

    camVerts  [8].setValues(TypeTraits<Real32>::getMax(),
                            TypeTraits<Real32>::getMax(),
                            TypeTraits<Real32>::getMax() );
    camVerts  [9].setValues(TypeTraits<Real32>::getMin(),
                            TypeTraits<Real32>::getMin(),
                            TypeTraits<Real32>::getMin() );
    sceneVerts[8].setValues(TypeTraits<Real32>::getMax(),
                            TypeTraits<Real32>::getMax(),
                            TypeTraits<Real32>::getMax() );
    sceneVerts[9].setValues(TypeTraits<Real32>::getMin(),
                            TypeTraits<Real32>::getMin(),
                            TypeTraits<Real32>::getMin() );

    for(UInt32 i = 0; i < 8; ++i)
    {
        matWorldToLight.mult(camVerts  [i], camVerts  [i]);

        matSceneToWorld.mult(sceneVerts[i], sceneVerts[i]);
        matWorldToLight.mult(sceneVerts[i], sceneVerts[i]);

        camVerts  [8][0] = osgMin(camVerts  [8][0], camVerts  [i][0]);
        camVerts  [9][0] = osgMax(camVerts  [9][0], camVerts  [i][0]);
        camVerts  [8][1] = osgMin(camVerts  [8][1], camVerts  [i][1]);
        camVerts  [9][1] = osgMax(camVerts  [9][1], camVerts  [i][1]);

        sceneVerts[8][0] = osgMin(sceneVerts[8][0], sceneVerts[i][0]);
        sceneVerts[9][0] = osgMax(sceneVerts[9][0], sceneVerts[i][0]);
        sceneVerts[8][1] = osgMin(sceneVerts[8][1], sceneVerts[i][1]);
        sceneVerts[9][1] = osgMax(sceneVerts[9][1], sceneVerts[i][1]);
        sceneVerts[8][2] = osgMin(sceneVerts[8][2], sceneVerts[i][2]);
        sceneVerts[9][2] = osgMax(sceneVerts[9][2], sceneVerts[i][2]);
    }

    // these points are the corners of the ortho shadow view volume
    Pnt3f lightMin(osgMax(camVerts[8][0], sceneVerts[8][0]),
                   osgMax(camVerts[8][1], sceneVerts[8][1]),
                   -sceneVerts[9][2]);
    
    Pnt3f lightMax(osgMin(camVerts[9][0], sceneVerts[9][0]),
                   osgMin(camVerts[9][1], sceneVerts[9][1]),
                   -sceneVerts[8][2]);

    // enlarge by 2% in x, y, z direction
    lightMin[0] -= (lightMax[0] - lightMin[0]) * 0.01f;
    lightMin[1] -= (lightMax[1] - lightMin[1]) * 0.01f; 
    lightMin[2] -= (lightMax[2] - lightMin[2]) * 0.01f;

    lightMax[0] += (lightMax[0] - lightMin[0]) * 0.01f;
    lightMax[1] += (lightMax[1] - lightMin[1]) * 0.01f;
    lightMax[2] += (lightMax[2] - lightMin[2]) * 0.01f;

    Matrix matLightProj;
    Matrix matLightProjTrans;

    MatrixOrthogonal(matLightProj,
                     lightMin[0], lightMax[0],
                     lightMin[1], lightMax[1],
                     lightMin[2], lightMax[2] );

    updateShadowTexImage  (data);
    updateShadowTexBuffers(data);
    updateRenderTargets   (data);

    Int32 shadowTexUnit = (this->getForceTextureUnit() > 0) ?
                           this->getForceTextureUnit()      : 7;

    ShaderProgram *shadowFP = this->getShadowFragmentProgram();

    if(shadowFP == NULL)
    {
        ShaderProgramUnrecPtr newShadowFP = ShaderProgram::createLocal();
        newShadowFP->setShaderType(GL_FRAGMENT_SHADER);
        newShadowFP->setProgram   (_dirFPCode        );

        newShadowFP->addUniformVariable("SSME_matEyeToLight", matEyeToLight);
        newShadowFP->addUniformVariable("SSME_matLightProj",  matLightProj );
        newShadowFP->addUniformVariable("SSME_texShadow",     shadowTexUnit);

        this->setShadowFragmentProgram(newShadowFP);
        shadowFP = newShadowFP;
    }
    else
    {
        shadowFP->updateUniformVariable("SSME_matEyeToLight", matEyeToLight);
        shadowFP->updateUniformVariable("SSME_matLightProj",  matLightProj );
    }

    commitChanges();

    this->pushPartition(ract);
    {
        RenderPartition   *part   = ract->getActivePartition( );
        Window            *win    = ract->getWindow         ( );
        FrameBufferObject *target = data->getRenderTargets  (0);
        Background        *back   = data->getBackground     ( );

        part->setRenderTarget(target);
        part->setWindow      (win   );

        part->calcViewportDimension(0.f, 0.f, 1.f, 1.f,
                                    target->getWidth (),
                                    target->getHeight() );

        part->setupProjection(matLightProj, matLightProjTrans);
        part->setupViewing   (matWorldToLight                );

        part->setNear        (parentPart->getNear());
        part->setFar         (parentPart->getFar ());

        part->calcFrustum    (                     );

        part->setBackground  (back                 );

        // force material for shadow map generation
        part->overrideMaterial(data->getLightPassMaterials(0),
                               ract->getActNode           ( ) );

        this->recurseFrom(ract, dirL);
        ract->useNodeList(false     );

        // undo override
        part->overrideMaterial(NULL,
                               ract->getActNode           ( ) );
    }
    this->popPartition(ract);
}
Exemplo n.º 24
0
pp_int32 DialogResample::handleEvent(PPObject* sender, PPEvent* event)
{
	if (event->getID() == eKeyDown)
	{
		pp_uint16 keyCode = *((pp_uint16*)event->getDataPtr());
		if (keyCode == VK_TAB)
		{
			switchListBox();
			event->cancel();
		}
	}
	else if (event->getID() == eCommand || event->getID() == eCommandRepeat)
	{
		switch (reinterpret_cast<PPControl*>(sender)->getID())
		{
			case PP_MESSAGEBOX_BUTTON_YES:
			{
				commitChanges();
				break;
			}

			case MESSAGEBOX_BUTTON_INCREASE_VALUEONE:
			{
				relnote++;
				toC4Speed();
				calcSize();
				updateListBoxes();
				parentScreen->paintControl(messageBoxContainerGeneric);
				break;
			}

			case MESSAGEBOX_BUTTON_DECREASE_VALUEONE:
			{
				relnote--;
				toC4Speed();
				calcSize();
				updateListBoxes();
				parentScreen->paintControl(messageBoxContainerGeneric);
				break;
			}

			case MESSAGEBOX_BUTTON_INCREASE_VALUETWO:
			{
				finetune++;
				toC4Speed();
				calcSize();
				updateListBoxes();
				parentScreen->paintControl(messageBoxContainerGeneric);
				break;
			}

			case MESSAGEBOX_BUTTON_DECREASE_VALUETWO:
			{
				finetune--;
				toC4Speed();
				calcSize();
				updateListBoxes();
				parentScreen->paintControl(messageBoxContainerGeneric);
				break;
			}

			case MESSAGEBOX_BUTTON_INCREASE_VALUETHREE:
			{
				c4spd++;
				fromC4Speed();
				calcSize();
				updateListBoxes();
				parentScreen->paintControl(messageBoxContainerGeneric);
				break;
			}

			case MESSAGEBOX_BUTTON_DECREASE_VALUETHREE:
			{
				c4spd--;
				fromC4Speed();
				calcSize();
				updateListBoxes();
				parentScreen->paintControl(messageBoxContainerGeneric);
				break;
			}
			
			case MESSAGEBOX_CONTROL_USER1:
			{	
				if (event->getID() != eCommand)
					break;
				
				interpolationType = (interpolationType + 1) % resamplerHelper->getNumResamplers();
				
				PPButton* button = static_cast<PPButton*>(messageBoxContainerGeneric->getControlByID(MESSAGEBOX_CONTROL_USER1));
				button->setText(resamplerHelper->getResamplerName(interpolationType, true));
				parentScreen->paintControl(messageBoxContainerGeneric);							
				break;
			}

			case MESSAGEBOX_CONTROL_USER2:
			{
				if (event->getID() != eCommand)
					break;
					
				this->adjustFtAndRelnote = reinterpret_cast<PPCheckBox*>(sender)->isChecked();
				break;
			}

		}
	}
	else if (event->getID() == eValueChanged)
	{
		switch (reinterpret_cast<PPControl*>(sender)->getID())
		{
			case MESSAGEBOX_LISTBOX_VALUE_ONE:
			{
				const PPString* str = *(reinterpret_cast<PPString* const*>(event->getDataPtr()));
				setRelNote((pp_int32)atoi(*str));
				calcSize();
				updateListBoxes();
				parentScreen->paintControl(messageBoxContainerGeneric);
				break;
			}

			case MESSAGEBOX_LISTBOX_VALUE_TWO:
			{
				const PPString* str = *(reinterpret_cast<PPString* const*>(event->getDataPtr()));
				setFineTune((pp_int32)atoi(*str));
				calcSize();
				updateListBoxes();
				parentScreen->paintControl(messageBoxContainerGeneric);
				break;
			}

			case MESSAGEBOX_LISTBOX_VALUE_THREE:
			{
				const PPString* str = *(reinterpret_cast<PPString* const*>(event->getDataPtr()));
				setC4Speed((float)atof(*str));
				calcSize();
				updateListBoxes();
				parentScreen->paintControl(messageBoxContainerGeneric);
				break;
			}
		}
	}
	
	return PPDialogBase::handleEvent(sender, event);
}
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

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

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

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

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

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

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

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

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

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


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

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

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

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

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

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


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

    mgr->setRoot(scene);

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


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

    commitChanges();

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

    osgExit();

    return 0;
}
Exemplo n.º 26
0
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);
    
    {
        // Set up Window
        WindowEventProducerRecPtr TutorialWindow = createNativeWindow();
        TutorialWindow->initWindow();

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

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


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

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

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

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

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

          Create an Button Component and
          a simple Font.
          See 17Label_Font for more
          information about Fonts.

         ******************************************************/
        ButtonRefPtr ExampleButton = OSG::Button::create();

        UIFontRefPtr ExampleFont = OSG::UIFont::create();
        ExampleFont->setSize(16);

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

          Edit the Button's characteristics.
            Note: the first 4 functions can
            be used with any Component and 
            are not specific to Button.

            -setMinSize(Vec2f): Determine the 
            Minimum Size of the Component.
            Some Layouts will automatically
            resize Components; this prevents
            the Size from going below a
            certain value.
            -setMaxSize(Vec2f): Determine the 
            Maximum Size of the Component.
            -setPreferredSize(Vec2f): Determine
            the Preferred Size of the Component.
            This is what the Component will
            be displayed at unless changed by
            another Component (such as a 
            Layout).
            -setToolTipText("Text"): Determine
            what text is displayed while
            Mouse is hovering above Component.
            The word Text will be displayed
            in this case.

            Functions specfic to Button:
            -setText("DesiredText"): Determine 
            the Button's text.  It will read
            DesiredText in this case.
            -setFont(FontName): Determine the 
            Font to be used on the Button.
            -setTextColor(Color4f): Determine the
            Color for the text.
            -setRolloverTextColor(Color4f): Determine
            what the text Color will be when
            the Mouse Cursor is above the 
            Button.
            -setActiveTextColor(Color4f): Determine
            what the text Color will be when
            the Button is pressed (denoted by
            Active).
            -setAlignment(Vec2f):
            Determine the Vertical Alignment
            of the text.  The value is 
            in [0.0, 1.0].

         ******************************************************/
        ExampleButton->setMinSize(Vec2f(50, 25));
        ExampleButton->setMaxSize(Vec2f(200, 100));
        ExampleButton->setPreferredSize(Vec2f(100, 50));
        ExampleButton->setToolTipText("Button 1 ToolTip");

        ExampleButton->setText("Button 1");
        ExampleButton->setFont(ExampleFont);
        ExampleButton->setTextColor(Color4f(1.0, 0.0, 0.0, 1.0));
        ExampleButton->setRolloverTextColor(Color4f(1.0, 0.0, 1.0, 1.0));
        ExampleButton->setActiveTextColor(Color4f(1.0, 0.0, 0.0, 1.0));
        ExampleButton->setAlignment(Vec2f(1.0,0.0));

        // Create an Action and assign it to ExampleButton
        // This Class is defined above, and will cause the output
        // window to display "Button 1 Action" when pressed
        ExampleButton->connectActionPerformed(boost::bind(actionPerformed, _1));

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

          Create a ToggleButton and determine its 
          characteristics.  ToggleButton inherits
          off of Button, so all characteristsics
          used above can be used with ToggleButtons
          as well.

          The only difference is that when pressed,
          ToggleButton remains pressed until pressed 
          again.

          -setSelected(bool): Determine whether the 
          ToggleButton is Selected (true) or
          deselected (false).  

         ******************************************************/
        ToggleButtonRefPtr ExampleToggleButton = OSG::ToggleButton::create();

        ExampleToggleButton->setSelected(false);
        ExampleToggleButton->setText("ToggleMe");
        ExampleToggleButton->setToolTipText("Toggle Button ToolTip");

        //Button with Image
        ButtonRefPtr ExampleDrawObjectButton = OSG::Button::create();
        ExampleDrawObjectButton->setDrawObjectToTextAlignment(Button::ALIGN_DRAW_OBJECT_RIGHT_OF_TEXT);
        ExampleDrawObjectButton->setText("Icon");

        ExampleDrawObjectButton->setImage(std::string("./Data/Icon.png"));
        ExampleDrawObjectButton->setActiveImage(std::string("./Data/Icon.png"));
        ExampleDrawObjectButton->setFocusedImage(std::string("./Data/Icon.png"));
        ExampleDrawObjectButton->setRolloverImage(std::string("./Data/Icon.png"));
        ExampleDrawObjectButton->setDisabledImage(std::string("./Data/Icon.png"));

        // Create The Main InternalWindow
        // Create Background to be used with the Main InternalWindow
        ColorLayerRefPtr MainInternalWindowBackground = OSG::ColorLayer::create();
        MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));
        InternalWindowRefPtr MainInternalWindow = OSG::InternalWindow::create();
        LayoutRefPtr MainInternalWindowLayout = OSG::FlowLayout::create();
        MainInternalWindow->pushToChildren(ExampleButton);
        MainInternalWindow->pushToChildren(ExampleToggleButton);
        MainInternalWindow->pushToChildren(ExampleDrawObjectButton);
        MainInternalWindow->setLayout(MainInternalWindowLayout);
        MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
        MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
        MainInternalWindow->setScalingInDrawingSurface(Vec2f(0.5f,0.5f));
        MainInternalWindow->setDrawTitlebar(false);
        MainInternalWindow->setResizable(false);

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

        TutorialDrawingSurface->openWindow(MainInternalWindow);

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

        TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);

        sceneManager.setRoot(scene);

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


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

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

        //Attach key controls

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

        commitChanges();

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

    osgExit();

    return 0;
}
Exemplo n.º 27
0
//----------------------------
// Function name: read
//----------------------------
//
//Parameters:
//p: Scene &image, const char *fileName
//GlobalVars:
//g:
//Returns:
//r:bool
// Caution
//c:
//Assumations:
//a:
//Describtions:
//d: read the image from the given file
//SeeAlso:
//s:
//
//------------------------------
NodeTransitPtr OBJSceneFileType::read(      std::istream &is,
                                      const Char8        *,
                                            Resolver        ) const
{
    NodeUnrecPtr rootPtr, nodePtr;
    std::string elem;
    std::map<std::string, DataElem>::const_iterator elemI;
    Vec3f vec3r;
    Pnt3f pnt3r;
    Vec2f vec2r;
    Real32 x,y,z;
    GeoPnt3fPropertyUnrecPtr coordPtr    = GeoPnt3fProperty::create();
    GeoVec2fPropertyUnrecPtr texCoordPtr = GeoVec2fProperty::create();
    GeoVec3fPropertyUnrecPtr normalPtr   = GeoVec3fProperty::create();
    GeometryUnrecPtr geoPtr;
    GeoIntegralPropertyUnrecPtr posIndexPtr, texIndexPtr, normalIndexPtr;
    GeoIntegralPropertyUnrecPtr lensPtr;
    GeoIntegralPropertyUnrecPtr typePtr;
    DataElem dataElem;
    DataElem lastDataElem;
    Char8 strBuf[8192], *token, *nextToken;
    Int32 strBufSize = sizeof(strBuf)/sizeof(Char8);
    Int32 index, posIndex = 0, indexType;
    Int32 i,j,n,primCount[3];
    std::list<Mesh> meshList;
    std::map<std::string, SimpleTexturedMaterialUnrecPtr> mtlMap;
    std::map<std::string, SimpleTexturedMaterialUnrecPtr>::iterator mtlI;
    Mesh emptyMesh;
    Face emptyFace;
    TiePoint  emptyTie;
    Int32 indexMask, meshIndexMask;
    std::list<Face>::iterator faceI;
    std::list<Mesh>::iterator meshI;
    bool isSingleIndex;

    // create the first mesh entry
    meshList.push_back(emptyMesh);
    meshI = meshList.begin();

    if(is)
    {
        primCount[0] = 0;
        primCount[1] = 0;
        primCount[2] = 0;

        for(is >> elem; is.eof() == false; is >> elem)
        {
            if(elem[0] == '#' || elem[0] == '$')
            {
                is.ignore(INT_MAX, '\n');
            }
            else
            {
                SceneFileHandler::the()->updateReadProgress();

                elemI = _dataElemMap.find(elem);
                dataElem = ((elemI == _dataElemMap.end()) ?
                        UNKNOWN_DE : elemI->second );
                switch (dataElem)
                {
                    case OBJECT_DE:
                    case GROUP_DE:
                    case SMOOTHING_GROUP_DE:
                        is.ignore(INT_MAX, '\n');
                    break;
                    case VERTEX_DE:
                        primCount[0]++;
                        is >> x >> y >> z;
                        pnt3r.setValues(x,y,z);
                        coordPtr->addValue(pnt3r);
                    break;
                    case VERTEX_TEXTURECOORD_DE:
                        primCount[1]++;
                        is >> x >> y;
                        vec2r.setValues(x,y);
                        texCoordPtr->addValue(vec2r);
                    break;
                    case VERTEX_NORMAL_DE:
                        primCount[2]++;
                        is >> x >> y >> z;
                        vec3r.setValues(x,y,z);
                        normalPtr->addValue(vec3r);
                    break;
                    case LIB_MTL_DE:
                        is >> elem;
                        readMTL ( elem.c_str(), mtlMap );
                        is.ignore(INT_MAX, '\n');
                    break;
                    case USE_MTL_DE:
                        is >> elem;
                        if (meshI->faceList.empty() == false)
                        {
                            meshList.push_front(emptyMesh);
                            meshI = meshList.begin();
                        }
                        mtlI = mtlMap.find(elem);
                        if (mtlI == mtlMap.end())
                        {
                            FFATAL (("Unkown mtl %s\n", elem.c_str()));
                        }
                        else
                        {
                            meshI->mtlPtr = mtlI->second;
                        }
                    break;
                    case FACE_DE:
                        meshI->faceList.push_front(emptyFace);
                        faceI = meshI->faceList.begin();
                        is.get(strBuf,strBufSize);
                        token = strBuf;
                        indexType = 0;
                        while(token && *token)
                        {
                            // some tools use line continuation for long
                            // face definitions - these use a \ at the line
                            // end
                            if(*token == '\\')
                            {
                                is.ignore(1, '\n');
                                is.get(strBuf,strBufSize);
                                token = strBuf;
                                indexType = 0;
                                continue;
                            }
                            for (; *token == '/'; token++)
                                indexType++;
                            for (; isspace(*token); token++)
                                indexType = 0;
                            index = strtol(token, &nextToken, 10);
                            if (token == nextToken)
                                break;
                            if (indexType == 0)
                                faceI->tieVec.push_back(emptyTie);
                            if (index >= 0)
                                index--;
                            else
                                index =  primCount[indexType] + index;
                            faceI->tieVec.back().index[indexType] = index;
                            token = nextToken;
                        }
                    break;

                    case UNKNOWN_DE:
                    default:
                        // don't warn about 3rd tex coord
                        if(lastDataElem != VERTEX_TEXTURECOORD_DE)
                        {
                            FWARNING (( "Unkown obj data elem: %s\n", 
                                        elem.c_str()));
                        }
                        is.ignore(INT_MAX, '\n');
                    break;
                }

                lastDataElem = dataElem;
            }
        }

#if 0
        std::cerr << "------------------------------------------------" << std::endl;
        i = 0;
        for (meshI = meshList.begin(); meshI != meshList.end(); meshI++)
        {
            std::cerr << "Mesh " << i << " faceCount :"
                      << meshI->faceList.size() << std::endl;
            j = 0 ;
            for ( faceI = meshI->faceList.begin(); faceI != meshI->faceList.end();
                  faceI++)
            std::cerr << "MESH " <<  i << "face: " << j++ << "tie num: "
                      << faceI->tieVec.size() << std::endl;
            i++;
        }
        std::cerr << "------------------------------------------------" << std::endl;
#endif

        // create Geometry objects
        for (meshI = meshList.begin(); meshI != meshList.end(); meshI++)
        {
            geoPtr   = Geometry::create();
            posIndexPtr = NULL;
            texIndexPtr = NULL;
            normalIndexPtr = NULL;
            lensPtr  = GeoUInt32Property::create();
            typePtr  = GeoUInt8Property ::create();

            // create and check mesh index mask
            meshIndexMask = 0;
            isSingleIndex = true;
            if ( meshI->faceList.empty() == false)
            {
                for ( faceI = meshI->faceList.begin();
                  faceI != meshI->faceList.end(); faceI++)
                {
                    indexMask = 0;
                    n = UInt32(faceI->tieVec.size());
                    for (i = 0; i < n; i++)
                    {
                        for (j = 0; j < 3; j++)
                        {
                            if ((index = (faceI->tieVec[i].index[j])) >= 0)
                            {
                                indexMask |= (1 << j);
                                if (j)
                                    isSingleIndex &= (posIndex == index);
                                else
                                    posIndex = index;
                            }
                        }
                    }
                    if (meshIndexMask == 0)
                    {
                        meshIndexMask = indexMask;
                    }
                    else if (meshIndexMask != indexMask)
                    {
                        // consider this real-world example:
                       // [...]
                       // f 1603//1747 1679//1744 1678//1743
                       // s 1
                       // f 9/1/10 5/2/9 1680/3/1748 1681/4/174
                       // [...]
                       // Some faces contain texture coords and others do not.
                       // The old version did just skip this geometry.
                       // This version should continue if there's at least
                       // the vertex index
                       // I've seen the change in the maskIndex only after a smooth group,
                       // so it's perhaps smarter to not ignore the smooth group further up in this code
                       if( !(indexMask & 1) )
                       {
                         // if there are vertex indices there's no reason to get in here
                          FFATAL (( "IndexMask unmatch, can not create geo\n"));
                          meshIndexMask = 0;
                          break;
                       }
                       else
                       {
                         // consider the minimum similarities of mesh masks
                         meshIndexMask &= indexMask;
                       }
                    }
                }
            }
            else
            {
                FWARNING (("Mesh with empty faceList\n"));
            }

            // fill the geo properties
            if (meshIndexMask)
            {
                geoPtr->setPositions ( coordPtr );
                posIndexPtr = GeoUInt32Property::create();
                if(!isSingleIndex)
                    geoPtr->setIndex(posIndexPtr, Geometry::PositionsIndex);
                geoPtr->setLengths   ( lensPtr );
                geoPtr->setTypes     ( typePtr );

                if ( (meshIndexMask & 2) && texCoordPtr->size() > 0 )
                {
                    geoPtr->setTexCoords ( texCoordPtr );
                    texIndexPtr = GeoUInt32Property::create();
                    if(!isSingleIndex)
                        geoPtr->setIndex(texIndexPtr, Geometry::TexCoordsIndex);
                }
                else
                {
                    geoPtr->setTexCoords ( NULL );
                }

                if ( (meshIndexMask & 4) && normalPtr->size() > 0 )
                {
                    geoPtr->setNormals   ( normalPtr );
                    normalIndexPtr = GeoUInt32Property::create();
                    if(!isSingleIndex)
                        geoPtr->setIndex(normalIndexPtr, Geometry::NormalsIndex);
                }
                else
                {
                    geoPtr->setNormals   ( NULL );
                }

                if (meshI->mtlPtr == NULL)
                {
                    meshI->mtlPtr = SimpleTexturedMaterial::create();
                    meshI->mtlPtr->setDiffuse( Color3f( .8f, .8f, .8f ) );
                    meshI->mtlPtr->setSpecular( Color3f( 1.f, 1.f, 1.f ) );
                    meshI->mtlPtr->setShininess( 20.f );
                }
                geoPtr->setMaterial  ( meshI->mtlPtr );

                for ( faceI = meshI->faceList.begin();
                      faceI != meshI->faceList.end(); faceI++)
                {
                    n = UInt32(faceI->tieVec.size());

                    // add the lens entry
                    lensPtr->push_back(n);

                    // add the type entry
                    typePtr->push_back(GL_POLYGON);

                    // create the index values
                    for (i = 0; i < n; i++)
                    {
                        if (isSingleIndex)
                        {
                            posIndexPtr->push_back(faceI->tieVec[i].index[0]);
                        }
                        else
                        {
                            posIndexPtr->push_back(faceI->tieVec[i].index[0]);
                            if(texIndexPtr != NULL)
                                texIndexPtr->push_back(faceI->tieVec[i].index[1]);
                            if(normalIndexPtr != NULL)
                                normalIndexPtr->push_back(faceI->tieVec[i].index[2]);
                        }
                    }
                }

                if(isSingleIndex)
                {
                    geoPtr->setIndex(posIndexPtr, Geometry::PositionsIndex);
                    geoPtr->setIndex(posIndexPtr, Geometry::NormalsIndex  );
                    geoPtr->setIndex(posIndexPtr, Geometry::TexCoordsIndex);
                }

                // need to port the geometry functions ...
                createSharedIndex( geoPtr );

                // check if we have normals
                // need to port the geometry functions ...

                if(geoPtr->getNormals() == NULL)
                    calcVertexNormals(geoPtr);

                // create and link the node
                nodePtr = Node::create();
                nodePtr->setCore( geoPtr );

                if (meshList.size() > 1)
                {
                    if (rootPtr == NULL)
                    {
                        rootPtr = Node::create();

                        GroupUnrecPtr tmpPtr = Group::create();

                        rootPtr->setCore ( tmpPtr );
                        rootPtr->addChild(nodePtr);
                    }
                    else
                    {
                        rootPtr->addChild(nodePtr);
                    }
                }
                else
                {
                    rootPtr = nodePtr;
                }
            }
        }
    }

    SceneFileHandler::the()->updateReadProgress(100);

    commitChanges();

    return NodeTransitPtr(rootPtr);
}
Exemplo n.º 28
0
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    {

    // Set up Window
    TutorialWindow = createNativeWindow();

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

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

    //Initialize Window
    TutorialWindow->initWindow();
    
    //Torus Material
    TheTorusMaterial = SimpleMaterial::create();
    dynamic_pointer_cast<SimpleMaterial>(TheTorusMaterial)->setAmbient(Color3f(0.2,0.2,0.2));
    dynamic_pointer_cast<SimpleMaterial>(TheTorusMaterial)->setDiffuse(Color3f(0.7,0.7,0.7));
    dynamic_pointer_cast<SimpleMaterial>(TheTorusMaterial)->setSpecular(Color3f(0.7,0.7,0.7));
    dynamic_pointer_cast<SimpleMaterial>(TheTorusMaterial)->setShininess(100.0f);

    //Torus Geometry
    GeometryRefPtr TorusGeometry = makeTorusGeo(.5, 2, 32, 32);
    TorusGeometry->setMaterial(TheTorusMaterial);
    
    NodeRefPtr TorusGeometryNode = Node::create();
    TorusGeometryNode->setCore(TorusGeometry);

    //Make Torus Node
    NodeRefPtr TorusNode = Node::create();
    TorusNodeTrans = Transform::create();
    setName(TorusNodeTrans, std::string("TorusNodeTransformationCore"));

    TorusNode->setCore(TorusNodeTrans);
    TorusNode->addChild(TorusGeometryNode);

    //Make Main Scene Node
    NodeRefPtr scene = Node::create();
    Trans = ComponentTransform::create();
    setName(Trans, std::string("MainTransformationCore"));

    scene->setCore(Trans);
    scene->addChild(TorusNode);

    setupAnimation();

    commitChanges();

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

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

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

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

    
    Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
    TutorialWindow->openWindow(WinPos,
            WinSize,
            "OpenSG 02TransformAnimation Window");

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

    }

    osgExit();

    return 0;
}
Exemplo n.º 29
0
bool PCSSShadowMap::initFBO(DrawEnv *pEnv)
{
    if(_useFBO)
    {
        Int32   width = _shadowVP->getPixelWidth();
        Int32   height = _shadowVP->getPixelHeight();

        if(width <= 0 || height <= 0)
            return false;

        if(_fb2 != 0)
            return true;

        Window *win = pEnv->getWindow();

#ifdef USE_FBO_FOR_COLOR_AND_FACTOR_MAP
        _width = _shadowVP->getPixelWidth();
        _height = _shadowVP->getPixelHeight();

        _colorMapImage->set(GL_RGB, _width, _height);

        _shadowFactorMapImage->set(GL_RGB, _width, _height);

        commitChanges();

        glGenFramebuffersEXT(1, &_fb);
        glGenRenderbuffersEXT(1, &_rb_depth);

        win->validateGLObject(_colorMap->getGLId(), pEnv);
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _fb);
        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
                                  GL_TEXTURE_2D,
                                  win->getGLObjectId(_colorMap->getGLId()), 0);
        win->validateGLObject(_shadowFactorMap->getGLId(), pEnv);
        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT,
                                  GL_TEXTURE_2D,
                                  win->getGLObjectId(_shadowFactorMap->getGLId
                                                     ()), 0);

        //Initialize Depth Renderbuffer
        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, _rb_depth);
        if(_useNPOTTextures)
            glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24_ARB
                                     , _shadowVP->getPixelWidth(),
                                     _shadowVP->getPixelHeight());
        else
            glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24_ARB
                                     , _widthHeightPOT, _widthHeightPOT);
        //Attach Renderbuffer to Framebuffer depth Buffer
        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT
                                     , GL_RENDERBUFFER_EXT, _rb_depth);

        win->validateGLObject(_colorMap->getGLId(), pEnv);
        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
                                  GL_TEXTURE_2D,
                                  win->getGLObjectId(_colorMap->getGLId()), 0);

        win->validateGLObject(_shadowFactorMap->getGLId(), pEnv);
        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT,
                                  GL_TEXTURE_2D,
                                  win->getGLObjectId(_shadowFactorMap->getGLId
                                                     ()), 0);

        bool    result = checkFrameBufferStatus(win);
#endif

        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);

        glGenFramebuffersEXT(1, &_fb2);
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _fb2);

        glDrawBuffer(GL_NONE);	// no color buffer dest
        glReadBuffer(GL_NONE);	// no color buffer src

        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);

    }

    return true;
}
Exemplo n.º 30
0
void PhysicsHandler::handleUpdate(EventDetails* const details)
{
    commitChanges();

    //Start the physics timing statistic
    StatTimeElem *PhysicsTimeStatElem = StatCollector::getGlobalElem(statPhysicsTime);
    if(PhysicsTimeStatElem) { PhysicsTimeStatElem->start(); }

    _TimeSinceLast += dynamic_cast<UpdateEventDetails* const>(details)->getElapsedTime();

    if(osgFloor(_TimeSinceLast/getStepSize()) > getMaxStepsPerUpdate())
    {
        SWARNING << "Physics Simulation slowing: dropping " << osgFloor(_TimeSinceLast/getStepSize())-getMaxStepsPerUpdate() << " steps" << std::endl;
        _TimeSinceLast = getMaxStepsPerUpdate()*getStepSize();
    }

    StatIntElem *NPhysicsStepsStatElem = StatCollector::getGlobalElem(statNPhysicsSteps);
    StatTimeElem *CollisionTimeStatElem = StatCollector::getGlobalElem(statCollisionTime);
    StatTimeElem *DynamicsTimeStatElem = StatCollector::getGlobalElem(statSimulationTime);
    while(_TimeSinceLast > getStepSize())
    {
        //Increment the steps statistic
        if(NPhysicsStepsStatElem) { NPhysicsStepsStatElem->inc(); }

        //*********** Collision Checks *************
        //Start the collision timing statistic
        if(CollisionTimeStatElem) { CollisionTimeStatElem->start(); }

        //Do collision checks
        for(UInt32 i(0) ; i<getMFSpaces()->size() ; ++i)
        {
            getSpaces(i)->Collide(getWorld());
        }

        //Stop the collision timing statistic
        if(CollisionTimeStatElem) { CollisionTimeStatElem->stop(); }


        //*********** Simulation step *************

        //Start the simulation timing statistic
        if(DynamicsTimeStatElem) { DynamicsTimeStatElem->start(); }

        //Step the dynamics simulation
        getWorld()->worldQuickStep(getStepSize());

        //Stop the simulation timing statistic
        if(DynamicsTimeStatElem) { DynamicsTimeStatElem->stop(); }

        //Decrease the time since last simulation step
        _TimeSinceLast -= getStepSize();
    }
    StatRealElem *NCollisionTestsStatElem = StatCollector::getGlobalElem(statNCollisionTests);
    if(NCollisionTestsStatElem) { NCollisionTestsStatElem->set(NCollisionTestsStatElem->get()/static_cast<Real32>(NPhysicsStepsStatElem->get())); }
    StatRealElem *NCollisionsStatElem = StatCollector::getGlobalElem(statNCollisions);
    if(NCollisionsStatElem) { NCollisionsStatElem->set(NCollisionsStatElem->get()/static_cast<Real32>(NPhysicsStepsStatElem->get())); }

    
    
    StatTimeElem *TransformUpdateTimeStatElem = StatCollector::getGlobalElem(statTransformUpdateTime);
    //Start the transform update timing statistic
    if(TransformUpdateTimeStatElem) { TransformUpdateTimeStatElem->start(); }
    //update matrices
    updateWorld(getUpdateNode());
    //Start the transform update timing statistic
    if(TransformUpdateTimeStatElem) { TransformUpdateTimeStatElem->stop(); }

    //Stop the physics timing statistic
    if(PhysicsTimeStatElem) { PhysicsTimeStatElem->stop(); }
}