原文出处: http://openmesh.org/Documentation/OpenMesh-Doc-Latest/tutorial.html
这个例子展现:
这个例子是第一个版本的平滑器。我们将会介绍迭代器(iterators)和循环机(circulators)。
这两个概念提供线性枚举的功能,比如网格中所有的顶点,围绕一个顶点循环,枚举所有的1-ring邻接元素。更详细的内容参考Mesh Iterators and Circulators。
首先我们定义Mesh类型。这一次我使用三角网格而不是多边形网格:
#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>
typedef OpenMesh::TriMesh_ArrayKernelT<> MyMesh;
读取将要平滑的文件:
if ( ! OpenMesh::IO::read_mesh(mesh, argv[2]) )
一个平滑迭代器由两步完成:
对每个顶点:计算1-ring的重心(barycenter)
对每个顶点:移动顶点到重心
我们可以轻松的实现顶点迭代。Mesh提供了迭代器的开始和结束分别是vertices_begin() 和 vertices_end()。
MyMesh::VertexIter v_it, v_end(mesh.vertices_end());
for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)
现在我们计算每个顶点的重心并存储起来:
std::vector<MyMesh::Point> cogs;
for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)
{
cog[0] = cog[1] = cog[2] = valence = 0.0;
for (vv_it=mesh.vv_iter( v_it ); vv_it; ++vv_it)
{
cog += mesh.point( vv_it );
++valence;
}
cogs.push_back(cog / valence);
}
计算重心完成之后,剩下的就是移动顶点到相应的重心。完整的代码如下:
#include <iostream>
#include <vector>
// -------------------- OpenMesh
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>
typedef OpenMesh::TriMesh_ArrayKernelT<> MyMesh;
int main(int argc, char **argv)
{
MyMesh mesh;
// check command line options
if (argc != 4)
{
std::cerr << "Usage: " << argv[0] << " #iterations infile outfile\n";
return 1;
}
// read mesh from stdin
if ( ! OpenMesh::IO::read_mesh(mesh, argv[2]) )
{
std::cerr << "Error: Cannot read mesh from " << argv[2] << std::endl;
return 1;
}
// this vector stores the computed centers of gravity
std::vector<MyMesh::Point> cogs;
std::vector<MyMesh::Point>::iterator cog_it;
cogs.reserve(mesh.n_vertices());
// smoothing mesh argv[1] times
MyMesh::VertexIter v_it, v_end(mesh.vertices_end());
MyMesh::VertexVertexIter vv_it;
MyMesh::Point cog;
MyMesh::Scalar valence;
unsigned int i, N(atoi(argv[1]));
for (i=0; i < N; ++i)
{
cogs.clear();
for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)
{
cog[0] = cog[1] = cog[2] = valence = 0.0;
for (vv_it=mesh.vv_iter( v_it ); vv_it; ++vv_it)
{
cog += mesh.point( vv_it );
++valence;
}
cogs.push_back(cog / valence);
}
for (v_it=mesh.vertices_begin(), cog_it=cogs.begin();
v_it!=v_end; ++v_it, ++cog_it)
if ( !mesh.is_boundary( v_it ) )
mesh.set_point( v_it, *cog_it );
}
// write mesh to stdout
if ( ! OpenMesh::IO::write_mesh(mesh, argv[3]) )
{
std::cerr << "Error: cannot write mesh to " << argv[3] << std::endl;
return 1;
}
return 0;
}