|
class getWorldCoordOfNodeVisitor : public osg::NodeVisitor
{
public:
getWorldCoordOfNodeVisitor():
osg::NodeVisitor(NodeVisitor::TRAVERSE_PARENTS), done(false)
{
wcMatrix= new osg::Matrixd();
}
virtual void apply(osg::Node &node)
{
if (!done)
{
if ( 0 == node.getNumParents() ) //到达根节点,此时节点路径也已记录完整
{
wcMatrix->set( osg::computeLocalToWorld(this->getNodePath()) );
done = true;
}
traverse(node);
}
}
osg::Matrixd* giveUpDaMat()
{
return wcMatrix;
}
private:
bool done;
osg::Matrix* wcMatrix;
};
osg::Matrixd* getWorldCoords( osg::Node* node)
{
getWorldCoordOfNodeVisitor* ncv = new getWorldCoordOfNodeVisitor();
if (node && ncv)
{
node->accept(*ncv);
return ncv->giveUpDaMat();
}
else
{
return NULL;
}
}
void main()
{
osgViewer::Viewer viewer;
osg::ref_ptr <osg::Group> root = new osg::Group() ;
osg::ref_ptr<osg::Node> osgcool = osgDB::readNodeFile("cessna.osg") ;
osg::ref_ptr<osg::MatrixTransform> trans = new osg::MatrixTransform ;
trans ->setMatrix(osg::Matrix::translate(0, 0, 10)) ;
trans ->addChild(osgcool.get()) ;
osg::ref_ptr<osg::MatrixTransform> scale = new osg::MatrixTransform ;
scale ->setMatrix(osg::Matrix::scale(0.5,0.5,0.5)*osg::Matrix::translate(0, 0, -50)) ;
scale ->addChild(osgcool.get()) ;
root ->addChild(osgcool.get()) ;
root ->addChild(trans.get()) ;
root ->addChild(scale.get()) ;
//遍历世界坐标
osg::Matrixd *pmatrix0 = getWorldCoords(osgcool);
osg::Vec3 pVec0 = pmatrix0->getTrans();
osg::Matrixd *pmatrix1 = getWorldCoords(trans);
osg::Vec3 pVec1 = pmatrix1->getTrans();
osg::Matrixd *pmatrix2 = getWorldCoords(scale);
osg::Vec3 pVec2 = pmatrix2->getTrans();
viewer.setSceneData(root.get());
viewer.realize();
viewer.run();
}
/*
程序当中
osg::Matrixd *pmatrix0 = getWorldCoords(osgcool);
osg::Vec3 pVec0 = pmatrix->getTrans();
osg::Matrixd *pmatrix1 = getWorldCoords(trans);
osg::Vec3 pVec1 = pmatrix1->getTrans();
osg::Matrixd *pmatrix2 = getWorldCoords(scale);
osg::Vec3 pVec2 = pmatrix2->getTrans();
为什么pVec0和pVec1数值一样呢,即为什么pmatrix0和pmatrix1数值一样呢
我的理解应该是pmatrix0是单位矩阵,即pVec0是(0,0,0)
现在的结果是pVec0和pVec1都是(0,0,10),pVec2是(0,0,-50)。
*/
|
|