用一张图片来修改osgViewer的背景
程序员文章站
2022-05-31 10:01:58
...
由于刚开始学习OSG的内容,对相机的理解并不是太深刻,工作中也出现了这个需求,于是决定好好研究一下。对于修改背景图片这个知识点确实不是太难,但是由于之前对于相机的理解太浅,所以这次还是收获很大的。主要是学习了《OSG视频》之后,自己凭借理解有重新编写出的Demo程序,实现效果还可以。下面给出创建背景文理相机的具体代码(开发环境:VS2013+Qt5.7.0+OSG3.4.0):
osg::Camera* createBackground(QString imageFilePath)
{
osg::ref_ptr<osg::Camera> camera = new osg::Camera;
camera->setProjectionMatrixAsOrtho2D(0, 800, 0, 600);
camera->setClearMask(GL_DEPTH_BUFFER_BIT);
camera->setViewport(0, 0, 800, 600);
camera->setViewMatrix(osg::Matrix::identity());
camera->setAllowEventFocus(false);
camera->setRenderOrder(osg::Camera::PRE_RENDER);
camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
camera->addChild(geode);
osg::ref_ptr<osg::Geometry> gm = new osg::Geometry;
geode->addDrawable(gm);
geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
osg::ref_ptr<osg::Vec3Array> vertex = new osg::Vec3Array;
vertex->push_back(osg::Vec3(0, 0, 0));
vertex->push_back(osg::Vec3(800, 0, 0));
vertex->push_back(osg::Vec3(800, 600, 0));
vertex->push_back(osg::Vec3(0, 600, 0));
gm->setVertexArray(vertex);
osg::ref_ptr<osg::Vec3Array> normal = new osg::Vec3Array;
normal->push_back(osg::Vec3(0, 0, 1));
gm->setNormalArray(normal);
gm->setNormalBinding(osg::Geometry::BIND_OVERALL);
osg::ref_ptr<osg::Vec2Array> coord = new osg::Vec2Array;
coord->push_back(osg::Vec2(0, 0));
coord->push_back(osg::Vec2(1, 0));
coord->push_back(osg::Vec2(1, 1));
coord->push_back(osg::Vec2(0, 1));
gm->setTexCoordArray(0, coord);
gm->addPrimitiveSet(new osg::DrawArrays(osg::DrawArrays::QUADS,0,4));
osg::ref_ptr<osg::Image> image = osgDB::readImageFile(imageFilePath.toStdString());
osg::ref_ptr<osg::Texture2D> t2d = new osg::Texture2D;
t2d->setImage(image);
gm->getOrCreateStateSet()->setTextureAttributeAndModes(0, t2d, osg::StateAttribute::ON);
return camera.release();
}
具体的理解是:首先创建一个辅助相机,这个相机就是整个显示界面的背景相机,其他模型的绘制都是在这个相机之上绘制的,代码最上面几行是对相机进行参数初始化,每一个参数都很重要。剩下的就是如何贴一张图片的功能代码了
运行效果图如下:
下一篇: PHP内核-源码安装与介绍详解