/**************************************************************************** * VCGLib o o * * Visual and Computer Graphics Library o o * * _ O _ * * Copyright(C) 2004-2016 \/)\/ * * Visual Computing Lab /\/| * * ISTI - Italian National Research Council | * * \ * * All rights reserved. * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * * for more details. * * * ****************************************************************************/ #ifndef __VCGLIB_POLY_MESH_ALGORITHM #define __VCGLIB_POLY_MESH_ALGORITHM #include #include #include #include #include #include //define a temporary triangle mesh type class TempFace; class TempVertex; struct TempUsedTypes: public vcg::UsedTypes::AsVertexType, vcg::Use::AsFaceType>{}; class TempVertex:public vcg::Vertex {}; class TempFace:public vcg::Face {}; class TempMesh: public vcg::tri::TriMesh< std::vector,std::vector > {}; namespace vcg{ /*! \ingroup PolyMeshType \headerfile color.h vcg/complex/algorithms/polygonal_algorithms.h \brief processing and optimization of generic polygonal meshes. This class is used to performs varisous kind of geometric optimization on generic polygonal mesh such as flattengin or imptove the shape of polygons. */ template class PolygonalAlgorithm { typedef typename PolyMeshType::FaceType FaceType; typedef typename PolyMeshType::VertexType VertexType; typedef typename PolyMeshType::CoordType CoordType; typedef typename PolyMeshType::ScalarType ScalarType; typedef typename vcg::face::Pos PosType; public: static bool CollapseEdges(PolyMeshType &poly_m, const std::vector &CollapsePos, const std::vector &InterpPos) { //this set how to remap the vertices after deletion std::map VertexRemap; vcg::tri::UpdateFlags::VertexClearS(poly_m); bool collapsed=false; //go over all faces and check the ones needed to be deleted for (size_t i=0;iVN(); VertexType *v0=currF->V(IndexE); VertexType *v1=currF->V((IndexE+1)%NumV); //safety check assert(v0!=v1); if (v0->IsS())continue; if (v1->IsS())continue; //put on the same position v0->P()=InterpPos[i]; v1->P()=InterpPos[i]; //select the the two vertices v0->SetS(); v1->SetS(); //set the remap VertexRemap[v1]=v0; collapsed=true; } //then remap vertices for (size_t i=0;i FaceV; for (int j=0;j::RemoveUnreferencedVertex(poly_m); //and compact them vcg::tri::Allocator::CompactEveryVector(poly_m); return collapsed; } private: static bool CollapseBorderSmallEdgesStep(PolyMeshType &poly_m, const ScalarType edge_limit, ScalarType angleDeg=100) { //update topology vcg::tri::UpdateTopology::FaceFace(poly_m); //update border vertices vcg::tri::UpdateFlags::VertexBorderFromFaceAdj(poly_m); vcg::tri::UpdateSelection::VertexCornerBorder(poly_m,math::ToRad(150.0)); std::vector CollapsePos; std::vector InterpPos; //go over all faces and check the ones needed to be deleted for (size_t i=0;iIsB(); bool IsBV1=v1->IsB(); bool IsS0=v0->IsS(); bool IsS1=v1->IsS(); if ((IsS0)&&(IsS1))continue; //in these cases is not possible to collapse if ((!IsBV0)&&(!IsBV1))continue; bool IsBorderE=(poly_m.face[i].FFp(j)==&poly_m.face[i]); if ((!IsBorderE)&&(IsBV0)&&(IsBV1))continue; assert((IsBV0)||(IsBV1)); CoordType pos0=v0->P(); CoordType pos1=v1->P(); ScalarType currL=(pos0-pos1).Norm(); if (currL>edge_limit)continue; //then collapse the point CoordType CurrInterpPos; if ((IsBV0)&&(!IsBV1))CurrInterpPos=pos0; if ((!IsBV0)&&(IsBV1))CurrInterpPos=pos1; if ((IsBV0)&&(IsBV1)) { if ((!IsS0)&&(!IsS1)) CurrInterpPos=(pos0+pos1)/2.0; else { if ((!IsS0)&&(IsS1)) CurrInterpPos=pos1; else { assert((IsS0)&&(!IsS1)); CurrInterpPos=pos0; } } } CollapsePos.push_back(PosType(&poly_m.face[i],j)); InterpPos.push_back(CurrInterpPos); } } return CollapseEdges(poly_m,CollapsePos,InterpPos); } static void LaplacianPos(PolyMeshType &poly_m,std::vector &AvVert) { //cumulate step AvVert.clear(); AvVert.resize(poly_m.vert.size(),CoordType(0,0,0)); std::vector AvSum(poly_m.vert.size(),0); for (size_t i=0;iP(); //cumulate over other positions ScalarType W=vcg::PolyArea(poly_m.face[i]); //assert(W!=0); for (size_t k=0;k<(size_t)poly_m.face[i].VN();k++) { if (k==j)continue; int IndexV=vcg::tri::Index(poly_m,poly_m.face[i].V(k)); AvVert[IndexV]+=currP*W; AvSum[IndexV]+=W; } } //average step for (size_t i=0;i PlF; PlF=PolyFittingPlane(F); if ((PlF.Direction()*F.N())<0) F.N()=-PlF.Direction(); else F.N()=PlF.Direction(); } public: static CoordType GetFaceGetBary(FaceType &F) { CoordType bary=PolyBarycenter(F); return bary; } /*! \brief update the face normal by averaging among vertex's * normals computed between adjacent edges */ static void UpdateFaceNormals(PolyMeshType &poly_m) { for (size_t i=0;i &TemplatePos) { vcg::GetPolyTemplatePos(f,TemplatePos,true); CoordType NormT=Normal(TemplatePos); //get the normal of vertices CoordType AVN(0,0,0); CoordType Origin(0,0,0); for (int j=0;jN(); for (size_t j=0;j Rot=vcg::RotationMatrix(NormT,AVN); //apply transformation for (size_t j=0;j avgPos(poly_m.vert.size(),CoordType(0,0,0)); std::vector weightSum(poly_m.vert.size(),0); //then compute the templated positions for (size_t i=0;i TemplatePos; GetRotatedTemplatePos(poly_m.face[i],TemplatePos); //then cumulate the position per vertex ScalarType val=vcg::PolyArea(poly_m.face[i]); if (val<(AvgArea*0.00001)) val=(AvgArea*0.00001); ScalarType W=1.0/val;//poly_m.face[i].Q(); //ScalarType W=1; for (size_t j=0;j AvVert; LaplacianPos(poly_m,AvVert); //then update the position for (size_t i=0;i1)alpha=1; // if (isnan(alpha))alpha=1; CoordType newP=avgPos[i]/weightSum[i]; newP=newP*(1-alpha)+AvVert[i]*alpha; if ((fixB)&&(poly_m.vert[i].IsB()))continue; if ((FixS)&&(poly_m.vert[i].IsS()))continue; poly_m.vert[i].P()=poly_m.vert[i].P()*Damp+ newP*(1-Damp); } } } /*! \brief This function smooth the borders of the polygonal mesh and reproject back to the triangolar one * except the vertices that are considered as corner wrt the angleDeg threshold */ template static void LaplacianReprojectBorder(PolyMeshType &poly_m, TriMeshType &tri_mesh, int nstep=100, ScalarType Damp=0.5, ScalarType angleDeg=100) { //first select corners vcg::tri::UpdateFlags::VertexClearS(poly_m); //update topology vcg::tri::UpdateTopology::FaceFace(poly_m); //update border vertices vcg::tri::UpdateFlags::VertexBorderFromFaceAdj(poly_m); //select corner vertices on the border ScalarType angleRad=angleDeg * M_PI / 180; vcg::tri::UpdateSelection::VertexCornerBorder(poly_m,angleRad); for (int s=0;s AvVert; LaplacianPos(poly_m,AvVert); for (size_t i=0;i::max(); CoordType closPos; for (size_t j=0;j Seg(P0,P1); ScalarType testD; CoordType closTest; vcg::SegmentPointDistance(Seg,testPos,closTest,testD); if (testD>minD)continue; minD=testD; closPos=closTest; } poly_m.vert[i].P()=closPos; } } } /*! \brief This function smooth the borders of the polygonal mesh and reproject back to its border */ static void LaplacianReprojectBorder(PolyMeshType &poly_m, int nstep=100, ScalarType Damp=0.5) { //transform into triangular TempMesh GuideSurf; vcg::tri::PolygonSupport::ImportFromPolyMesh(GuideSurf,poly_m); vcg::tri::UpdateBounding::Box(GuideSurf); vcg::tri::UpdateNormal::PerVertexNormalizedPerFace(GuideSurf); vcg::tri::UpdateTopology::FaceFace(GuideSurf); vcg::tri::UpdateFlags::FaceBorderFromFF(GuideSurf); LaplacianReprojectBorder(poly_m,GuideSurf,nstep,Damp); } /*! \brief This function performs the reprojection of the polygonal mesh onto a triangular one passed as input parameter */ template static void LaplacianReproject(PolyMeshType &poly_m, TriMeshType &tri_mesh, bool fixIrr=false, int nstep=100, ScalarType Damp=0.5) { typedef typename TriMeshType::FaceType FaceType; typedef vcg::GridStaticPtr TriMeshGrid; TriMeshGrid grid; //initialize the grid grid.Set(tri_mesh.face.begin(),tri_mesh.face.end()); ScalarType MaxD=tri_mesh.bbox.Diag(); if (fixIrr) poly_m.NumIrregular(true); for (int s=0;s AvVert; LaplacianPos(poly_m,AvVert); for (size_t i=0;i AvVert; LaplacianPos(poly_m,AvVert); for (size_t i=0;i static void SmoothReprojectPCA(PolyMeshType &poly_m, TriMeshType &tri_mesh, int relaxStep=100, bool fixIrr=false, ScalarType Damp=0.5) { vcg::tri::UpdateTopology::FaceFace(poly_m); //UpdateBorderVertexFromPFFAdj(poly_m); vcg::tri::UpdateFlags::VertexBorderFromFaceAdj(poly_m); typedef typename TriMeshType::FaceType FaceType; typedef vcg::GridStaticPtr TriMeshGrid; TriMeshGrid grid; //initialize the grid grid.Set(tri_mesh.face.begin(),tri_mesh.face.end()); ScalarType MaxD=tri_mesh.bbox.Diag(); // //update quality as area // for (size_t i=0;i::ImportFromPolyMesh(GuideSurf,poly_m); vcg::tri::UpdateBounding::Box(GuideSurf); vcg::tri::UpdateNormal::PerVertexNormalizedPerFace(GuideSurf); vcg::tri::UpdateTopology::FaceFace(GuideSurf); vcg::tri::UpdateFlags::FaceBorderFromFF(GuideSurf); //optimize it vcg::PolygonalAlgorithm::SmoothReprojectPCA(poly_m,GuideSurf,relaxStep,fixIrr,Damp); } /*! \brief This function return average edge size */ static ScalarType AverageEdge(const PolyMeshType &poly_m) { ScalarType AvL=0; size_t numE=0; for (size_t i=0;iP(); CoordType pos1=poly_m.face[i].cV((j+1)%NumV)->P(); AvL+=(pos0-pos1).Norm(); numE++; } } AvL/=numE; return AvL; } /*! \brief This function remove valence 2 faces from the mesh */ static void RemoveValence2Faces(PolyMeshType &poly_m) { for (size_t i=0;i=3)continue; vcg::tri::Allocator::DeleteFace(poly_m,poly_m.face[i]); } //then remove unreferenced vertices vcg::tri::Clean::RemoveUnreferencedVertex(poly_m); vcg::tri::Allocator::CompactEveryVector(poly_m); } /*! \brief This function remove valence 2 vertices on the border by considering the degree threshold * bacause there could be eventually some corner that should be preserved */ static void RemoveValence2BorderVertices(PolyMeshType &poly_m, ScalarType corner_degree=25) { //update topology vcg::tri::UpdateTopology::FaceFace(poly_m); //update border vertices //UpdateBorderVertexFromPFFAdj(poly_m); vcg::tri::UpdateFlags::VertexBorderFromFaceAdj(poly_m); vcg::tri::UpdateFlags::VertexClearS(poly_m); //select corners for (size_t i=0;iIsB())||(!v1->IsB())||(!v2->IsB()))continue; CoordType dir0=(v0->P()-v1->P()); CoordType dir1=(v2->P()-v1->P()); dir0.Normalize(); dir1.Normalize(); ScalarType testDot=(dir0*dir1); if (testDot>(-cos(corner_degree* (M_PI / 180.0)))) v1->SetS(); } } typename PolyMeshType::template PerVertexAttributeHandle valenceVertH = vcg::tri::Allocator:: template GetPerVertexAttribute (poly_m); //initialize to zero for (size_t i=0;i FaceV; for (size_t j=0;jIsD()); if ((!v->IsS()) && (v->IsB()) && (valenceVertH[v]==1)) continue; FaceV.push_back(v); } //then deallocate face if (FaceV.size()==NumV)continue; //otherwise deallocate and set new vertices poly_m.face[i].Dealloc(); poly_m.face[i].Alloc(FaceV.size()); for (size_t j=0;j::RemoveUnreferencedVertex(poly_m); vcg::tri::Allocator::CompactEveryVector(poly_m); vcg::tri::Allocator::DeletePerVertexAttribute(poly_m,valenceVertH); } /*! \brief This function collapse small edges which are on the boundary of the mesh * this is sometimes useful to remove small edges coming out from a quadrangulation which is not * aligned to boundaries */ static void CollapseBorderSmallEdges(PolyMeshType &poly_m,const ScalarType perc_average=0.3) { //compute the average edge ScalarType AvEdge=AverageEdge(poly_m); ScalarType minLimit=AvEdge*perc_average; while(CollapseBorderSmallEdgesStep(poly_m,minLimit)){}; RemoveValence2Faces(poly_m); RemoveValence2BorderVertices(poly_m); } /*! \brief This function use a local global approach to flatten polygonal faces * the approach is similar to "Shape-Up: Shaping Discrete Geometry with Projections" */ static ScalarType FlattenFaces(PolyMeshType &poly_m, size_t steps=100,bool OnlySFaces=false) { ScalarType MaxDispl=0; for (size_t s=0;s > VertPos(poly_m.vert.size()); for (size_t i=0;i FacePos; for (int j=0;jIsD()); FacePos.push_back(v->P()); } //then fit the plane vcg::Plane3 FitPl; vcg::FitPlaneToPointSet(FacePos,FitPl); //project each point onto fitting plane for (int j=0;jP()); VertPos[IndexV].push_back(ProjP); } } for (size_t i=0;iQ()+=AreaF/(ScalarType)poly_m.face[i].VN(); } } static void InterpolateQualityVertFormFaces(PolyMeshType &poly_m) { std::vector SumW(poly_m.vert.size(),0); for (size_t i=0;iQ()+=AreaF*(ScalarType)poly_m.face[i].Q(); size_t IndexV=vcg::tri::Index(poly_m,poly_m.face[i].V(j)); SumW[IndexV]+=AreaF; } } for (size_t i=0;i0) poly_m.vert[i].Q()/=SumW[i]; else poly_m.vert[i].Q()=0; } } static void ClosestPoint(const PolyMeshType &poly_m,const CoordType &pos, int &CloseF,CoordType &ClosePos) { ScalarType minD=std::numeric_limits::max(); CloseF=-1; for (size_t i=0;iminD)continue; minD=currD; CloseF=i; ClosePos=closeTest; } } static void Triangulate(PolyMeshType &poly_m,size_t IndexF) { CoordType bary=vcg::PolyBarycenter(poly_m.face[IndexF]); size_t sizeV=poly_m.face[IndexF].VN(); //add the new vertex vcg::tri::Allocator::AddVertex(poly_m,bary); VertexType *newV=&poly_m.vert.back(); std::vector ToUpdateF; //then reupdate the faces for (size_t j=0;j<(sizeV-1);j++) { VertexType * v0=poly_m.face[IndexF].V0(j); VertexType * v1=poly_m.face[IndexF].V1(j); VertexType * v2=newV; vcg::tri::Allocator::AddFaces(poly_m,1); poly_m.face.back().Alloc(3); poly_m.face.back().V(0)=v0; poly_m.face.back().V(1)=v1; poly_m.face.back().V(2)=v2; ToUpdateF.push_back(poly_m.face.size()-1); } VertexType * v0=poly_m.face[IndexF].V0((sizeV-1)); VertexType * v1=poly_m.face[IndexF].V1((sizeV-1)); poly_m.face[IndexF].Dealloc(); poly_m.face[IndexF].Alloc(3); poly_m.face[IndexF].V(0)=v0; poly_m.face[IndexF].V(1)=v1; poly_m.face[IndexF].V(2)=newV; ToUpdateF.push_back(IndexF); } static void Triangulate(PolyMeshType &poly_m) { size_t size0=poly_m.face.size(); for (size_t i=0;i static void TriangulateToTriMesh(PolyMeshType &poly_m,TriMeshType &triangle_mesh) { triangle_mesh.Clear(); PolyMeshType PolySwap; vcg::tri::Append::Mesh(PolySwap,poly_m); Triangulate(PolySwap); //then copy onto the triangle mesh vcg::tri::Append::Mesh(triangle_mesh,PolySwap); } }; }//end namespace vcg #endif