|

楼主 |
发表于 2025-3-18 14:18:19
|
显示全部楼层
代码实现 1:使用CGAL库
如果你已经安装 CGAL,可以使用如下代码生成Mesh。
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Surface_mesh.h>
#include <cmath>
#include <iostream>
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef K::Point_3 Point;
typedef CGAL::Surface_mesh<Point> Mesh;
// 生成圆柱Mesh
void generate_cylinder_mesh(Mesh &mesh, double radius, double height, int n_segments, int n_height) {
double angle_step = 2 * M_PI / n_segments;
double height_step = height / n_height;
// 底面中心和顶面中心
Mesh::Vertex_index bottom_center = mesh.add_vertex(Point(0, 0, 0));
Mesh::Vertex_index top_center = mesh.add_vertex(Point(0, 0, height));
// 生成圆周顶点
std::vector<Mesh::Vertex_index> bottom_circle, top_circle;
for (int i = 0; i < n_segments; ++i) {
double theta = i * angle_step;
double x = radius * cos(theta);
double y = radius * sin(theta);
// 底面和顶面圆周上的点
bottom_circle.push_back(mesh.add_vertex(Point(x, y, 0)));
top_circle.push_back(mesh.add_vertex(Point(x, y, height)));
}
// 连接底面
for (int i = 0; i < n_segments; ++i) {
int next_i = (i + 1) % n_segments;
mesh.add_face(bottom_center, bottom_circle[next_i], bottom_circle);
}
// 连接顶面
for (int i = 0; i < n_segments; ++i) {
int next_i = (i + 1) % n_segments;
mesh.add_face(top_center, top_circle, top_circle[next_i]);
}
// 连接侧面(生成四边形或两个三角形)
for (int i = 0; i < n_segments; ++i) {
int next_i = (i + 1) % n_segments;
// 侧面分为上下两个三角形
mesh.add_face(bottom_circle, bottom_circle[next_i], top_circle[next_i]);
mesh.add_face(bottom_circle, top_circle[next_i], top_circle);
}
std::cout << "圆柱Mesh生成完成!顶点数量: " << mesh.num_vertices() << ",面片数量: " << mesh.num_faces() << std::endl;
}
int main() {
Mesh mesh;
double radius = 1.0;
double height = 3.0;
int n_segments = 32; // 圆周分割数
int n_height = 1; // 高度分割层数
generate_cylinder_mesh(mesh, radius, height, n_segments, n_height);
// 打印顶点和面片信息
for (auto v : mesh.vertices()) {
std::cout << "Vertex: " << mesh.point(v) << std::endl;
}
for (auto f : mesh.faces()) {
std::cout << "Face: ";
for (auto h : CGAL::halfedges_around_face(mesh.halfedge(f), mesh)) {
std::cout << mesh.point(target(h, mesh)) << " ";
}
std::cout << std::endl;
}
return 0;
}
|
|