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();
}