ogs中所有加入场景中的数据都会加入到一个Group类对象中,几何图元作为一个对象由osg::Geode类来组织管理。绘制几何图元对象时,先创建一个Geometry对象,这个对象中要设置绘制所需的基本信息,图元的顶点、顶点颜色、顶点关联方式以及法线。
#include <Windows.h>
#include <osgViewer/Viewer>
#include <osgDB/ReadFile>
#include <osg/Node>
#include <osg/Geode>
#include <osg/Geometry>
int main(int argc,char** argv)
{
osgViewer::Viewer view;
osg::Group* root = new osg::Group();
#pragma region 几何图元模块
osg::ref_ptr<osg::Geometry> geom = new osg::Geometry();
//定义顶点
osg::ref_ptr<osg::Vec3Array> v = new osg::Vec3Array();
geom->setVertexArray(v);
v->push_back(osg::Vec3(-1.f,0.f,1.f));
v->push_back(osg::Vec3(1.f,0.f,-1.f));
v->push_back(osg::Vec3(1.f,0.f,1.f));
//定义颜色数组
osg::ref_ptr<osg::Vec4Array> c =new osg::Vec4Array();
geom->setColorArray(c);
geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
c->push_back(osg::Vec4(1.f,0.f,0.f,1.f));
c->push_back(osg::Vec4(0.f,1.f,0.f,1.f));
c->push_back(osg::Vec4(0.f,0.f,1.f,1.f));
//定义法线
osg::ref_ptr<osg::Vec3Array> n = new osg::Vec3Array();
geom->setNormalArray(n);
geom->setNormalBinding(osg::Geometry::BIND_OVERALL);
n->push_back(osg::Vec3(0.f,-1.f,0.f));
//设置顶点关联方式
//PrimitiveSet类,这个类松散地封装了OpenGL的绘图基元,
//包括点(POINTS),线(LINES),多段线(LINE_STRIP),封闭线(LINE_LOOP),四边形(QUADS),多边形(POLYGON)等。
geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::POLYGON,0,3));
//几何组节点
osg::ref_ptr<osg::Geode> geo = new osg::Geode();
geo->addDrawable(geom);
#pragma endregion
root->addChild(geo);
view.setSceneData(root);
//view.realize();
view.run();
}