OSG 学习第三课:绘制彩色正方形

彩色正方形效果图

效果图

代码

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


©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容