# 利用osg::ClipPlane 对节点进行多边形裁切

ClipPlane是通过AX+BY+CZ+D的符号来判断裁切范围的

#include <osgViewer/Viewer>
#include <osg/Node>
#include <osg/Geode>
#include <osg/Group>
#include <osg/ClipPlane>
#include <osg/ShapeDrawable>
#include <osgUtil/Optimizer>

#include <Eigen/SVD>
#include <Eigen/Dense>

using namespace Eigen;

///过点A,B，计算一个与normal平行的平面
osg::Vec4d ComputePlane(osg::Vec3d A, osg::Vec3d B, osg::Vec3d normal) {
osg::Vec3d n = (B-A)^normal;//如果逆时针仍然无法显示，请调整A，B顺序
return osg::Vec4d(n, -n * A);
}
///用一堆三维点拟合一个平面,返回平面法向，算法：SVD
osg::Vec3d fitPlane(std::vector<osg::Vec3d> points) {
//中心化
int n = points.size();
osg::Vec3d center(0, 0, 0);
for (int i = 0; i < n; i++)
center += points[i];
center /= n;
MatrixXd A(n,3);
for (int i = 0; i < points.size(); i++) {
A(i, 0) = points[i].x() - center.x();
A(i, 1) = points[i].y() - center.y();
A(i, 2) = points[i].z() - center.z();
}
//AX=0的解 是SVD分解中的V的最后一列
JacobiSVD<Eigen::MatrixXd> svd(A, ComputeThinU | ComputeThinV);
MatrixXd V = svd.matrixV();
osg::Vec3d normal(V(2,0), V(2, 1), V(2, 2));
return normal;
}
osg::ref_ptr<osg::Node> createClipNode(std::vector<osg::Vec3d> trimPolygon, osg::ref_ptr<osg::Node> subgraph) {
osg::ref_ptr<osg::Group> root = new osg::Group();
osg::Vec3d n = fitPlane(trimPolygon);
trimPolygon.push_back(trimPolygon[0]);//a trick
for (int i = 1; i < trimPolygon.size(); i++) {
osg::Vec4d Plane = ComputePlane(trimPolygon[i - 1], trimPolygon[i], n);
osg::ref_ptr<osg::ClipPlane> cl= new osg::ClipPlane(i - 1, Plane);
root->getOrCreateStateSet()->setAttributeAndModes(cl.get(), osg::StateAttribute::ON);
}
root->setCullingActive(false);
return root.release();
}
int main()
{
//绘制长方体
osg::ref_ptr<osg::Geode> node = new osg::Geode;
osg::ref_ptr<osg::Box> box = new osg::Box(osg::Vec3(0.0, 0.0, 0.0),192*2,1,108*2);
//指定裁剪多边形顶点，只能裁剪凸多边形
//注意要逆时针指定，方向反了就都被裁剪掉了
std::vector<osg::Vec3d> pts;
pts.push_back(osg::Vec3d(128, 0, 0));
pts.push_back(osg::Vec3d(64, 0, 72));
pts.push_back(osg::Vec3d(-64, 0, 72));
pts.push_back(osg::Vec3d(-128, 0, 0));
pts.push_back(osg::Vec3d(-64, 0, -72));
pts.push_back(osg::Vec3d(64, 0, -72));
//裁切
osg::ref_ptr<osg::Node> Trim = createClipNode(pts, node);
//渲染
osgUtil::Optimizer optimizer;
optimizer.optimize(Trim.get());
osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer();
viewer->setSceneData(Trim.get());
viewer->setUpViewInWindow(600, 100, 800, 600);
viewer->run();

return 0;
}

• 0
点赞
• 7
收藏
觉得还不错? 一键收藏
• 打赏
• 6
评论
01-08 1239
06-22 4247
04-14 193
09-13 4957
08-15 173
05-17 743
04-03 1680
02-04 3372
05-06 787
02-11 2740
02-22
08-26
04-10
10-13 4707

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。