彩色正方形效果图
![](https://img.haomeiwen.com/i6491732/7bdb243d82ef8b44.png)
效果图
代码
#include <osgDB/ReadFile>
#include <osgViewer/Viewer>
#include <osg/MatrixTransform>
#include <osg/Geometry>
#include <osg/Node>
#include <osg/Geode>
osg::ref_ptr<osg::Node> createQuad() {
// 首先创建一个osg::Geometry,把这个Geometry对象加入到Geode类对象中。
// 这个Geometry对象中要设置绘制所需的基本信息:
// 图元顶点Vertex、顶点的颜色Color、顶点之间的关联方式PrimitiveSet和法线Normal
// Geometry类对象是被管理的几何体;
osg::ref_ptr<osg::Geometry> geom = new osg::Geometry;
// Geode类对象是用来专门管理可绘制几何体的;
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
// 定义四个顶点
osg::ref_ptr<osg::Vec3Array> v = new osg::Vec3Array;
geom->setVertexArray(v.get());
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));
v->push_back(osg::Vec3(-1.f, 0.f, 1.f));
// 定义颜色数组,设置绑定方式为逐点绑定;
osg::ref_ptr<osg::Vec4Array> c = new osg::Vec4Array;
geom->setColorArray(c.get());
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));
c->push_back(osg::Vec4(1.f, 1.f, 1.f, 1.f));
// 定义法线,法线为指向y轴负半轴,法线不同会影响光照的效果;
osg::ref_ptr<osg::Vec3Array> n = new osg::Vec3Array;
geom->setNormalArray(n.get());
geom->setNormalBinding(osg::Geometry::BIND_OVERALL);
n->push_back(osg::Vec3(0.f, -1.f, 0.f));
// 设置顶点关联方式
geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, 4));
geode->addDrawable(geom.get());
return geode.get();
}
void main()
{
osgViewer::Viewer viewer;
osg::Group* root = new osg::Group();
root->addChild(createQuad().get());
viewer.setSceneData(root);
viewer.realize();
viewer.run();
}
网友评论