Пример #1
0
 virtual void drawImplementation( osg::RenderInfo& renderInfo ) const
 {
     unsigned int contextID = renderInfo.getContextID();
     if ( !_initialized )
     {
         NanoVGDrawable* constMe = const_cast<NanoVGDrawable*>(this);
         glewInit();
         constMe->_vg = nvgCreateGL2( NVG_ANTIALIAS|NVG_STENCIL_STROKES|NVG_DEBUG );
         if ( !constMe->_vg )
         {
             OSG_NOTICE << "[NanoVGDrawable] Failed to create VG context" << std::endl;
             return;
         }
         
         constMe->initializeGL( renderInfo.getState() );
         constMe->_activeContextID = contextID;
         constMe->_initialized = true;
     }
     else if ( _vg && contextID==_activeContextID )
     {
         osg::State* state = renderInfo.getState();
         state->disableAllVertexArrays();
         state->disableTexCoordPointer( 0 );
         
         nvgBeginFrame( _vg, _width, _height, 1.0f );
         updateGL( state );
         nvgEndFrame( _vg );
     }
 }
Пример #2
0
void
LayerDrawable::drawImplementation(osg::RenderInfo& ri) const
{
    //OE_INFO << LC << (_layer ? _layer->getName() : "[empty]") << " tiles=" << _tiles.size() << std::endl;

    // Get this context's state values:
    PerContextDrawState& ds = _drawState->getPCDS(ri.getContextID());

    ds.refresh(ri, _drawState->_bindings);

    if (ds._layerUidUL >= 0)
    {
        GLint uid = _layer ? (GLint)_layer->getUID() : (GLint)-1;
        ds._ext->glUniform1i(ds._layerUidUL, uid);
    }
    else
    {
        // This just means that the fragment shader for this layer doesn't use oe_layer_uid
    }

    for (DrawTileCommands::const_iterator tile = _tiles.begin(); tile != _tiles.end(); ++tile)
    {
        tile->draw(ri, *_drawState, 0L);
    }

    // If set, dirty all OSG state to prevent any leakage - this is sometimes
    // necessary when doing custom OpenGL within a Drawable.
    if (_clearOsgState)
    {
        // Dirty the texture attributes so OSG can properly reset them
        // NOTE: cannot call state.dirtyAllAttributes, because that would invalidate
        // positional state like light sources!
        reinterpret_cast<StateEx*>(ri.getState())->dirtyAllTextureAttributes();

        // NOTE: this is a NOOP in OSG 3.5.x, but not in 3.4.x ... Later we will need to
        // revisit whether to call disableAllVertexArrays() in 3.5.x instead.
        ri.getState()->dirtyAllVertexArrays();
        
        // unbind local buffers when finished.
        ds._ext->glBindBuffer(GL_ARRAY_BUFFER_ARB,0);
        ds._ext->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB,0);

        // gw: no need to do this, in fact it will cause positional attributes
        // (light clip planes and lights) to immediately be reapplied under the
        // current MVM, which will by definition be wrong!)
        //ri.getState()->apply();
    }
}
Пример #3
0
void CallbackDrawable::drawImplementation(osg::RenderInfo& ri) const
{
    glPushAttrib(GL_ALL_ATTRIB_BITS);

    glDisable(GL_LIGHTING);
    glDisable(GL_TEXTURE_2D);
    glDisable(GL_TEXTURE_1D);

    MyGLClientState state;
    //printGLState();
    pushClientState(state);
    _renderer->draw(ri.getContextID());
    popClientState(state);

    glPopAttrib();
}
Пример #4
0
void
PerContextDrawState::refresh(osg::RenderInfo& ri, const RenderBindings* bindings)
{
    // Establish a GL Extensions handle:
    if (!_ext.valid())
    {
        _ext = osg::GLExtensions::Get(ri.getContextID(), true);
    }

    // Size the sampler states property:
    if (_samplerState._samplers.size() < bindings->size())
    {
        _samplerState._samplers.resize(bindings->size());
    }

    const osg::Program::PerContextProgram* pcp = ri.getState()->getLastAppliedProgramObject();
    if (pcp && (pcp != _pcp))
    {
        // Reset all sampler matrix states since their uniform locations are going to change.
        //_runningLayerDrawOrder = 0;
        _elevTexelCoeff.clear();
        _morphConstants.clear();
        _parentTextureExists.clear();
        _samplerState.clear();

        // for each sampler binding, initialize its state tracking structure 
        // and resolve its matrix uniform location:
        for (unsigned i = 0; i < bindings->size(); ++i)
        {
            const SamplerBinding& binding = (*bindings)[i];
            _samplerState._samplers[i]._matrixUL = pcp->getUniformLocation(osg::Uniform::getNameID(binding.matrixName()));
        }

        // resolve all the other uniform locations:
        _tileKeyUL = pcp->getUniformLocation(osg::Uniform::getNameID("oe_tile_key"));
        _elevTexelCoeffUL = pcp->getUniformLocation(osg::Uniform::getNameID("oe_tile_elevTexelCoeff"));
        _parentTextureExistsUL = pcp->getUniformLocation(osg::Uniform::getNameID("oe_layer_texParentExists"));
        _layerUidUL = pcp->getUniformLocation(osg::Uniform::getNameID("oe_layer_uid"));
        _layerOrderUL = pcp->getUniformLocation(osg::Uniform::getNameID("oe_layer_order"));
        _morphConstantsUL = pcp->getUniformLocation(osg::Uniform::getNameID("oe_tile_morph"));
    }

    _pcp = pcp;
}
void MYGUIManager::drawImplementation( osg::RenderInfo& renderInfo ) const
{
    unsigned int contextID = renderInfo.getContextID();
    if ( !_initialized )
    {
        MYGUIManager* constMe = const_cast<MYGUIManager*>(this);
        constMe->_platform = new MyGUI::OpenGLPlatform;
        constMe->_platform->initialise( constMe );
        constMe->setupResources();
        
        constMe->_gui = new MyGUI::Gui;
        constMe->_gui->initialise( _resourceCoreFile );
        constMe->initializeControls();

		osg::ref_ptr<osgViewer::GraphicsWindow> gw;
		if (_gw.lock(gw)) {
			gw->useCursor(_useHWCursor);
		}
		MyGUI::PointerManager& manager = MyGUI::PointerManager::getInstance();
		manager.setVisible(!_useHWCursor);
		manager.eventChangeMousePointer += MyGUI::newDelegate(constMe, &MYGUIManager::notifyChangeMousePointer);

        constMe->_activeContextID = contextID;
        constMe->_initialized = true;
    }
    else if ( contextID==_activeContextID )
    {
        osg::State* state = renderInfo.getState();
        state->disableAllVertexArrays();
        state->disableTexCoordPointer( 0 );
        
        glPushMatrix();
        glPushAttrib( GL_ALL_ATTRIB_BITS );
		if ( _platform )
		{
		    updateEvents();
		    _platform->getRenderManagerPtr()->drawOneFrame();
        }
        glPopAttrib();
        glPopMatrix();
    }
}
Пример #6
0
void MYGUIManager::drawImplementation( osg::RenderInfo& renderInfo ) const
{
	MYGUIManager* constMe = const_cast<MYGUIManager*>(this);

    unsigned int contextID = renderInfo.getContextID();
    if ( !_initialized )
    {
		constMe->_platform = new MyOpenGLPlatform;
        constMe->_platform->initialise( constMe );
        constMe->setupResources();
        
        constMe->_gui = new MyGUI::Gui;
        constMe->_gui->initialise( _resourceCoreFile );
        constMe->initializeControls();
        
        constMe->_activeContextID = contextID;
        constMe->_initialized = true;
    }
    else if ( contextID==_activeContextID )
    {
        osg::State* state = renderInfo.getState();
        state->disableAllVertexArrays();
		state->disableTexCoordPointer( 1 );
        
        glPushMatrix();
        glPushAttrib( GL_ALL_ATTRIB_BITS );
		if ( _platform )
		{
			constMe->setIntersectionPoint(getIntersectionPoint(),true);
			constMe->lock();
		    updateEvents();
			_platform->getMyRenderManagerPtr()->drawOneFrame();
			constMe->unlock();
        }
        glPopAttrib();
        glPopMatrix();

		state->dirtyAllVertexArrays();
		state->dirtyTexCoordPointer(1);
		state->dirtyAllAttributes();
    }
}
Пример #7
0
    //--------------------------------------------------------------------------
    void UnitInMipmapOut::noticeFinishRendering(osg::RenderInfo &renderInfo, const osg::Drawable* drawable)
    {
        // this method will be called everytime when a drawable of this unit
        // is rendered. Hence we check here if we are using hardware mipmap 
        // generation and apply this if neccessary

        // if we have used a shader to generate mipmaps, then we can safely return
        if (mUseShader) return;

        // get the fbo extensions
        osg::FBOExtensions* fbo_ext = osg::FBOExtensions::instance(renderInfo.getContextID(),true);
        
        // we don't use shader, that means that the mipmaps are generated in hardware, hence do this
        std::map<int, osg::ref_ptr<osg::Texture> >::iterator it = mOutputTex.begin();
        for (; it != mOutputTex.end(); it++)
        {
            renderInfo.getState()->applyTextureAttribute(0, it->second.get());
            fbo_ext->glGenerateMipmap(it->second->getTextureTarget());
        }
    }
Пример #8
0
void SiltEffect::SiltDrawable::drawImplementation(osg::RenderInfo& renderInfo) const
{
    if (!_geometry) return;

    const osg::Geometry::Extensions* extensions = osg::Geometry::getExtensions(renderInfo.getContextID(),true);

    glPushMatrix();

    typedef std::vector<const CellMatrixMap::value_type*> DepthMatrixStartTimeVector;
    DepthMatrixStartTimeVector orderedEntries;
    orderedEntries.reserve(_currentCellMatrixMap.size());

    for(CellMatrixMap::const_iterator citr = _currentCellMatrixMap.begin();
        citr != _currentCellMatrixMap.end();
        ++citr)
    {
        orderedEntries.push_back(&(*citr));
    }

    std::sort(orderedEntries.begin(),orderedEntries.end(),LessFunctor());

    for(DepthMatrixStartTimeVector::reverse_iterator itr = orderedEntries.rbegin();
        itr != orderedEntries.rend();
        ++itr)
    {
        extensions->glMultiTexCoord1f(GL_TEXTURE0+1, (*itr)->second.startTime);

        glMatrixMode( GL_MODELVIEW );
        glLoadMatrix((*itr)->second.modelview.ptr());

        _geometry->draw(renderInfo);

        unsigned int numVertices = osg::minimum(_geometry->getVertexArray()->getNumElements(), _numberOfVertices);
        glDrawArrays(_drawType, 0, numVertices);
    }

    glPopMatrix();
}
Пример #9
0
void CudaTestDrawable::drawImplementation(osg::RenderInfo& ri) const
{
    if(ri.getContextID())
    {
	return;
    }
    //std::cerr << "Draw context: " << ri.getContextID() << std::endl;
    if(!_init)
    {
	init();
	_init = true;
    }

    glFinish();

    struct timeval start,end;
    getTime(start);

    copyData();

    getTime(end);
    printDiff("Copy Time: ",start,end);
}
Пример #10
0
void PanoDrawableLOD::drawImplementation(osg::RenderInfo& ri) const
{
    if(_badInit)
    {
	return;
    }

    glPushAttrib(GL_ALL_ATTRIB_BITS);

    int context = ri.getContextID();

    int eye = 0;
    osg::Node::NodeMask parentMask;

    if(!getNumParents())
    {
	glPopAttrib();
	return;
    }

    parentMask = getParent(0)->getNodeMask();

    if((parentMask & CULL_MASK_LEFT) || (parentMask & CULL_MASK) || (ScreenConfig::instance()->getEyeSeparationMultiplier() == 0.0))
    {
	if(ScreenBase::getEyeSeparation() >= 0)
	{
	    eye = DRAW_LEFT;
	}
	else
	{
	    eye = DRAW_RIGHT;
	}
    }
    else
    {
	if(ScreenBase::getEyeSeparation() >= 0)
	{
	    eye = DRAW_RIGHT;
	}
	else
	{
	    eye = DRAW_LEFT;
	}
    }

    _pdi->initLock.lock();

    if(!_pdi->initMap[context])
    {
	if(!_pdi->cacheMap[context])
	{
	    GLenum err = glewInit();
	    if (GLEW_OK != err)
	    {
		std::cerr << "Error on glew init: " << glewGetErrorString(err) << std::endl;
		_badInit = true;
		_pdi->initLock.unlock();
		glPopAttrib();
		return;
	    }
	    int cachesize = ConfigManager::getInt("value","Plugin.PanoViewLOD.CacheSize",256);
	    _pdi->cacheMap[context] = new sph_cache(cachesize);
	    _pdi->cacheMap[context]->set_debug(false);

	    _pdi->updateLock[context] = new OpenThreads::Mutex();
	}

	int time = 1;
	if(_pdi->modelMap[context])
	{
	    time = _pdi->modelMap[context]->get_time();
	    delete _pdi->modelMap[context];
	    delete _pdi->transitionModelMap[context];
	}
	GLint buffer,ebuffer;
	glGetIntegerv(GL_ARRAY_BUFFER_BINDING,&buffer);
	glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING,&ebuffer);

	_pdi->modelMap[context] = new sph_model(*_pdi->cacheMap[context],_vertData,_fragData,_mesh,_depth,_size);
	_pdi->transitionModelMap[context] = new sph_model(*_pdi->cacheMap[context],_vertData,_fragData,_mesh,_depth,_size);
	// Set start time to last model's time since timestamps are used by the disk cache
	_pdi->modelMap[context]->set_time(time);
	_pdi->transitionModelMap[context]->set_time(time);

	glBindBuffer(GL_ARRAY_BUFFER, buffer);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebuffer);

	_pdi->leftFileIDs[context] = std::vector<int>();
	_pdi->rightFileIDs[context] = std::vector<int>();
    }

    if(!(_pdi->initMap[context] & eye))
    {
	if(eye & DRAW_LEFT)
	{
	    for(int i = 0; i < _pdi->leftEyeFiles.size(); i++)
	    {
		_pdi->leftFileIDs[context].push_back(_pdi->cacheMap[context]->add_file(_pdi->leftEyeFiles[i]));
	    }
	    if(_pdi->leftEyeFiles.size() > 1 && _currentIndex < _pdi->leftFileIDs[context].size())
	    {
                int last, next;
                next = (_currentIndex+1) % _pdi->leftFileIDs[context].size();
                last = (_currentIndex-1+_pdi->leftFileIDs[context].size()) % _pdi->leftFileIDs[context].size();
		sph_cache::_diskCache->setLeftFiles(_pdi->leftFileIDs[context][last],_pdi->leftFileIDs[context][_currentIndex],_pdi->leftFileIDs[context][next]);
	    }
	    else if(_pdi->leftEyeFiles.size() == 1 && _currentIndex < _pdi->leftFileIDs[context].size())
	    {
		sph_cache::_diskCache->setLeftFiles(-1,_pdi->leftFileIDs[context][_currentIndex],-1);
	    }
	}
	else if(eye & DRAW_RIGHT)
	{
	    for(int i = 0; i < _pdi->rightEyeFiles.size(); i++)
	    {
		_pdi->rightFileIDs[context].push_back(_pdi->cacheMap[context]->add_file(_pdi->rightEyeFiles[i]));
	    }
	    if(_pdi->rightEyeFiles.size() > 1 && _currentIndex < _pdi->rightFileIDs[context].size())
	    {
                int last, next;
                next = (_currentIndex+1) % _pdi->rightFileIDs[context].size();
                last = (_currentIndex-1+_pdi->rightFileIDs[context].size()) % _pdi->rightFileIDs[context].size();
		sph_cache::_diskCache->setRightFiles(_pdi->rightFileIDs[context][last],_pdi->rightFileIDs[context][_currentIndex],_pdi->rightFileIDs[context][next]);
	    }
	    else if(_pdi->rightEyeFiles.size() == 1 && _currentIndex < _pdi->rightFileIDs[context].size())
	    {
		sph_cache::_diskCache->setRightFiles(-1,_pdi->rightFileIDs[context][_currentIndex],-1);
	    }
	}
	_pdi->initMap[context] |= eye;
    }

    _pdi->initLock.unlock();

    _pdi->updateLock[context]->lock();

    if(!_pdi->updateDoneMap[context])
    {
#ifdef PRINT_TIMING
	struct timeval ustart, uend;
	gettimeofday(&ustart,NULL);
#endif
	_pdi->cacheMap[context]->update(_pdi->modelMap[context]->tick());
	_pdi->transitionModelMap[context]->tick();
	_pdi->updateDoneMap[context] = true;
#ifdef PRINT_TIMING
	gettimeofday(&uend,NULL);
	double utime = (uend.tv_sec - ustart.tv_sec) + ((uend.tv_usec - ustart.tv_usec)/1000000.0);
	std::cerr << "Context: " << context << " Update time: " << utime << std::endl;
#endif
    }

    _pdi->updateLock[context]->unlock(); 

    if(_transitionType == NORMAL || !_transitionActive)
    {
	osg::Matrix modelview;
	modelview.makeScale(osg::Vec3(_radius,_radius,_radius));
	modelview = modelview * ri.getState()->getModelViewMatrix();

	int fileID[2];
	int pv[2];
	int pc = 0;
	int fc = 0;
	float fade = 0;
	if(eye & DRAW_LEFT)
	{
	    if(_currentFadeTime == 0.0)
	    {
		fileID[0] = _pdi->leftFileIDs[context][_currentIndex];
		fc = 1;
	    }
	    else
	    {
		fileID[0] = _pdi->leftFileIDs[context][_lastIndex];
		fileID[1] = _pdi->leftFileIDs[context][_currentIndex];
		fc = 2;
		pv[0] = _pdi->leftFileIDs[context][_nextIndex];
		pc = 1;
		fade = 1.0 - (_currentFadeTime / _totalFadeTime);
		//std::cerr << "Files: " << fileID[0] << " " << fileID[1] << std::endl;
	    }
	}
	else if(eye & DRAW_RIGHT)
	{
	    if(_currentFadeTime == 0.0)
	    {
		fileID[0] = _pdi->rightFileIDs[context][_currentIndex];
		fc = 1;
	    }
	    else
	    {
		fileID[0] = _pdi->rightFileIDs[context][_lastIndex];
		fileID[1] = _pdi->rightFileIDs[context][_currentIndex];
		fc = 2;
		pv[0] = _pdi->rightFileIDs[context][_nextIndex];
		pc = 1;
		fade = 1.0 - (_currentFadeTime / _totalFadeTime);
		//std::cerr << "Files: " << fileID[0] << " " << fileID[1] << std::endl;
	    }
	}

	//std::cerr << "Fade: " << fade << std::endl;

	_pdi->modelMap[context]->set_fade(fade);
	glUseProgram(0);
	_pdi->modelMap[context]->prep(ri.getState()->getProjectionMatrix().ptr(),modelview.ptr(), (int)ri.getState()->getCurrentViewport()->width(), (int)ri.getState()->getCurrentViewport()->height());

	//printGLState();
	MyGLClientState glstate;
	pushClientState(glstate);

	//GLint buffer,ebuffer;
	//glGetIntegerv(GL_ARRAY_BUFFER_BINDING,&buffer);
	//glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING,&ebuffer);
	//bool vertexOn = glIsEnabled(GL_VERTEX_ARRAY);
	//glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT);
	//clearGLClientState();

	_pdi->modelMap[context]->draw(ri.getState()->getProjectionMatrix().ptr(), modelview.ptr(), fileID, fc, pv, pc, _alpha);

	popClientState(glstate);

    }
    else
    {
	osg::Matrix modelviewfrom;
	modelviewfrom.makeScale(osg::Vec3(_radius,_radius,_radius));
	modelviewfrom = modelviewfrom * _pdi->fromTransitionTransform * ri.getState()->getModelViewMatrix();

	osg::Matrix modelviewto;
	modelviewto.makeScale(osg::Vec3(_radius*1.001,_radius*1.001,_radius*1.001));
	modelviewto = modelviewto * _pdi->toTransitionTransform * ri.getState()->getModelViewMatrix();

	int fileIDfrom[2];
	int fileIDto[2];
	int pv[2];
	int pc = 0;
	int fc = 0;
	float fade = 0;
	if(eye & DRAW_LEFT)
	{
	    fileIDfrom[0] = _pdi->leftFileIDs[context][_lastIndex];
	    fileIDto[0] = _pdi->leftFileIDs[context][_currentIndex];
	    fc = 1;
	}
	else if(eye & DRAW_RIGHT)
	{
	    fileIDfrom[0] = _pdi->rightFileIDs[context][_lastIndex];
	    fileIDto[0] = _pdi->rightFileIDs[context][_currentIndex];
	    fc = 1;
	}

	//std::cerr << "Fade: " << fade << std::endl;

	_pdi->modelMap[context]->set_fade(fade);
	_pdi->transitionModelMap[context]->set_fade(fade);
	glUseProgram(0);
	_pdi->modelMap[context]->prep(ri.getState()->getProjectionMatrix().ptr(),modelviewto.ptr(), (int)ri.getState()->getCurrentViewport()->width(), (int)ri.getState()->getCurrentViewport()->height());
	_pdi->transitionModelMap[context]->prep(ri.getState()->getProjectionMatrix().ptr(),modelviewfrom.ptr(), (int)ri.getState()->getCurrentViewport()->width(), (int)ri.getState()->getCurrentViewport()->height());

	MyGLClientState glstate;
	pushClientState(glstate);

	_pdi->modelMap[context]->draw(ri.getState()->getProjectionMatrix().ptr(), modelviewto.ptr(), fileIDto, fc, pv, pc, 1.0);
	_pdi->transitionModelMap[context]->draw(ri.getState()->getProjectionMatrix().ptr(), modelviewfrom.ptr(), fileIDfrom, fc, pv, pc, 1.0 - _pdi->transitionFade);

	popClientState(glstate);
    }

    //glPopClientAttrib();
    //glBindBuffer(GL_ARRAY_BUFFER, buffer);
    //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebuffer);
    /*if(vertexOn)
    {
	glEnableClientState(GL_VERTEX_ARRAY);
    }*/

    glPopAttrib();
}
Пример #11
0
void NoesisDrawable::drawImplementation( osg::RenderInfo& renderInfo ) const
{
    unsigned int contextID = renderInfo.getContextID();
    if ( !_initialized )
    {
        if ( !NoesisSystemManager::contextInitialized )
        {
            NsGetKernel()->InitSystems();
            NoesisSystemManager::contextInitialized = true;
        }

        NoesisDrawable* constMe = const_cast<NoesisDrawable*>( this );
        constMe->initializeUI( renderInfo );
        constMe->registerEventHandlers();
        _activeContextID = contextID;
        _initialized = true;
    }
    else if ( contextID==_activeContextID )
    {
        if ( _dirty )
        {
            _uiRenderer->SetSize( _width, _height );
            _dirty = false;
        }
        
        osg::State* state = renderInfo.getState();
        state->disableAllVertexArrays();
        
        // Make sure the client unit and active unit are unified
        state->setClientActiveTextureUnit( 0 );
        state->setActiveTextureUnit( 0 );
        
#if !PARALLEL_UPDATING_AND_RENDERING
        // Update
        NsGetKernel()->Tick();

        osg::FrameStamp* fs = renderInfo.getView()->getFrameStamp();
        if ( fs ) _uiRenderer->Update( fs->getSimulationTime() );
#endif
        // Obtain commands
        RenderCommands renderCommands = _uiRenderer->WaitForUpdate();
        osg::FBOExtensions* fbo = osg::FBOExtensions::instance(contextID, true);

        // Render offscreen
        if ( fbo )
        {;
            _uiRenderer->Render( renderCommands.offscreenCommands.GetPtr() );
            fbo->glBindFramebuffer( GL_FRAMEBUFFER_EXT, 0 );
        }

        // Render
        _uiRenderer->Render( renderCommands.commands.GetPtr() );

        // Restore buffer states
        osg::GLBufferObject::Extensions* buf = osg::GLBufferObject::getExtensions(contextID, true);
        buf->glBindBuffer( GL_ARRAY_BUFFER_ARB, 0 );
        buf->glBindBuffer( GL_ELEMENT_ARRAY_BUFFER_ARB, 0 );

        osg::GL2Extensions* gl2 = osg::GL2Extensions::Get(contextID, true);
        gl2->glDisableVertexAttribArray( 0 );
        gl2->glDisableVertexAttribArray( 1 );
        gl2->glDisableVertexAttribArray( 2 );
        gl2->glDisableVertexAttribArray( 3 );
        gl2->glDisableVertexAttribArray( 4 );
        gl2->glDisableVertexAttribArray( 5 );
        gl2->glDisableVertexAttribArray( 6 );
    }
    else
        std::cout << "Multiple contexts are not supported at present!" << std::endl;
}
void ScreenInterlacedTopBottom::InterlaceCallback::operator()(
        osg::RenderInfo &renderInfo) const
{
    int context = renderInfo.getContextID();
    const osg::GL2Extensions* extensions = osg::GL2Extensions::Get(context,
            true);
    //osg::FBOExtensions* ext = osg::FBOExtensions::instance(context,true);
    //ext->glBindFramebuffer(osg::FrameBufferObject::READ_DRAW_FRAMEBUFFER, 0);
    //glColorMask(true,true,true,true);
    //osgDB::writeImageFile(*screen->image,"/home/aprudhom/testImage.tif");
    //exit(0);
    //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    //glFinish();
    //return;
    /*if(skip)
     {
     //screen->_camera->setClearColor(osg::Vec4(1.0,0,0,0));
     skip = false;
     return;
     }
     else
     {
     //screen->_camera->setClearColor(osg::Vec4(0,1.0,0,0));
     skip = true;
     }*/

    if(first)
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    }

    //glPushAttrib(GL_ALL_ATTRIB_BITS);

    //std::cerr << "Callback." << std::endl;
    if(!_initMap[context])
    {
        OpenThreads::ScopedLock < OpenThreads::Mutex > lock(_initLock);
        std::string shaderdir = CalVR::instance()->getResourceDir() + "/shaders/";

        osg::Shader * vert, *frag;
        if(odd)
        {
            vert = osg::Shader::readShaderFile(osg::Shader::VERTEX,
                    osgDB::findDataFile(shaderdir + "interlace.vert"));
            frag = osg::Shader::readShaderFile(osg::Shader::FRAGMENT,
                    osgDB::findDataFile(shaderdir + "interlace-odd.frag"));
        }
        else
        {
            vert = osg::Shader::readShaderFile(osg::Shader::VERTEX,
                    osgDB::findDataFile(shaderdir + "interlace.vert"));
            frag = osg::Shader::readShaderFile(osg::Shader::FRAGMENT,
                    osgDB::findDataFile(shaderdir + "interlace-even.frag"));
        }

        _programMap[context] = new osg::Program;
        _programMap[context]->addShader(vert);
        _programMap[context]->addShader(frag);

        _geometryMap[context] = new osg::Geometry();

        osg::DrawArrays * quad = new osg::DrawArrays(
                osg::PrimitiveSet::TRIANGLE_STRIP,0,0);
        osg::Vec2Array * verts = new osg::Vec2Array(0);
        _geometryMap[context]->setVertexArray(verts);
        _geometryMap[context]->addPrimitiveSet(quad);
        verts->push_back(osg::Vec2(-1.0,1.0));
        verts->push_back(osg::Vec2(-1.0,-1.0));
        verts->push_back(osg::Vec2(1.0,1.0));
        verts->push_back(osg::Vec2(1.0,-1.0));

        _geometryMap[context]->setUseDisplayList(false);

        quad->setCount(4);

        /*glGenBuffers(1,&_arrayMap[context]);
         glBindBuffer(GL_ARRAY_BUFFER, arrayMap[context]);
         float points[8] = {-1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, -1.0};

         glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(float), points, GL_STATIC_DRAW);
         glBindBuffer(GL_ARRAY_BUFFER, 0);*/

        _initMap[context] = true;
    }

    glViewport((int)screen->_myInfo->myChannel->left,
            (int)screen->_myInfo->myChannel->bottom,
            (int)screen->_myInfo->myChannel->width,
            (int)screen->_myInfo->myChannel->height);

    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();

    //GLint activeTexture,bindtex;
    //glGetIntegerv(GL_ACTIVE_TEXTURE,&activeTexture);

    unsigned int activeTexture = renderInfo.getState()->getActiveTextureUnit();

    osg::Texture::TextureObject * to = _texture->getTextureObject(context);

    renderInfo.getState()->setActiveTextureUnit(0);
    //glActiveTexture(GL_TEXTURE0);
    //glGetIntegerv(GL_TEXTURE_BINDING_2D,&bindtex);
    if(to)
    {
        to->bind();
    }
    //_texture->apply(*renderInfo.getState());

    _programMap[context]->apply(*renderInfo.getState());
    _geometryMap[context]->drawImplementation(renderInfo);

    //glBindTexture(GL_TEXTURE_2D,bindtex);

    extensions->glUseProgram(0);
    renderInfo.getState()->setLastAppliedProgramObject(0);

    renderInfo.getState()->setActiveTextureUnit(activeTexture);
    //glActiveTexture(activeTexture);
    /*glBegin(GL_TRIANGLE_STRIP);

     glColor3f(1.0,0.0,0.0);

     glVertex2f(-1.0,1.0);
     glVertex2f(-1.0,-1.0);
     glVertex2f(1.0,1.0);
     glVertex2f(1.0,-1.0);

     glEnd();*/

    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();

    //glPopAttrib();
}
void PrecipitationEffect::PrecipitationDrawable::drawImplementation(osg::RenderInfo& renderInfo) const
{
#if defined(OSG_GL_MATRICES_AVAILABLE)

if (!_geometry) return;


    const osg::Geometry::Extensions* extensions = osg::Geometry::getExtensions(renderInfo.getContextID(),true);

    // save OpenGL matrices
    glPushMatrix();

    if (_requiresPreviousMatrix)
    {
        renderInfo.getState()->setActiveTextureUnit(0);
        glMatrixMode( GL_TEXTURE );
        glPushMatrix();
    }

    typedef std::vector<const CellMatrixMap::value_type*> DepthMatrixStartTimeVector;
    DepthMatrixStartTimeVector orderedEntries;
    orderedEntries.reserve(_currentCellMatrixMap.size());

    for(CellMatrixMap::const_iterator citr = _currentCellMatrixMap.begin();
        citr != _currentCellMatrixMap.end();
        ++citr)
    {
        orderedEntries.push_back(&(*citr));
    }

    std::sort(orderedEntries.begin(),orderedEntries.end(),LessFunctor());

    for(DepthMatrixStartTimeVector::reverse_iterator itr = orderedEntries.rbegin();
        itr != orderedEntries.rend();
        ++itr)
    {
        extensions->glMultiTexCoord1f(GL_TEXTURE0+1, (*itr)->second.startTime);

        // load cells current modelview matrix
        if (_requiresPreviousMatrix)
        {
            glMatrixMode( GL_MODELVIEW );
            glLoadMatrix((*itr)->second.modelview.ptr());

            CellMatrixMap::const_iterator pitr = _previousCellMatrixMap.find((*itr)->first);
            if (pitr != _previousCellMatrixMap.end())
            {
                // load previous frame modelview matrix for motion blurr effect
                glMatrixMode( GL_TEXTURE );
                glLoadMatrix(pitr->second.modelview.ptr());
            }
            else
            {
                // use current modelview matrix as "previous" frame value, cancelling motion blurr effect
                glMatrixMode( GL_TEXTURE );
                glLoadMatrix((*itr)->second.modelview.ptr());
            }
        }
        else
        {
            glLoadMatrix((*itr)->second.modelview.ptr());
        }

        _geometry->draw(renderInfo);

        unsigned int numVertices = osg::minimum(_geometry->getVertexArray()->getNumElements(), _numberOfVertices);
        glDrawArrays(_drawType, 0, numVertices);
    }

    // restore OpenGL matrices
    if (_requiresPreviousMatrix)
    {
        glPopMatrix();
        glMatrixMode( GL_MODELVIEW );
    }

    glPopMatrix();
#else
    OSG_NOTICE<<"Warning: ParticleEffect::drawImplementation(..) not fully implemented."<<std::endl;
#endif
}
Пример #14
0
void
TritonDrawable::drawImplementation(osg::RenderInfo& renderInfo) const
{
    osg::State* state = renderInfo.getState();

    state->disableAllVertexArrays();

    _TRITON->initialize( renderInfo );
    if ( !_TRITON->ready() )
        return;

    if ( _TRITON->passHeightMapToTriton() && !_terrainChangedCallback.valid() )
    {
        const_cast<TritonDrawable*>(this)->setupHeightMap(*state);
    }

    ::Triton::Environment* environment = _TRITON->getEnvironment();

    osgEarth::NativeProgramAdapterCollection& adapters = _adapters[ state->getContextID() ];
    if ( adapters.empty() )
    {
        const char* prefix = "oe_";
        adapters.push_back( new osgEarth::NativeProgramAdapter(state, (GLint)_TRITON->getOcean()->GetShaderObject(::Triton::GOD_RAYS), prefix));
        adapters.push_back( new osgEarth::NativeProgramAdapter(state, (GLint)_TRITON->getOcean()->GetShaderObject(::Triton::SPRAY_PARTICLES), prefix));
        adapters.push_back( new osgEarth::NativeProgramAdapter(state, (GLint)_TRITON->getOcean()->GetShaderObject(::Triton::WAKE_SPRAY_PARTICLES), prefix));
        adapters.push_back( new osgEarth::NativeProgramAdapter(state, (GLint)_TRITON->getOcean()->GetShaderObject(::Triton::WATER_DECALS), prefix));
        adapters.push_back( new osgEarth::NativeProgramAdapter(state, (GLint)_TRITON->getOcean()->GetShaderObject(::Triton::WATER_SURFACE_PATCH), prefix));
        adapters.push_back( new osgEarth::NativeProgramAdapter(state, (GLint)_TRITON->getOcean()->GetShaderObject(::Triton::WATER_SURFACE), prefix));
    }
    adapters.apply( state );

    // Pass the final view and projection matrices into Triton.
    if ( environment )
    {
        environment->SetCameraMatrix( state->getModelViewMatrix().ptr() );
        environment->SetProjectionMatrix( state->getProjectionMatrix().ptr() );
    }

    if ( _TRITON->passHeightMapToTriton() )
    {
        unsigned cid = renderInfo.getContextID();

        bool dirty =
            ( _contextDirty[cid] ) ||
            ( renderInfo.getView()->getCamera()->getViewMatrix()       != _viewMatrix ) ||
            ( renderInfo.getView()->getCamera()->getProjectionMatrix() != _projMatrix );

        if ( dirty )
        {
            updateHeightMap( renderInfo );
            _contextDirty[renderInfo.getContextID()] = 0;
            _viewMatrix = renderInfo.getView()->getCamera()->getViewMatrix();
            _projMatrix = renderInfo.getView()->getCamera()->getProjectionMatrix();
        }
    }

    state->dirtyAllVertexArrays();

    // Now light and draw the ocean:
    if ( environment )
    {
        // User pre-draw callback:
        if (_TRITON->getCallback())
        {
            _TRITON->getCallback()->onDrawOcean(
                _TRITON->getEnvironmentWrapper(),
                _TRITON->getOceanWrapper());
        }

        // The sun position is roughly where it is in our skybox texture:

        // Since this is a simple example we will just assume that Sun is the light from View light source
        // TODO: fix this...
        osg::Light* light = renderInfo.getView() ? renderInfo.getView()->getLight() : NULL;

        // This is the light attached to View so there are no transformations above..
        // But in general case you would need to accumulate all transforms above the light into this matrix
        osg::Matrix lightLocalToWorldMatrix = osg::Matrix::identity();

        // If you don't know where the sun lightsource is attached and don't know its local to world matrix you may use
        // following elaborate scheme to grab the light source while drawing Triton ocean:
        // - Install cull callback to catch CullVisitor and record pointer to its associated RenderStage
        //   I was hoping RenderStage can be found from renderInfo in drawImplementation but I didn't figure how ...
        // - When TritonDrawable::drawImplementation is called all lights will be already applied to OpenGL
        //   then just find proper infinite directional light by scanning renderStage->PositionalStateContainer.
        // - Note that we canot scan for the lights inside cull because they may not be traversed before Triton drawable
        // - When you found interesting ligt source that can work as Sun, read its modelview matrix and lighting params
        //   Multiply light position by ( modelview * inverse camera view ) and pass this to Triton with lighting colors

        if ( light && light->getPosition().w() == 0 )
        {
            osg::Vec4 ambient = light->getAmbient();
            osg::Vec4 diffuse = light->getDiffuse();
            osg::Vec4 position = light->getPosition();

            // Compute light position/direction in the world
            position = position * lightLocalToWorldMatrix;

            // Diffuse direction and color
            environment->SetDirectionalLight(
                ::Triton::Vector3( position[0], position[1], position[2] ),
                ::Triton::Vector3( diffuse[0],  diffuse[1],  diffuse[2] ) );

            // Sun-based ambient value:
            osg::Vec3d up = osg::Vec3d(0,0,0) * renderInfo.getCurrentCamera()->getInverseViewMatrix();
            up.normalize();
            osg::Vec3d pos3 = osg::Vec3d(position.x(), position.y(), position.z());
            pos3.normalize();
            float dot = osg::clampAbove(up*pos3, 0.0);
            dot*=dot;
            float sunAmbient = (float)osg::clampBetween( dot, 0.0f, 0.88f );
            float fa = std::max(sunAmbient, ambient[0]);

            // Ambient color based on the zenith color in the cube map
            environment->SetAmbientLight( ::Triton::Vector3(fa, fa, fa) );
            //::Triton::Vector3( ambient[0], ambient[1], ambient[2] ) );
        }

        else
        {
            environment->SetDirectionalLight( ::Triton::Vector3(0,0,1), ::Triton::Vector3(1,1,1) );
            environment->SetAmbientLight( ::Triton::Vector3(0.88f, 0.88f, 0.88f) );
        }

        // Build transform from our cube map orientation space to native Triton orientation
        // See worldToCubeMap function used in SkyBox to orient sky texture so that sky is up and earth is down
        osg::Matrix m = osg::Matrix::rotate( osg::PI_2, osg::X_AXIS ); // = worldToCubeMap

        ::Triton::Matrix3 transformFromYUpToZUpCubeMapCoords(
            m(0,0), m(0,1), m(0,2),
            m(1,0), m(1,1), m(1,2),
            m(2,0), m(2,1), m(2,2) );

        // Grab the cube map from our sky box and give it to Triton to use as an _environment map
        // GLenum texture = renderInfo.getState()->getLastAppliedTextureAttribute( _stage, osg::StateAttribute::TEXTURE );
        if ( _cubeMap.valid() )
        {
            environment->SetEnvironmentMap(
                (::Triton::TextureHandle)_cubeMap->getTextureObject( state->getContextID() )->id(), transformFromYUpToZUpCubeMapCoords );

            if( _planarReflectionMap.valid() && _planarReflectionProjection.valid() )
            {
                osg::Matrix & p = *_planarReflectionProjection;

                ::Triton::Matrix3 planarProjection( p(0,0), p(0,1), p(0,2),
                                                    p(1,0), p(1,1), p(1,2),
                                                    p(2,0), p(2,1), p(2,2) );

                environment->SetPlanarReflectionMap( (::Triton::TextureHandle)
                                                     _planarReflectionMap->getTextureObject( state->getContextID() )->id(),
                                                     planarProjection, 0.125  );
            }
        }

        // Draw the ocean for the current time sample
        if ( _TRITON->getOcean() )
        {
            _TRITON->getOcean()->Draw( renderInfo.getView()->getFrameStamp()->getSimulationTime() );
        }
    }

    // Put GL back in a state that won't confuse the OSG state tracking:
    state->dirtyAllVertexArrays();
    state->dirtyAllAttributes();
    //osg::GL2Extensions* api = osg::GL2Extensions::Get(state->getContextID(), true);
    //api->glUseProgram((GLuint)0);
    //state->setLastAppliedProgramObject( 0L );
    state->apply();
}
Пример #15
0
void
TritonDrawable::updateHeightMap(osg::RenderInfo& renderInfo) const
{
    if ( !_TRITON->ready() )
        return;

    osg::ref_ptr<MapNode> mapNode;
    if (!_mapNode.lock(mapNode))
        return;

    const osg::Matrix& viewMatrix = renderInfo.getCurrentCamera()->getViewMatrix();
    const osg::Matrix& projectionMatrix = renderInfo.getCurrentCamera()->getProjectionMatrix();

    osg::Vec3d eye, center, up;
    viewMatrix.getLookAt(eye, center, up);
    double fovyDEG=0.0, aspectRatio=0.0, zNear=0.0, zFar=0.0;
    projectionMatrix.getPerspective(fovyDEG, aspectRatio,zNear,zFar);

    // aspect_ratio = tan( HFOV/2 ) / tan( VFOV/2 )
    // tan( HFOV/2 ) = tan( VFOV/2 ) * aspect_ratio
    // HFOV/2 = atan( tan( VFOV/2 ) * aspect_ratio )
    // HFOV = 2.0 * atan( tan( VFOV/2 ) * aspect_ratio )
    double fovxDEG = osg::RadiansToDegrees( 2.0 * atan( tan(osg::DegreesToRadians(fovyDEG))/2.0 * aspectRatio ));

    double eyeLat=0.0, eyeLon=0.0, eyeHeight=0.0;
    mapNode->getMap()->getSRS()->getEllipsoid()->convertXYZToLatLongHeight(eye.x(), eye.y(), eye.z(), eyeLat, eyeLon, eyeHeight);
    double clampedEyeX=0.0, clampedEyeY=0.0,clampedEyeZ=0.0;
    mapNode->getMap()->getSRS()->getEllipsoid()->convertLatLongHeightToXYZ(eyeLat, eyeLon, 0.0, clampedEyeX, clampedEyeY, clampedEyeZ);
    osg::Vec3 mslEye(clampedEyeX,clampedEyeY,clampedEyeZ);
    double lookAtLat=0.0, lookAtLon=0.0, lookAtHeight=0.0;
    mapNode->getMap()->getSRS()->getEllipsoid()->convertXYZToLatLongHeight(center.x(), center.y(), center.z(), lookAtLat, lookAtLon, lookAtHeight);

    // Calculate the distance to the horizon from the eyepoint
    double eyeLen = eye.length();
    double radE = mslEye.length();
    double hmax = radE + 8848.0;
    double hmin = radE - 12262.0;
    double hasl = osg::maximum(0.1, eyeLen - radE);
    double radius = eyeLen - hasl;
    double horizonDistance = osg::minimum(radE, sqrt( 2.0*radius*hasl + hasl*hasl ));

    osg::Vec3d heightCamEye(eye);

    double near = osg::maximum(1.0, heightCamEye.length() - hmax);
    double far = osg::maximum(10.0, heightCamEye.length() - hmin + radE);
    //osg::notify( osg::ALWAYS ) << "near = " << near << "; far = " << far << std::endl;

    //horizonDistance *= 0.25;

    _heightCamera->setProjectionMatrix(osg::Matrix::ortho(-horizonDistance,horizonDistance,-horizonDistance,horizonDistance,near,far) );
    _heightCamera->setViewMatrixAsLookAt( heightCamEye, osg::Vec3d(0.0,0.0,0.0), osg::Vec3d(0.0,0.0,1.0));

    const osg::Matrixd bias(0.5, 0.0, 0.0, 0.0,
                            0.0, 0.5, 0.0, 0.0,
                            0.0, 0.0, 0.5, 0.0,
                            0.5, 0.5, 0.5, 1.0);

    osg::Matrix hMM = _heightCamera->getViewMatrix() * _heightCamera->getProjectionMatrix() * bias;
    ::Triton::Matrix4 heightMapMatrix(hMM(0,0),hMM(0,1),hMM(0,2),hMM(0,3),
                                      hMM(1,0),hMM(1,1),hMM(1,2),hMM(1,3),
                                      hMM(2,0),hMM(2,1),hMM(2,2),hMM(2,3),
                                      hMM(3,0),hMM(3,1),hMM(3,2),hMM(3,3));

    osg::Texture::TextureObject* texObj = _heightMap->getTextureObject(renderInfo.getContextID());

    if(texObj)
    {
        PassHeightMapToTritonCallback* cb = dynamic_cast<PassHeightMapToTritonCallback*>(_heightCamera->getFinalDrawCallback());
        if( cb )
        {
            cb->_enable = true;
            cb->_id = texObj->id();
            cb->_heightMapMatrix = heightMapMatrix;
        }
    }
    else
    {
        // may happen on the first frame; ignore
        //OE_WARN << LC << "Texture object is NULL (Internal error)" << std::endl;
    }

#ifdef DEBUG_HEIGHTMAP
    mapNode->getParent(0)->removeChild(0, 1);
    mapNode->getParent(0)->insertChild(0, makeFrustumFromCamera(_heightCam));
#endif /* DEBUG_HEIGHTMAP */
}
Пример #16
0
void FadeText::drawImplementation(osg::RenderInfo& renderInfo) const
{

    osg::State& state = *renderInfo.getState();

    ViewBlendColourMap::iterator itr = _viewBlendColourMap.find(renderInfo.getView());
    if (itr != _viewBlendColourMap.end())
    {
        Text::drawImplementation(*renderInfo.getState(), itr->second );
    }
    else
    {
        Text::drawImplementation(*renderInfo.getState(), osg::Vec4(1.0f,1.0f,1.0f,1.0f) );
    }


    // now pass on new details

    FadeTextUserData* userData = dynamic_cast<FadeTextUserData*>(renderInfo.getUserData());
    if (!userData)
    {
        if (renderInfo.getUserData())
        {
            OSG_NOTICE<<"Warning user data not of supported type."<<std::endl;
            return;
        }

        userData = getGlobalFadeText()->createNewFadeTextUserData(renderInfo.getView());

        if (!userData)
        {
            OSG_NOTICE<<"Memory error, unable to create FadeTextUserData."<<std::endl;
            return;
        }

        renderInfo.setUserData(userData);
    }

    unsigned int frameNumber = renderInfo.getState()->getFrameStamp()->getFrameNumber();
    if (frameNumber != userData->_frameNumber)
    {
        // new frame so must reset UserData structure.
        userData->_frameNumber = frameNumber;
        userData->_fadeTextInView.clear();
    }



    osgText::Text::AutoTransformCache& atc = _autoTransformCache[renderInfo.getContextID()];

    osg::Matrix lmv = atc._matrix;
    lmv.postMult(state.getModelViewMatrix());

    if (renderInfo.getView() && renderInfo.getView()->getCamera())
    {
        // move from camera into the view space.
        lmv.postMult(state.getInitialInverseViewMatrix());
        lmv.postMult(renderInfo.getView()->getCamera()->getViewMatrix());
    }

    FadeTextData ftd(const_cast<osgText::FadeText*>(this));

    ftd._vertices[0].set(osg::Vec3d(_textBB.xMin(),_textBB.yMin(),_textBB.zMin())*lmv);
    ftd._vertices[1].set(osg::Vec3d(_textBB.xMax(),_textBB.yMin(),_textBB.zMin())*lmv);
    ftd._vertices[2].set(osg::Vec3d(_textBB.xMax(),_textBB.yMax(),_textBB.zMin())*lmv);
    ftd._vertices[3].set(osg::Vec3d(_textBB.xMin(),_textBB.yMax(),_textBB.zMin())*lmv);

    userData->_fadeTextInView.push_back(ftd);

}
Пример #17
0
void CEGUIDrawable::drawImplementation( osg::RenderInfo& renderInfo ) const
{
    unsigned int contextID = renderInfo.getContextID();
    
    if ( !_initialized )
    {

        OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);

        if ( !_initialized )
        {
        CEGUI::OpenGLRenderer::bootstrapSystem( CEGUI::OpenGLRenderer::TTT_NONE );
        if ( !CEGUI::System::getSingletonPtr() ) return;

        CEGUI::DefaultResourceProvider* resource =
            static_cast<CEGUI::DefaultResourceProvider*>( CEGUI::System::getSingleton().getResourceProvider() );
        resource->setResourceGroupDirectory( "schemes", "./datafiles/schemes/" );
        resource->setResourceGroupDirectory( "imagesets", "./datafiles/imagesets/" );
        resource->setResourceGroupDirectory( "fonts", "./datafiles/fonts/" );
        resource->setResourceGroupDirectory( "layouts", "./datafiles/layouts/" );
        resource->setResourceGroupDirectory( "looknfeels", "./datafiles/looknfeel/" );
        resource->setResourceGroupDirectory( "lua_scripts", "./datafiles/lua_scripts/" );

        CEGUI::ImageManager::setImagesetDefaultResourceGroup( "imagesets" );
        CEGUI::Font::setDefaultResourceGroup( "fonts" );
        CEGUI::Scheme::setDefaultResourceGroup( "schemes" );
        CEGUI::WidgetLookManager::setDefaultResourceGroup( "looknfeels" );
        CEGUI::WindowManager::setDefaultResourceGroup( "layouts" );
        CEGUI::ScriptModule::setDefaultResourceGroup( "lua_scripts" );

         ready_for_init_signal_();
        _activeContextID = contextID;
        _initialized = true;
        }
   }
    else if ( contextID==_activeContextID )
    {
        osg::State* state = renderInfo.getState();
        state->disableAllVertexArrays();
        state->disableTexCoordPointer( 0 );
        auto tex_unit = state->getActiveTextureUnit();
		state->setActiveTextureUnit(0);
        
		glPushMatrix();
        glPushAttrib( GL_ALL_ATTRIB_BITS );

        CEGUI::OpenGLRenderer* renderer = static_cast<CEGUI::OpenGLRenderer*>(
            CEGUI::System::getSingleton().getRenderer() );
        osg::Viewport* viewport = renderInfo.getCurrentCamera()->getViewport();
        if ( renderer && viewport )
        {
            const CEGUI::Sizef& size = renderer->getDisplaySize();
            if ( size.d_width!=viewport->width() || size.d_height!=viewport->height() )
            {
                CEGUI::System::getSingleton().notifyDisplaySizeChanged(
                    CEGUI::Sizef(viewport->width(), viewport->height()) );
            }
        }

        double currentTime = (state->getFrameStamp() ? state->getFrameStamp()->getSimulationTime() : 0.0);
        CEGUI::System::getSingleton().injectTimePulse( (currentTime - _lastSimulationTime)/1000.0 );
        CEGUI::System::getSingleton().renderAllGUIContexts();
        _lastSimulationTime = currentTime;

        glPopAttrib();
        glPopMatrix();

        state->setActiveTextureUnit(tex_unit);
    }

}
void HBAODrawCallback::operator()( osg::RenderInfo& renderInfo ) const
{
    osg::State& state = *(renderInfo.getState());
    if ( !_aoContext )
    {
        // Initialize AO
        HBAODrawCallback* nonconst = const_cast<HBAODrawCallback*>( this );
        if ( !nonconst->initializeContext(renderInfo) ) return;
    }
    
    // Handle scene elements
    osg::Matrixf projMatrix = state.getProjectionMatrix();
    osg::Matrixf viewMatrix = state.getModelViewMatrix();
    if ( !_depthTexture || !_outputTexture ) return;
    
    unsigned int contextID = renderInfo.getContextID();
    GLuint fboID = _fbo->getHandle(contextID);
    if ( _dirtyFBO )
    {
        _fbo->setAttachment( osg::Camera::COLOR_BUFFER,
                             osg::FrameBufferAttachment(_outputTexture.get()) );
        _dirtyFBO = false;
    }
    
    if ( fboID==0 )
    {
        _fbo->apply( state );
        fboID = _fbo->getHandle(contextID);
    }
    
    osg::Texture::TextureObject* depthObj = _depthTexture->getTextureObject(contextID);
    osg::Texture::TextureObject* normalObj =
        _normalTexture.valid() ? _normalTexture->getTextureObject(contextID) : NULL;
    if ( fboID==0 || !depthObj ) return;
    
    // Render AO
    GFSDK_SSAO_Parameters_GL aoParams;
    aoParams.Radius = 2.0f;
    aoParams.Bias = 0.2f;
    aoParams.DetailAO = 1.0f;
    aoParams.CoarseAO = 1.0f;
    aoParams.DepthStorage = GFSDK_SSAO_FP32_VIEW_DEPTHS;//GFSDK_SSAO_FP16_VIEW_DEPTHS;
    aoParams.PowerExponent = 10.0f;
    aoParams.Output.BlendMode = GFSDK_SSAO_OVERWRITE_RGB;
    aoParams.Blur.Enable = true;
    aoParams.Blur.Sharpness = 4.0f;
    aoParams.Blur.Radius = GFSDK_SSAO_BLUR_RADIUS_2;//GFSDK_SSAO_BLUR_RADIUS_4;//GFSDK_SSAO_BLUR_RADIUS_8;
    
    GFSDK_SSAO_InputData_GL input;
    input.DepthData.DepthTextureType = GFSDK_SSAO_HARDWARE_DEPTHS;
    input.DepthData.FullResDepthTexture = GFSDK_SSAO_Texture_GL(GL_TEXTURE_2D, depthObj->id());
    input.DepthData.ProjectionMatrix.Data = GFSDK_SSAO_Float4x4(projMatrix.ptr());
    input.DepthData.ProjectionMatrix.Layout = GFSDK_SSAO_ROW_MAJOR_ORDER;
    input.DepthData.MetersToViewSpaceUnits = 1.0f;
    if ( normalObj )
    {
        input.NormalData.Enable = true;
        input.NormalData.FullResNormalTexture = GFSDK_SSAO_Texture_GL(GL_TEXTURE_2D, normalObj->id());
        input.NormalData.WorldToViewMatrix.Data = GFSDK_SSAO_Float4x4(viewMatrix.ptr());
        input.NormalData.WorldToViewMatrix.Layout = GFSDK_SSAO_ROW_MAJOR_ORDER;
        input.NormalData.DecodeScale = 2.0f;
        input.NormalData.DecodeBias = -1.0f;
    }
    
    GFSDK_SSAO_RenderMask renderMask = GFSDK_SSAO_RENDER_AO;//GFSDK_SSAO_RENDER_DEBUG_NORMAL;
    glDisable( GL_DEPTH_TEST );
    
    GFSDK_SSAO_Status status = _aoContext->RenderAO( &input, &aoParams, fboID, renderMask );
    if ( status!=GFSDK_SSAO_OK )
    {
        OSG_WARN << "[HBAODrawCallback] Failed to render AO: " << status << std::endl;
    }
}
Пример #19
0
        virtual void drawImplementation(osg::RenderInfo& renderInfo) const
        {
        #if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE) && !defined(OSG_GL3_AVAILABLE)

            if( renderInfo.getContextID() != _contextID )
                return;


            float vx = 0.0f;
            float vy = 0.0f;
            float vw = 1.0f;
            float vh = 1.0f;
            if (_viewport.valid())
            {
                vx = _viewport->x();
                vy = _viewport->y();
                vw = _viewport->width();
                vh = _viewport->height();
            }

            glMatrixMode( GL_PROJECTION );
            glPushMatrix();
            glLoadIdentity();
            glOrtho( 0.0, vw, 0.0, vh, -1.0, 1.0 );

            glMatrixMode( GL_MODELVIEW );
            glPushMatrix();
            glLoadIdentity();

            glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );

            Images::const_iterator p;
            float th = 0.0;
            for( p = _logos[Center].begin(); p != _logos[Center].end(); p++ )
            {
                th += (*p)->t();
            }

            float place[][4] = {
                { vw*0.5f, ((vh*0.5f) + th*0.5f), -0.5f, -1.0f },
                { vx, vh, 0.0f, -1.0f },
                { vw, vh, -1.0f, -1.0f },
                { vx, vy, 0.0f, 1.0f },
                { vw, vy, -1.0f, 1.0f },
                { vw*0.5f, vh , -0.5f, -1.0f },
                { vw*0.5f, 0.0f , -0.5f, 1.0f },
            };

            for( int i = Center; i < last_position; i++ )
            {
                if( _logos[i].size() != 0 )
                {
                    float x = place[i][0];
                    float y = place[i][1];
                    float xi = place[i][2];
                    float yi = place[i][3];
                    for( p = _logos[i].begin(); p != _logos[i].end(); p++ )
                    {
                        osg::Image *img = (*p).get();
                        glPixelStorei(GL_UNPACK_ALIGNMENT, img->getPacking());
                        glPixelStorei(GL_UNPACK_ROW_LENGTH, img->getRowLength());
                        x = place[i][0] + xi * img->s();
                        if( i == Center || i == UpperLeft || i == UpperRight || i == UpperCenter)
                            y += yi * img->t();
                        glRasterPos2f( x, y );
                        glDrawPixels( img->s(), img->t(), img->getPixelFormat(), img->getDataType(), img->data() );
                        if( i == LowerLeft || i == LowerRight || i == LowerCenter)
                            y += yi * img->t();
                    }
                }
            }

            glPopMatrix();
            glMatrixMode( GL_PROJECTION );
            glPopMatrix();
            glMatrixMode( GL_MODELVIEW );
        #else
            OSG_NOTICE<<"Warning: Logos::drawImplementation(..) not supported."<<std::endl;
        #endif
        }