使用迭代器和環繞器
本例主要說明以下問題:
1.如何使用迭代器
2.如何使用環繞器
這個例子是第一版mesh光滑器。這裏,我們將介紹迭代器和環繞器,這兩個概念能提兩個線性枚舉功能:一是線性枚舉mesh上的所有節點;二是枚舉環繞某個節點的所有節點(例如,環繞與某個節點相鄰的所有一環節點)。更多的細節描述,可參考Mesh IteratorsandCirculators。
首先,我們要定義我們自己的mesh類型。這次,我們使用三角面替代上節提到的多邊形面。
#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>
typedef OpenMesh::TriMesh_ArrayKernelT<>MyMesh;
我們這次從文件中讀取一個mesh,使用OpenMesh::IO::read_mesh函數。
if ( ! OpenMesh::IO::read_mesh(mesh,argv[2]) )
構造用於光滑處理的迭代器需要兩個步驟:
1.對每個節點:計算其一環臨近節點的重心;
2.對每個節點:將其移動到剛剛計算出的重心位置。
通過節點迭代器,可以輕鬆實現。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)
爲了計算重心,我們要通過VertexVertexIter提供的迭代器環繞當前節點的一環臨近節點。
MyMesh::VertexVertexItervv_it;
for (vv_it=mesh.vv_iter( *v_it ); vv_it.is_valid(); ++vv_it)
現在,我們可以計算存儲在數組cogs中的所有節點的重心,代碼如下:
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.is_valid(); ++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::VertexVertexItervv_it;
MyMesh::Pointcog;
MyMesh::Scalarvalence;
unsignedint 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.is_valid(); ++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;
}