OSG模型控制
标签(空格分隔): OSG
OSG中模型控制主要是控制场景中的数据,包括移动、缩放模型、对模型位置求解、隐藏显示模型,不包括视口的控制。
基本操作
基本操作为添加、删除、隐藏、开关模型详细代码为
#ifdef _DEBUG
#pragma comment(lib,"osgViewerd.lib")
#pragma comment(lib,"osgDBd.lib")
#pragma comment(lib,"OpenThreadsd.lib")
#pragma comment(lib,"osgd.lib")
#else
#pragma comment(lib,"osgViewer.lib")
#pragma comment(lib,"osgDB.lib")
#pragma comment(lib,"OpenThreads.lib")
#pragma comment(lib,"osg.lib")
#endif
#include <osgViewer/viewer>
#include <osgDB/readfile>
using namespace osg;
int main()
{
ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer;
viewer->setUpViewOnSingleScreen();
//添加节点
ref_ptr<Group> gp = new Group;
Node* glider = osgDB::readNodeFile("glider.osg");
Node* osgcool = osgDB::readNodeFile("osgcool.osgt");
gp->addChild(glider);
gp->addChild(osgcool);
//删除节点
//gp->removeChild(glider);
//隐藏节点
osgcool->setNodeMask(0);
viewer->setSceneData(gp);
return viewer->run();
}
其中隐藏模型是暂时在场景中消失,内存中仍然存在,并且仍在渲染,系统资源并没有减少。开关模型则是在内存中将模型消除。
开关的简单代码如下:
int main()
{
ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer;
viewer->setUpViewOnSingleScreen();
//添加节点
ref_ptr<Group> gp = new Group;
Node* glider = osgDB::readNodeFile("glider.osg");
Node* osgcool = osgDB::readNodeFile("osgcool.osgt");
Switch* sw = new Switch();
sw->addChild(glider,false);
sw->addChild(osgcool);
gp->addChild(sw);
viewer->setSceneData(gp);
return viewer->run();
}
结果
移动、旋转、缩放
对模型最常见的操作是移动,其次是选择缩放。OSG通常将模型放在场景中央。
移动旋转缩放都是对模型节点的矩阵乘法操作。在OSG中,矩阵可以当作某个节点的子节点加入场景中。代码为
#ifdef _DEBUG
#pragma comment(lib,"osgViewerd.lib")
#pragma comment(lib,"osgDBd.lib")
#pragma comment(lib,"OpenThreadsd.lib")
#pragma comment(lib,"osgd.lib")
#else
#pragma comment(lib,"osgViewer.lib")
#pragma comment(lib,"osgDB.lib")
#pragma comment(lib,"OpenThreads.lib")
#pragma comment(lib,"osg.lib")
#endif
#include <osgViewer/viewer>
#include <osgDB/readfile>
#include <osg/MatrixTransform>
using namespace osg;
int main()
{
ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer;
viewer->setUpViewOnSingleScreen();
//添加节点
ref_ptr<Group> gp = new Group;
Node* osgcool = osgDB::readNodeFile("osgcool.osgt");
gp->addChild(osgcool);
//z轴向上平移2个单位
ref_ptr<MatrixTransform> trans = new MatrixTransform;
trans->setMatrix(Matrix::translate(0, 0, 2));
trans->addChild(osgcool);
//缩小1倍并z轴向下平移2个单位
ref_ptr<MatrixTransform> scale = new MatrixTransform;
scale->setMatrix(Matrix::scale(.5f, .5f, .5f) * Matrix::translate(0, 0, -2));
scale->addChild(osgcool);
//缩小1倍并z轴向下平移2个单位 x轴向右平移2个单位 再x轴旋转45度
ref_ptr<MatrixTransform> rot = new MatrixTransform;
rot->setMatrix(Matrix::rotate(DegreesToRadians(45.0f),1.f,.0f,.0f) *
Matrix::scale(.5f, .5f, .5f) * Matrix::translate(4, 0, -2));
rot->addChild(osgcool);
gp->addChild(trans);
gp->addChild(scale);
gp->addChild(rot);
viewer->setSceneData(gp);
return viewer->run();
}