使用 OCC 创建 正方体和圆柱体,并且通过布尔运算,切除正方体内的圆柱体,保存 stl 几何模型。
#include <iostream>
#include <iomanip>
#include "BRepPrimAPI_MakeCylinder.hxx"
#include "BRepPrimAPI_MakeBox.hxx"
#include "BRepAlgoAPI_Cut.hxx"
#include "BRepGProp.hxx"
#include "STEPControl_Writer.hxx"
#include "GProp_GProps.hxx"
int main(int argc, char* argv[])
{
//创建 长 x 宽 x 高 100x100x50
gp_Pnt lowerLeftCornerOfBox(-50.0, -50.0, 0.0); // 位置点
BRepPrimAPI_MakeBox boxMaker(lowerLeftCornerOfBox, 100, 100, 50); // 长宽高
TopoDS_Shape box = boxMaker.Shape(); // 创建 box 形状
//创建圆柱 radius 25.0, height 50.0
BRepPrimAPI_MakeCylinder cylinderMaker(25.0, 50.0); // 创建圆柱
TopoDS_Shape cylinder = cylinderMaker.Shape(); // 创建 Cylinder 形状
// 剪切 box 里的圆柱部分
BRepAlgoAPI_Cut cutMaker(box, cylinder);
TopoDS_Shape boxWithHole = cutMaker.Shape(); // 创建 布尔运算之后的几何
//保存几何文件 STEP
STEPControl_Writer writer;
writer.Transfer(boxWithHole, STEPControl_AsIs);
writer.Write("boxWithHole.stp");
std::cout << "Created box with hole, file is written to boxWithHole.stp" << std::endl;
// 计算新几何的体积
GProp_GProps volumeProperties;
BRepGProp::VolumeProperties(boxWithHole, volumeProperties);
//计算体积
std::cout << std::setprecision(14) << "Volume of the model is: " << volumeProperties.Mass() << std::endl;
//计算质心
std::cout << "Center of mass is: " << volumeProperties.CentreOfMass().X() << " " << volumeProperties.CentreOfMass().Y() << " " << volumeProperties.CentreOfMass().Z() << std::endl;
//计算惯性矩阵
gp_Mat inertiaMatrix = volumeProperties.MatrixOfInertia();
std::cout << "Matrix of inertia: " << std::endl;
for (int i = 1; i <= 3; ++i) {
for (int j = 1; j <= 3; ++j) {
std::cout << inertiaMatrix(i, j) << "\t";
}
std::cout << std::endl;
}
return 0;
}