OSG中嵌入一个opengl代码(且opengl图形能动态更新)
(1)继承osg::Drawable::DrawCallback,在
drawImplementation(osg::RenderInfo& renderInfo,const osg::Drawable* drawable)函数里添加opengl代码。
(2)Drawable设置绘制回调函数,并注意要把显示列表设置为false:
geometry->setUseDisplayList(false);
geometry->setDrawCallback(new DrawCallback);
――――――――――――
参考代码如下(改编自OSG的例子程序osgSpaceWarp):
#include "stdafx.h"
#include <osgViewer/Viewer>
#include <osg/Group>
#include <osg/Geometry>
#pragma comment( lib, "osgd.lib"); //.在Debug版本下的库名都加d,如"osgd.lib"
#pragma comment( lib, "osgDBd.lib")
#pragma comment( lib, "osgViewerd.lib");
#pragma comment( lib, "osgUtild.lib");
//opengl的头文件和库文件
#include <gl/gl.h>
#include <gl/glu.h>
#pragma comment(lib,"opengl32.lib")
#pragma comment(lib,"glu32.lib")
class DrawCallback : public osg::Drawable::DrawCallback
{
virtual void drawImplementation(osg::RenderInfo& renderInfo,const osg::Drawable* drawable) const
{
static double dColor= 0;//颜色
glColor3f( dColor, 0, 0);
glBegin(GL_TRIANGLES);//在OSG中画一个opengl三角形
glVertex3f( 0.0, 0.0, -2.0);
glVertex3f( 0.2, 0.0, -2.0);
glVertex3f( 0.0, 0.4, -2.0);
glEnd();
dColor += 0.01;//颜色渐变
if ( dColor > 1.0)
{
dColor= 0.0;
}
}
};
int main( int argc, char **argv )
{
osgViewer::Viewer viewer;
osg::Geometry* geometry = new osg::Geometry;
//此处一定要把显示列表设置为false,
//否则DrawCallback的drawImplementation()函数只会调用一次,而不是在画一帧时都动态更新opengl图形
geometry->setUseDisplayList(false);
geometry->setDrawCallback(new DrawCallback);//Drawable设置动态更新opengl图形
osg::Geode* geode = new osg::Geode;
geode->addDrawable(geometry);
geode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
osg::Group* group = new osg::Group;
group->addChild(geode);
viewer.setSceneData( group);
//return viewer.run();
osg::Matrix mt;
mt.makeIdentity();
while ( !viewer.done())
{
viewer.getCamera()->setViewMatrix( mt);
viewer.frame();
}
}