osg點選pick物體


osg已經實現了通過屏幕坐標直接與物體求交的方法。
能得到pick的物體,也能得到坐標。
我希望點擊大地形,根據點擊的點畫出直線。
屏幕坐標與世界坐標的轉換都會了,隨后實現這個功能。
#pragma once

#include <osgGA/GUIEventHandler>
#include <osgUtil/LineSegmentIntersector>
#include <osgViewer/Viewer>

class CPickHandler :  public osgGA::GUIEventHandler
{
public:
    CPickHandler(osgViewer::Viewer *viewer);
    ~CPickHandler( void);

    osgViewer::Viewer *m_pViewer;

     virtual  bool handle( const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa);

     void pick( float fX, float fY);
};

#include  " StdAfx.h "
#include  " PickHandler.h "

CPickHandler::CPickHandler(osgViewer::Viewer *viewer):m_pViewer(viewer)
{
}


CPickHandler::~CPickHandler( void)
{
}

bool CPickHandler::handle(  const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa )
{
     switch (ea.getEventType())
    {
     case(osgGA::GUIEventAdapter::PUSH):
        {
             if (ea.getButton() ==  1)
            {
                pick(ea.getX(),ea.getY());
            }
             return  true;
        }
    }

     return  false;
}

void CPickHandler::pick(  float fX, float fY )
{
    osgUtil::LineSegmentIntersector::Intersections intersections;
     if (m_pViewer->computeIntersections(fX,fY,intersections))
    {
         for (auto itr=intersections.begin();itr!=intersections.end();++itr)
        {
             if (!itr->nodePath.empty())
            {
                 const osg::NodePath& np = itr->nodePath;
                 for ( int i=np.size()- 1;i>= 0;--i)
                {
                    osg::ref_ptr<osg::Node> node = dynamic_cast<osg::Node *>(np[i]);
                     if (NULL != node && node->getName().compare( " cow ") ==  0)
                    {
                        node->setNodeMask( 0);
                         // itr->getWorldIntersectPoint(); // 得到坐標
                    }
                }
            }
        }
    }
}
屏幕坐標與世界坐標轉換
osg::Vec3 DrawCallback::getPoint()
{
    osg::Vec3 vec3;

    osg::ref_ptr<osgViewer::Viewer> viewer = dynamic_cast<osgViewer::Viewer *>(m_pAA);
    osg::ref_ptr<osg::Camera> camera = viewer->getCamera();
    osgViewer::Renderer *render = dynamic_cast<osgViewer::Renderer *>(camera->getRenderer());
    osgUtil::SceneView *sceneView = render->getSceneView( 0);

    osg::Vec3 vScreen(m_pEA->getX(),m_pEA->getY(), 0);
    osg::Vec3 window;
    sceneView->projectWindowIntoObject(vScreen,window);

    osg::Matrix mVPW = camera->getViewMatrix() * camera->getProjectionMatrix() * camera->getViewport()->computeWindowMatrix();
    osg::Matrix invertVPW;
    invertVPW.invert(mVPW);

    vec3 = window * invertVPW;

     return vec3;
}
1.配置MD
2.配置x64
3.找到mfc example
4.寫callback
5.創建一個節點掛到根節點下,為這個節點設置一個回調器。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM