osg获取纹理节点纹理方法

class TextureVisitor:public osg::NodeVisitor
{
public:
TextureVisitor();
TextureVisitor(QString dirPath);
void apply(osg::Node& node);
void apply(osg::Geode& geode);
void apply(osg::StateSet* state);
/*
函数名称: getPaths
函数描述:
输入参数: 获取节点下的图片路径
输出参数:
函数返回:
函数备注:
*/
inline QStringList getPaths(){return _list;}

protected:
    QStringList _list;
    QString _dirPath;
};

TextureVisitor::TextureVisitor():osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN)
{
}

TextureVisitor::TextureVisitor(QString dirPath):osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN)
{
    _dirPath = dirPath;
}

void TextureVisitor::apply(osg::Node& node)
{
    if(node.getStateSet())
    {
        apply(node.getStateSet());
    }
    traverse(node);
}

void TextureVisitor::apply(osg::Geode& geode)
{
    if(geode.getStateSet())
    {
        apply(geode.getStateSet());
    }
    unsigned int cnt = geode.getNumDrawables();
    for(unsigned int i = 0; i < cnt; i++)
    {
        osg::Drawable* draw = geode.getDrawable(i);
        if(draw)
        {
            osg::StateSet *state = draw->getStateSet();
            if(state)
                apply(state);
        }
    }
    traverse(geode);
}

void TextureVisitor::apply(osg::StateSet* state)
{
    if(state == NULL)
        return;

    osg::StateSet::TextureAttributeList& texAttribList = state->getTextureAttributeList();
    for(unsigned int i = 0; i < texAttribList.size(); i++)
    {
        osg::Texture2D* tex2D = dynamic_cast(state->getTextureAttribute(i, osg::StateAttribute::TEXTURE));
        if(tex2D)
        {
            osg::Image *image = tex2D->getImage();
            if(image && image->valid())
            {
                QString path = QString::fromLocal8Bit(tex2D->getImage()->getFileName().data());
                if(!_list.contains(path))
                {
                    _list.append(path);
                    if(!_dirPath.isEmpty())
                    {
                        QFileInfo info(path);
                        QString newPath = _dirPath + "/" + info.fileName();
                        osgDB::writeImageFile(*image,newPath.toLocal8Bit().data());
                    }
                }
            }
        }
    }
}

导出节点所以存在的纹理图片

你可能感兴趣的:(C++,osg)