ClipPlane是通过AX+BY+CZ+D的符号来判断裁切范围的
利用多个ClipPlane可以对节点进行多边形切割
代码如下:
#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();
root->addChild(subgraph.get());
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);
node->addDrawable(new osg::ShapeDrawable(box));
//指定裁剪多边形顶点,只能裁剪凸多边形
//注意要逆时针指定,方向反了就都被裁剪掉了
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;
}