OSG获取模型XYZ范围并生成最小包围盒

#include <osgDB/ReadFile>
#include <osgDB/FileUtils>
#include <osg/Group>
#include <osg/ShapeDrawable>  
#include <osg/PolygonMode>
#include <osg/LineWidth>
#include <osg/MatrixTransform>
#include <osg/ComputeBoundsVisitor>
#include <osgViewer/Viewer>

osg::ref_ptr<osg::Node> cretateBoundingBox(osg::Node * node)
{
    osg::ref_ptr<osg::Geode> geode = new osg::Geode();
    osg::ComputeBoundsVisitor boundVisitor;
    node->accept(boundVisitor);
    osg::BoundingBox boundingBox = boundVisitor.getBoundingBox();

    //输出XYZ范围及中心点坐标
    osg::notify(osg::ALWAYS) << "bouding box info" << std::endl;
    osg::notify(osg::ALWAYS) << "xMax: " << boundingBox.xMax() << std::endl;
    osg::notify(osg::ALWAYS) << "xMin: " << boundingBox.xMin() << std::endl;
    osg::notify(osg::ALWAYS) << "yMax: " << boundingBox.yMax() << std::endl;
    osg::notify(osg::ALWAYS) << "yMin: " << boundingBox.yMin() << std::endl;
    osg::notify(osg::ALWAYS) << "zMax: " << boundingBox.zMax() << std::endl;
    osg::notify(osg::ALWAYS) << "zMin: " << boundingBox.zMin() << std::endl;
    osg::notify(osg::ALWAYS) << "center: x=" << boundingBox.center().x() 
        << ",y=" << boundingBox.center().y() 
        << ",z=" << boundingBox.center().z() << std::endl;

    float length = boundingBox.xMax() - boundingBox.xMin();
    float width = boundingBox.yMax() - boundingBox.yMin();
    float height = boundingBox.zMax() - boundingBox.zMin();
    osg::ref_ptr<osg::ShapeDrawable> drawable = new osg::ShapeDrawable(
        new osg::Box(boundingBox.center(), length, width, height));
    drawable->setColor(osg::Vec4(1.0, 1.0, 0.0, 1.0));

    osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet;
    stateset = drawable->getOrCreateStateSet();
    osg::ref_ptr<osg::PolygonMode> polygonMode = new osg::PolygonMode(
        osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE);
    stateset->setAttributeAndModes(polygonMode);

    osg::ref_ptr<osg::LineWidth> linewidth = new osg::LineWidth(3.0);
    stateset->setAttribute(linewidth);

    geode->addDrawable(drawable);
    return geode;
}

void main()
{
    osgDB::getDataFilePathList().push_back("F:\\OSGWorkspace\\osgOcean\\OpenSceneGraph\\data");
    osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer();
    viewer->setUpViewInWindow(100, 100, 1024, 768);

    osg::ref_ptr<osg::Group> root = new osg::Group();
    osg::ref_ptr<osg::Node> cow = osgDB::readNodeFile("cow.osg");
    osg::ref_ptr<osg::MatrixTransform> cowMt = new osg::MatrixTransform(osg::Matrix::translate(0,0,0));
    cowMt->addChild(cow);
    osg::ref_ptr<osg::Node> cowBoundingBox = cretateBoundingBox(cowMt);

    root->addChild(cowMt);
    root->addChild(cowBoundingBox);

    viewer->setSceneData(root.get());
    viewer->realize();
    viewer->run();
}

运行截图:

OSG获取模型XYZ范围并生成最小包围盒_第1张图片

OSG获取模型XYZ范围并生成最小包围盒_第2张图片

你可能感兴趣的:(工作记录)