class PickEvent : public osgGA::GUIEventHandler
{
public:
PickEvent(osg::Geometry* drawable) : _drawable(drawable){}
~PickEvent(){}
public:
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
if (ea.getEventType() == osgGA::GUIEventAdapter::PUSH)
{
osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa);
double x = ea.getX();
double y = ea.getY();
osg::Matrix mat = viewer->getCamera()->getViewMatrix() * viewer->getCamera()->getProjectionMatrix();
mat = mat * viewer->getCamera()->getViewport()->computeWindowMatrix();
osg::Matrix inversemat = osg::Matrix::inverse(mat);
osg::Vec3d v3start = osg::Vec3d(ea.getX(), ea.getY(), 0.0) * inversemat;
osg::Vec3d v3end = osg::Vec3d(ea.getX(), ea.getY(), 1.0) * inversemat;
osg::TriangleFunctor<MyTestPicker::TriangleIntersector> intersector;
intersector.set(v3start, v3end);
_drawable->accept(intersector);
MyTestPicker::TriangleIntersections::iterator it = intersector._intersections.begin();
std::pair<const float,MyTestPicker::TriangleIntersection> ps = *it;
osg::Vec3d v1 = *(ps.second._v1);
osg::Vec3d v2 = *(ps.second._v2);
osg::Vec3d v3 = *(ps.second._v3);
osg::Sphere* sphere = new osg::Sphere;
sphere->setCenter(v1);
sphere->setRadius(1);
osg::ShapeDrawable* shapeDrawable = new osg::ShapeDrawable(sphere);
osg::Geode* geode = new osg::Geode;
geode->addDrawable(shapeDrawable);
osg::Camera* camera = viewer->getCamera();
camera->addChild(geode);
}
return false;
}
public:
osg::Transform* _transform;
osg::Geometry* _drawable;
};
void main()
{
osgViewer::Viewer viewer;
osg::Node* node = osgDB::readNodeFile("D://cow.osg");
osg::Group* group = dynamic_cast<osg::Group*>(node);
osg::Node* child = group->getChild(0);
osg::Geode* geode = dynamic_cast<osg::Geode*>(child);
osg::Geometry* drawable = (osg::Geometry*)geode->getDrawable(0);
viewer.addEventHandler(new PickEvent(drawable));
viewer.setSceneData(group);
return viewer.run();
}
}