欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

osg绘制立体几何

程序员文章站 2022-06-10 21:01:13
...

根据网友的代码,实现了,然后自己画出来立方体什么的,发现并不难。。。加入顶点坐标然后根据坐标数组进行绘制

一、openGL中,定义了10种图元:GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP, GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_QUADS, GL_QUAD_STRIP, GL_POLYGON

十种图元的作用比较简单,就不多介绍。

二、OSG中图元的设置是通过

bool addPrimitiveSet(PrimitiveSet* primitiveset);

所有图元类都继承于PrimitiveSet,不同的图元类可以以不同的方式解释顶点数组(不仅仅是OpenGL的那些方式)

四、osg::DrawArrays

五、osg::DrawElementsUInt

此类依赖两个东西解释顶点数组,第一个当然是顶点数组了,第二个是个索引数组。索引数组是什么呢?举个例子。

有如下两个三角形(ABC)(BCD),如果想以GL_TRIANGLES方式绘制,如果用DrawArrays,就要往顶点数组中插6个顶点ABCBCD,如果三角面巨多,有这么多重复顶点是不可接受的。而使用osg::DrawElementsUInt可以解决此问题。

DrawElementsUInt接受一个索引数组IndexArray,是对顶点数组的索引,如此顶点数组中就可以只放ABCD四个顶点,而索引数组为(123234)6个数字,这样存储代价就小了许多。

DrawElemetnsUInt(osg::PrimitiveSet::TRIANGLES, IndexArray->size(), &IndexArray->front())

#include <Windows.h>
#include <osgViewer/Viewer>
#include <osg/Group>
#include <osgDB/ReadFile>

int main(void)
{
osg::ref_ptrosgViewer::Viewer viewer = new osgViewer::Viewer;

osg::ref_ptr<osg::Group> sceneRoot = new osg::Group;

//创建几何体
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry;
osg::Vec4dArray* color = new osg::Vec4dArray;
color->push_back(osg::Vec4d(0.0, 0.0, 1.0, 1.0));
geometry->setColorArray(color);
osg::Vec3Array* vecArray = new osg::Vec3Array;
vecArray->push_back(osg::Vec3d(0.0,0.0,0.0));
vecArray->push_back(osg::Vec3d(4.0,0.0,0.0));
vecArray->push_back(osg::Vec3d(2.0, 4.0, 0.0));
vecArray->push_back(osg::Vec3d(2.0, 2.0, 4.0));
geometry->setVertexArray(vecArray);

osg::ref_ptr<osg::DrawElementsUInt> drawElemUInt = new osg::DrawElementsUInt(GL_TRIANGLE_FAN);
drawElemUInt->push_back(0);
drawElemUInt->push_back(1);
drawElemUInt->push_back(1);
drawElemUInt->push_back(2);
drawElemUInt->push_back(2);
drawElemUInt->push_back(0);

drawElemUInt->push_back(0);
drawElemUInt->push_back(1);
drawElemUInt->push_back(1);
drawElemUInt->push_back(3);
drawElemUInt->push_back(3);
drawElemUInt->push_back(0);

drawElemUInt->push_back(0);
drawElemUInt->push_back(2);
drawElemUInt->push_back(2);
drawElemUInt->push_back(3);
drawElemUInt->push_back(3);
drawElemUInt->push_back(0);


drawElemUInt->push_back(1);
drawElemUInt->push_back(3);
drawElemUInt->push_back(3);
drawElemUInt->push_back(2);
drawElemUInt->push_back(2);
drawElemUInt->push_back(1);

geometry->addPrimitiveSet(drawElemUInt);
osg::Geode* geode = new osg::Geode;
geode->addDrawable(geometry);

sceneRoot->addChild(geode);

viewer->setSceneData(sceneRoot);
viewer->realize();
return viewer->run();

}

相关标签: OSG