int main()
{
osg::Cylinder* cylinder = new osg::Cylinder(osg::Vec3(0.f, 0.f, 0.f), 2.0f, 10.0f);
osg::ShapeDrawable* sd = new osg::ShapeDrawable(cylinder);
sd->setColor(osg::Vec4(0.8f, 0.5f, 0.2f, 1.f));
osg::Geode* geode = new osg::Geode;
geode->addDrawable(sd);
osg::ref_ptr<osg::ClipPlane> clipPlane = new osg::ClipPlane(0,0.6,0,0.8, 1);//截断平面
osg::ref_ptr<osg::ClipNode> clipNode = new osg::ClipNode();
clipNode->addClipPlane(clipPlane.get());
clipNode->addChild(geode);
clipNode->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
osg::ref_ptr<osg::Group> root = new osg::Group();
root->addChild(clipNode.get());
osgViewer::Viewer viewer;
viewer.setSceneData(root.get());
//如果 面求交
osg::ref_ptr<osgUtil::IntersectorGroup> intersectorGroup = new osgUtil::IntersectorGroup();
osg::ref_ptr<osgUtil::PlaneIntersector> plane = new osgUtil::PlaneIntersector(osg::Plane(0.6, 0, 0.8, 1));
intersectorGroup->addIntersector(plane.get());
//遍历整个节点树(也可以是某个子树或几何体节点)
osgUtil::IntersectionVisitor intersectVisitor(intersectorGroup.get());
geode->accept(intersectVisitor);
osg::Vec3Array* coords = new osg::Vec3Array;
if (intersectorGroup->containsIntersections())
{//有交点
std::cout << "Found intersections " << std::endl;
osgUtil::IntersectorGroup::Intersectors& intersectors = intersectorGroup->getIntersectors();
for (osgUtil::IntersectorGroup::Intersectors::iterator intersector_itr = intersectors.begin();
intersector_itr != intersectors.end();
++intersector_itr)
{
osgUtil::PlaneIntersector* lsi = dynamic_cast<osgUtil::PlaneIntersector*>(intersector_itr->get());
if (lsi)
{
osgUtil::PlaneIntersector::Intersections& intersections = lsi->getIntersections();
std::cout << intersections.size() << std::endl;
osgUtil::PlaneIntersector::Intersections::iterator itr;
for (itr = intersections.begin();
itr != intersections.end();
++itr)
{
osgUtil::PlaneIntersector::Intersection& intersection = *itr;
// OSG_NOTICE<<" transforming "<<std::endl;
// transform points on polyline
for (osgUtil::PlaneIntersector::Intersection::Polyline::iterator pitr = intersection.polyline.begin();
pitr != intersection.polyline.end();
++pitr)
{
if (intersection.matrix.valid())
{
*pitr = (*pitr) * (*intersection.matrix);
}
coords->push_back(*pitr+osg::Vec3d(5,0,0));
std::cout << "pos=" << (*pitr).x() << "," << (*pitr).y() << "," << (*pitr).z() << std::endl;
}
}
}
}
}
//相交的面
if (coords->size() > 3)
{
osg::ref_ptr<osgUtil::DelaunayTriangulator> dt = new osgUtil::DelaunayTriangulator();
// 添加点坐标
dt->setInputPointArray(coords);
dt->triangulate();
osg::DrawElementsUInt* pElem = dt->getTriangles();
osg::ref_ptr<osg::Geometry> ClipPlane = new osg::Geometry();
ClipPlane->setVertexArray(coords);
ClipPlane->addPrimitiveSet(pElem);
geode->addDrawable(ClipPlane.get());
}
viewer.run();
}
运行结果: