osgUtil.AddRangeOperator
是OpenSceneGraph中的一个实用工具类,用于添加新的数据到现有数据列表中。
osgUtil.AddRangeOperator
是用于批量添加数据的工具类。它可以用于添加图形数据、节点、状态等等。
class AddRangeOperator : public osg::Operation
{
public:
typedef std::vector<osg::Referenced*> Objects;
AddRangeOperator(Objects& objects):
osg::Operation("AddRangeOperator",false),
_objects(objects) {}
virtual void operator()(osg::Object* object)
{
osg::NodeVisitor* nv = dynamic_cast<osg::NodeVisitor*>(object);
if (nv)
{
for(unsigned int i=0; i<_objects.size(); ++i)
{
osg::Node* node = dynamic_cast<osg::Node*>(_objects[i]);
if (node) nv->addNode(*node);
osg::Drawable* drawable = dynamic_cast<osg::Drawable*>(_objects[i]);
if (drawable) nv->addDrawable(drawable);
osg::StateAttribute* attribute = dynamic_cast<osg::StateAttribute*>(_objects[i]);
if (attribute) nv->getState()->setAttribute(attribute, osg::StateAttribute::ON);
osg::StateSet* stateSet = dynamic_cast<osg::StateSet*>(_objects[i]);
if (stateSet) nv->getState()->merge(*stateSet);
}
}
}
protected:
Objects& _objects;
};
AddRangeOperator(Objects& objects)
参数含义:
objects
:需要添加的数据列表。operator()
virtual void operator()(osg::Object* object)
参数含义:
object
:需要添加数据的节点或节点访问器。osg::Node* loadedModel = osgDB::readNodeFile("cow.osg");
osg::Geometry* loadedGeometry = dynamic_cast<osg::Geometry*>(loadedModel->getOrCreateStateSet()->getAttribute(osg::StateAttribute::VERTEX));
osg::StateSet* loadedStateSet = loadedGeometry->getOrCreateStateSet();
osg::Node* newModel = osgDB::readNodeFile("teapot.osg");
osg::Geometry* newGeometry = dynamic_cast<osg::Geometry*>(newModel->getOrCreateStateSet()->getAttribute(osg::StateAttribute::VERTEX));
osg::StateSet* newStateSet = newGeometry->getOrCreateStateSet();
std::vector<osg::Referenced*> objectsToAdd;
objectsToAdd.push_back(newModel);
objectsToAdd.push_back(newGeometry);
objectsToAdd.push_back(newStateSet);
osg::ref_ptr<osgUtil::AddRangeOperator> addRangeOp = new osgUtil::AddRangeOperator(objectsToAdd);
loadedModel->accept(*addRangeOp);
该代码示例:加载cow.osg文件,提取其中的几何数据和状态集,然后加载teapot.osg文件,提取其中的几何数据和状态集。接着将需要添加的数据存储到std::vector
中,最后将处理器和存储需要添加的数据的std::vector
传递给AddRangeOperator
类的构造函数。最后,通过调用源模型的accept()
函数,将新的几何数据和状态集添加到源模型中。