osg控制節點的顯示與否

使物體或者說Node隱藏方式有兩種,一種是設置NodeMask,另外一種是使用osg的switch類來控制。
兩者的區別是
前者只是看不到,數據還在場景中,隱藏了並不能影響渲染性能,不影響內存中的數據;

後者是從內存中暫時移除,會對性能有所影響,需要顯示時再加載進場景。


回調的速度好像是每幀調用一次,這樣程序運行起來,會看到球以很快的速度在閃。爲了更方便的觀察,我在回調中做了限制,每5000次取反一次進行顯示。


osg::Switch隱藏和顯示節點的接口有很多種組合方法,我在程序中有體現。將節點添加到Switch對象中,可以通過getChildIndex來獲取當前節點在Switch對象中的索引。


如果需要將Switch對象中節點全部隱藏和顯示,可以使用setAllChildrenOff和setAllChildrenOn接口。


完整程序:

#include <osg/Geode>
#include <osgViewer/Viewer>
#include <osg/ShapeDrawable>
#include <osg/Switch>

using namespace osg;
using namespace osgViewer;

#pragma  comment(lib,"osgd.lib")
#pragma  comment(lib,"osgViewerd.lib")

class NodeVisiableCallback :public NodeCallback
{
public:
	NodeVisiableCallback(unsigned int index) :_bVisiable(false), _childIndex(index), _tick(0){}
	~NodeVisiableCallback(){};

	virtual void operator()(Node* node, NodeVisitor* nv)
	{
		if (_tick < 5000)
		{
			_tick++;
			return;
		}
		else
		{
			_tick = 0;
		}
		ref_ptr<Switch> sw = dynamic_cast<Switch*>(node);
		if (sw)
			sw->setValue(_childIndex, _bVisiable = !_bVisiable);
	}
protected:
	bool _bVisiable;
	unsigned int _tick;
	unsigned int _childIndex;
};

int main(int argc, char **argv)
{
	Viewer viewer;

	ref_ptr<Group> group = new Group;
	
	ref_ptr<Geode> node1 = new Geode;
	ref_ptr<Geode> node2 = new Geode;

	ref_ptr<ShapeDrawable> sphere1 = new ShapeDrawable(new Sphere(Vec3(10, 0, 0), 2.f));
	ref_ptr<ShapeDrawable> sphere2 = new ShapeDrawable(new Sphere(Vec3(-10, 0, 0), 2.f));

	node1->addDrawable(sphere1);
	node2->addDrawable(sphere2);

	ref_ptr<Switch> sw = new Switch;
	//on
	sw->addChild(node1);
	sw->setUpdateCallback(new NodeVisiableCallback(sw->getChildIndex(node1)));
	//off 1
	//sw->addChild(node1,0);
	//off 2
	//sw->addChild(node1);
	//sw->setChildValue(node1, 0);
	//off 3
	//sw->addChild(node1);
	//sw->setValue(sw->getChildIndex(node1), 0);
	//off 4
	//sw->addChild(node1);
	//sw->setAllChildrenOff();

	group->addChild(sw);
	group->addChild(node2);

	viewer.setSceneData(group.get());
	
	viewer.realize();
	viewer.run();
}

本文地址:http://blog.csdn.net/u011417605/article/details/70237688

發佈了119 篇原創文章 · 獲贊 91 · 訪問量 45萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章