看了下网上的方法, 基本上可分为两种:
1. 在osg中创建结点, 比如Geometry对象, 然后给该对象添加DrawCallback, 在这个DrawCallback中使用opengl进行绘制
2. 创建一个Drawable的派生类, 在该类中重写drawImplementation()函数, 在该函数中使用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();
}
}
第二种方法, 差不太多的:
class MyDrawable : public osg::Drawable
{
public:
MyDrawable()
{
}
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/
MyDrawable(const MyDrawable& latlonline, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY) :
osg::Drawable(latlonline,copyop)
{
}
META_Object(osg, MyDrawable)
virtual void drawImplementation(osg::RenderInfo &renderInfo) const
{
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_LINE_LOOP);
float x,y;
double radious =osg::WGS_84_RADIUS_EQUATOR/10000 + 10; //radious为圆半径
radious = 0.3;
double step = 0.01f; //step为画圆的步长
for(double angle = 0.0f; angle <= osg::PI *2; angle += step)
{
x = radious *sin(angle);
y = radious *cos(angle);
glVertex3f(x, y, -2.0);
}
glEnd();
}
};