Salome HOME
Projection 2D failure due to incorrect detection of distorted result faces
[modules/smesh.git] / src / StdMeshers / StdMeshers_Projection_2D.cxx
index 38832904d84d4903ecce6379f165d798cf2812f2..7b3d1e1e1f157ff9157f722b9978e02af6f1dcdd 100644 (file)
@@ -51,6 +51,7 @@
 #include <BRep_Tool.hxx>
 #include <Bnd_B2d.hxx>
 #include <GeomAPI_ProjectPointOnSurf.hxx>
+#include <GeomLib_IsPlanarSurface.hxx>
 #include <TopExp.hxx>
 #include <TopExp_Explorer.hxx>
 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
@@ -196,7 +197,7 @@ namespace {
    */
   //================================================================================
 
-  bool isOldNode( const SMDS_MeshNode* node/*, const bool is1DComputed*/ )
+  bool isOldNode( const SMDS_MeshNode* node )
   {
     // old nodes are shared by edges and new ones are shared
     // only by faces created by mapper
@@ -404,23 +405,30 @@ namespace {
   //================================================================================
   /*!
    * \brief Compose TSideVector for both FACEs keeping matching order of EDGEs
+   *        and fill src2tgtNodes map
    */
   //================================================================================
 
-  bool getWires(const TopoDS_Face&                 tgtFace,
-                const TopoDS_Face&                 srcFace,
-                SMESH_Mesh *                       tgtMesh,
-                SMESH_Mesh *                       srcMesh,
-                const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
-                TSideVector&                       srcWires,
-                TSideVector&                       tgtWires,
-                const bool                         is1DComputed)
+  TError getWires(const TopoDS_Face&                 tgtFace,
+                  const TopoDS_Face&                 srcFace,
+                  SMESH_Mesh *                       tgtMesh,
+                  SMESH_Mesh *                       srcMesh,
+                  const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
+                  TSideVector&                       srcWires,
+                  TSideVector&                       tgtWires,
+                  TAssocTool::TNodeNodeMap&          src2tgtNodes,
+                  bool&                              is1DComputed)
   {
+    SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
+    SMESHDS_Mesh* srcMeshDS = srcMesh->GetMeshDS();
+
+    src2tgtNodes.clear();
+
     // get ordered src EDGEs
     TError err;
     srcWires = StdMeshers_FaceSide::GetFaceWires( srcFace, *srcMesh,/*skipMediumNodes=*/0, err);
     if ( err && !err->IsOK() )
-      return false;
+      return err;
 
     // make corresponding sequence of tgt EDGEs
     tgtWires.resize( srcWires.size() );
@@ -431,13 +439,17 @@ namespace {
       TopTools_IndexedMapOfShape edgeMap; // to detect seam edges
       for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
       {
-        TopoDS_Edge E = TopoDS::Edge( shape2ShapeMap( srcWire->Edge( iE ), /*isSrc=*/true));
+        TopoDS_Edge     srcE = srcWire->Edge( iE );
+        TopoDS_Edge     tgtE = TopoDS::Edge( shape2ShapeMap( srcE, /*isSrc=*/true));
+        TopoDS_Shape srcEbis = shape2ShapeMap( tgtE, /*isSrc=*/false );
+        if ( srcE.Orientation() != srcEbis.Orientation() )
+          tgtE.Reverse();
         // reverse a seam edge encountered for the second time
-        const int index = edgeMap.Add( E );
+        const int index = edgeMap.Add( tgtE );
         if ( index < edgeMap.Extent() ) // E is a seam
         {
           // check which of edges to reverse, E or one already being in tgtEdges
-          if ( are2dConnected( tgtEdges.back(), E, tgtFace ))
+          if ( are2dConnected( tgtEdges.back(), tgtE, tgtFace ))
           {
             list< TopoDS_Edge >::iterator eIt = tgtEdges.begin();
             std::advance( eIt, index-1 );
@@ -445,30 +457,73 @@ namespace {
           }
           else
           {
-            E.Reverse();
+            tgtE.Reverse();
           }
         }
         if ( srcWire->NbEdges() == 1 && tgtMesh == srcMesh ) // circle
         {
           // try to verify ori by propagation
-          pair<int,TopoDS_Edge> nE = StdMeshers_ProjectionUtils::GetPropagationEdge
-            ( srcMesh, E, srcWire->Edge( iE ));
+          pair<int,TopoDS_Edge> nE =
+            StdMeshers_ProjectionUtils::GetPropagationEdge( srcMesh, tgtE, srcE );
           if ( !nE.second.IsNull() )
-            E = nE.second;
+            tgtE = nE.second;
         }
-        tgtEdges.push_back( E );
-      }
+        tgtEdges.push_back( tgtE );
+
+
+        // Fill map of src to tgt nodes with nodes on edges
+
+        if ( srcMesh->GetSubMesh( srcE )->IsEmpty() ||
+             tgtMesh->GetSubMesh( tgtE )->IsEmpty() )
+        {
+          // add nodes on VERTEXes for a case of not meshes EDGEs
+          const TopoDS_Shape&  srcV = SMESH_MesherHelper::IthVertex( 0, srcE );
+          const TopoDS_Shape&  tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
+          const SMDS_MeshNode* srcN = SMESH_Algo::VertexNode( TopoDS::Vertex( srcV ), srcMeshDS );
+          const SMDS_MeshNode* tgtN = SMESH_Algo::VertexNode( TopoDS::Vertex( tgtV ), tgtMeshDS );
+          if ( srcN && tgtN )
+            src2tgtNodes.insert( make_pair( srcN, tgtN ));
+        }
+        else
+        {
+          const bool skipMediumNodes = true;
+          map< double, const SMDS_MeshNode* > srcNodes, tgtNodes;
+          if ( !SMESH_Algo::GetSortedNodesOnEdge( srcMeshDS, srcE, skipMediumNodes, srcNodes) ||
+               !SMESH_Algo::GetSortedNodesOnEdge( tgtMeshDS, tgtE, skipMediumNodes, tgtNodes ))
+            return SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH,
+                                            "Invalid node parameters on edges");
+
+          if (( srcNodes.size() != tgtNodes.size() ) && tgtNodes.size() > 0 )
+            return SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH,
+                                            "Different number of nodes on edges");
+          if ( !tgtNodes.empty() )
+          {
+            map< double, const SMDS_MeshNode* >::iterator u_tn = tgtNodes.begin();
+            if ( srcE.Orientation() == tgtE.Orientation() )
+            {
+              map< double, const SMDS_MeshNode* >::iterator u_sn = srcNodes.begin();
+              for ( ; u_tn != tgtNodes.end(); ++u_tn, ++u_sn)
+                src2tgtNodes.insert( make_pair( u_sn->second, u_tn->second ));
+            }
+            else
+            {
+              map< double, const SMDS_MeshNode* >::reverse_iterator u_sn = srcNodes.rbegin();
+              for ( ; u_tn != tgtNodes.end(); ++u_tn, ++u_sn)
+                src2tgtNodes.insert( make_pair( u_sn->second, u_tn->second ));
+            }
+            is1DComputed = true;
+          }
+        }
+      } // loop on EDGEs of a WIRE
+
       tgtWires[ iW ].reset( new StdMeshers_FaceSide( tgtFace, tgtEdges, tgtMesh,
                                                      /*theIsForward = */ true,
                                                      /*theIgnoreMediumNodes = */false));
-      if ( is1DComputed &&
-           srcWires[iW]->GetUVPtStruct().size() !=
-           tgtWires[iW]->GetUVPtStruct().size())
-        return false;
-    }
-    return true;
+    } // loop on WIREs
+
+    return TError();
   }
-                             
+
   //================================================================================
   /*!
    * \brief Preform projection in case if tgtFace.IsPartner( srcFace ) and in case
@@ -481,7 +536,8 @@ namespace {
                       const TSideVector&                 tgtWires,
                       const TSideVector&                 srcWires,
                       const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
-                      TAssocTool::TNodeNodeMap&          src2tgtNodes)
+                      TAssocTool::TNodeNodeMap&          src2tgtNodes,
+                      const bool                         is1DComputed)
   {
     SMESH_Mesh *    tgtMesh = tgtWires[0]->GetMesh();
     SMESH_Mesh *    srcMesh = srcWires[0]->GetMesh();
@@ -498,6 +554,11 @@ namespace {
       gp_Trsf srcTrsf = srcFace.Location();
       gp_Trsf tgtTrsf = tgtFace.Location();
       trsf.Set( srcTrsf.Inverted() * tgtTrsf );
+      // check
+      gp_Pnt srcP = BRep_Tool::Pnt( srcWires[0]->FirstVertex() );
+      gp_Pnt tgtP = BRep_Tool::Pnt( tgtWires[0]->FirstVertex() );
+      if ( tgtP.Distance( trsf.Transform( srcP )) > tol )
+        trsf.Set( tgtTrsf.Inverted() * srcTrsf );
     }
     else
     {
@@ -507,6 +568,7 @@ namespace {
       vector< gp_XYZ > srcPnts, tgtPnts;
       srcPnts.reserve( totNbSeg );
       tgtPnts.reserve( totNbSeg );
+      gp_XYZ srcBC( 0,0,0 ), tgtBC( 0,0,0 );
       for ( size_t iW = 0; iW < srcWires.size(); ++iW )
       {
         const double minSegLen = srcWires[iW]->Length() / totNbSeg;
@@ -523,6 +585,8 @@ namespace {
             tgtPnts.push_back( tgtWires[iW]->Value3d( tgtU ).XYZ() );
             srcU += srcDu;
             tgtU += tgtDu;
+            srcBC += srcPnts.back();
+            tgtBC += tgtPnts.back();
           }
         }
       }
@@ -535,6 +599,8 @@ namespace {
       const int nbTestPnt = 20;
       const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
       // check boundary
+      gp_Pnt trsfTgt = trsf.Transform( srcBC / srcPnts.size() );
+      trsfIsOK = ( trsfTgt.SquareDistance( tgtBC / tgtPnts.size() ) < tol*tol );
       for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
       {
         gp_Pnt trsfTgt = trsf.Transform( srcPnts[i] );
@@ -545,8 +611,8 @@ namespace {
       {
         BRepAdaptor_Surface srcSurf( srcFace );
         gp_Pnt srcP =
-          srcSurf.Value( 0.5 * ( srcSurf.FirstUParameter() + srcSurf.LastUParameter() ),
-                         0.5 * ( srcSurf.FirstVParameter() + srcSurf.LastVParameter() ));
+          srcSurf.Value( 0.321 * ( srcSurf.FirstUParameter() + srcSurf.LastUParameter() ),
+                         0.123 * ( srcSurf.FirstVParameter() + srcSurf.LastVParameter() ));
         gp_Pnt tgtTrsfP = trsf.Transform( srcP );
         TopLoc_Location loc;
         GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( tgtFace, loc, 0.1*tol );
@@ -561,61 +627,6 @@ namespace {
         return false;
     }
 
-    // Fill map of src to tgt nodes with nodes on edges
-
-    src2tgtNodes.clear();
-    TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
-
-    bool tgtEdgesMeshed = false;
-    for ( TopExp_Explorer srcExp( srcFace, TopAbs_EDGE); srcExp.More(); srcExp.Next() )
-    {
-      const TopoDS_Shape& srcEdge = srcExp.Current();
-      const TopoDS_Shape& tgtEdge = shape2ShapeMap( srcEdge, /*isSrc=*/true );
-      tgtEdgesMeshed != tgtMesh->GetSubMesh( tgtEdge )->IsEmpty();
-
-      if ( srcMesh->GetSubMesh( srcEdge )->IsEmpty() ||
-           tgtMesh->GetSubMesh( tgtEdge )->IsEmpty() )
-        continue;
-
-      map< double, const SMDS_MeshNode* > srcNodes, tgtNodes;
-      if (( ! SMESH_Algo::GetSortedNodesOnEdge( srcMeshDS,
-                                                TopoDS::Edge( srcEdge ),
-                                                /*ignoreMediumNodes = */true,
-                                                srcNodes ))
-           ||
-          ( ! SMESH_Algo::GetSortedNodesOnEdge( tgtMeshDS,
-                                                TopoDS::Edge( tgtEdge ),
-                                                /*ignoreMediumNodes = */true,
-                                                tgtNodes ))
-           ||
-          (( srcNodes.size() != tgtNodes.size() ) && tgtNodes.size() > 0 )
-          )
-        return false;
-
-      if ( !tgtNodes.empty() )
-      {
-        map< double, const SMDS_MeshNode* >::iterator u_tn = tgtNodes.begin();
-        map< double, const SMDS_MeshNode* >::iterator u_sn = srcNodes.begin();
-        for ( ; u_tn != tgtNodes.end(); ++u_tn, ++u_sn)
-          src2tgtNodes.insert( make_pair( u_sn->second, u_tn->second ));
-      }
-    }
-    // check nodes on VERTEXes for a case of not meshes EDGEs
-    for ( TopExp_Explorer srcExp( srcFace, TopAbs_VERTEX); srcExp.More(); srcExp.Next() )
-    {
-      const TopoDS_Shape&  srcV = srcExp.Current();
-      const TopoDS_Shape&  tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
-      const SMDS_MeshNode* srcN = SMESH_Algo::VertexNode( TopoDS::Vertex( srcV ), srcMeshDS );
-      const SMDS_MeshNode* tgtN = SMESH_Algo::VertexNode( TopoDS::Vertex( tgtV ), tgtMeshDS );
-      if ( !srcN )
-        continue;
-      if ( !tgtN || tgtV.ShapeType() != TopAbs_VERTEX )
-        return false;
-
-      src2tgtNodes.insert( make_pair( srcN, tgtN ));
-    }
-
-
     // Make new faces
 
     // prepare the helper to adding quadratic elements if necessary
@@ -623,13 +634,14 @@ namespace {
     helper.IsQuadraticSubMesh( tgtFace );
 
     SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
-    if ( !tgtEdgesMeshed && srcSubDS->NbElements() )
+    if ( !is1DComputed && srcSubDS->NbElements() )
       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
 
     SMESH_MesherHelper srcHelper( *srcMesh );
     srcHelper.SetSubShape( srcFace );
 
     const SMDS_MeshNode* nullNode = 0;
+    TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
 
     // indices of nodes to create properly oriented faces
     bool isReverse = ( !trsf.IsIdentity() );
@@ -699,7 +711,12 @@ namespace {
 
     if ( !tgtFace.IsPartner( srcFace ) )
     {
+      SMESH_MesherHelper edgeHelper( *tgtMesh );
+      edgeHelper.ToFixNodeParameters( true );
+      helper.ToFixNodeParameters( true );
+
       int nbOkPos = 0;
+      bool toCheck = true;
       const double tol2d = 1e-12;
       srcN_tgtN = src2tgtNodes.begin();
       for ( ; srcN_tgtN != src2tgtNodes.end(); ++srcN_tgtN )
@@ -709,22 +726,20 @@ namespace {
         {
         case SMDS_TOP_FACE:
         {
+          if ( nbOkPos > 10 ) break;
           gp_XY uv = helper.GetNodeUV( tgtFace, n ), uvBis = uv;
           if (( helper.CheckNodeUV( tgtFace, n, uv, tol )) &&
-              (( uv - uvBis ).SquareModulus() < tol2d )    &&
-              ( ++nbOkPos > 10 ))
-            return true;
+              (( uv - uvBis ).SquareModulus() < tol2d ))
+            ++nbOkPos;
           else
-            nbOkPos = 0;
+            nbOkPos = -((int) src2tgtNodes.size() );
           break;
         }
         case SMDS_TOP_EDGE:
         {
           const TopoDS_Edge & tgtE = TopoDS::Edge( tgtMeshDS->IndexToShape( n->getshapeId() ));
-          double u = helper.GetNodeU( tgtE, n ), uBis = u;
-          if (( !helper.CheckNodeU( tgtE, n, u, tol )) ||
-              (( u - uBis ) < tol2d ))
-            nbOkPos = 0;
+          edgeHelper.SetSubShape( tgtE );
+          edgeHelper.GetNodeU( tgtE, n, 0, &toCheck );
           break;
         }
         default:;
@@ -747,8 +762,8 @@ namespace {
                              const TSideVector&                 tgtWires,
                              const TSideVector&                 srcWires,
                              const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
-                             const bool                         is1DComputed,
-                             TAssocTool::TNodeNodeMap&          src2tgtNodes)
+                             TAssocTool::TNodeNodeMap&          src2tgtNodes,
+                             const bool                         is1DComputed)
   {
     SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
     SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
@@ -831,33 +846,6 @@ namespace {
 
     // 2) Projection
 
-    src2tgtNodes.clear();
-    TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
-
-    // fill src2tgtNodes in with nodes on EDGEs
-    for ( size_t iW = 0; iW < srcWires.size(); ++iW )
-      if ( is1DComputed )
-      {
-        const vector<UVPtStruct>& srcUVs = srcWires[iW]->GetUVPtStruct();
-        const vector<UVPtStruct>& tgtUVs = tgtWires[iW]->GetUVPtStruct();
-        for ( size_t i = 0; i < srcUVs.size(); ++i )
-          src2tgtNodes.insert( make_pair( srcUVs[i].node, tgtUVs[i].node ));
-      }
-      else
-      {
-        for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
-        {
-          TopoDS_Vertex srcV = srcWires[iW]->FirstVertex(iE);
-          TopoDS_Vertex tgtV = tgtWires[iW]->FirstVertex(iE);
-          const SMDS_MeshNode* srcNode = SMESH_Algo::VertexNode( srcV, srcMesh->GetMeshDS() );
-          const SMDS_MeshNode* tgtNode = SMESH_Algo::VertexNode( tgtV, tgtMesh->GetMeshDS() );
-          if ( tgtNode && srcNode )
-            src2tgtNodes.insert( make_pair( srcNode, tgtNode ));
-        }
-      }
-
-    // make elements
-
     SMESHDS_SubMesh* srcSubDS = srcMesh->GetMeshDS()->MeshElements( srcFace );
 
     SMESH_MesherHelper helper( *tgtMesh );
@@ -874,6 +862,7 @@ namespace {
     srcHelper.SetSubShape( srcFace );
 
     const SMDS_MeshNode* nullNode = 0;
+    TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
 
     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
     vector< const SMDS_MeshNode* > tgtNodes;
@@ -904,10 +893,9 @@ namespace {
           case SMDS_TOP_EDGE: {
             TopoDS_Shape srcEdge = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
             TopoDS_Edge  tgtEdge = TopoDS::Edge( shape2ShapeMap( srcEdge, /*isSrc=*/true ));
-            tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtEdge ));
-            double U = srcHelper.GetNodeU( TopoDS::Edge( srcEdge ), srcNode );
+            double U = Precision::Infinite();
             helper.CheckNodeU( tgtEdge, n, U, Precision::PConfusion());
-            n->SetPosition(SMDS_PositionPtr(new SMDS_EdgePosition( U )));
+            tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtEdge ), U );
             break;
           }
           case SMDS_TOP_VERTEX: {
@@ -938,74 +926,63 @@ namespace {
    */
   //================================================================================
 
-  void fixDistortedFaces( SMESH_MesherHelper& helper )
+  bool fixDistortedFaces( SMESH_MesherHelper& helper,
+                          TSideVector&        tgtWires )
   {
-    // Detect bad faces
-
-    bool haveBadFaces = false;
-
-    const TopoDS_Face&  F = TopoDS::Face( helper.GetSubShape() );
-    SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( F );
-    if ( !smDS || smDS->NbElements() == 0 ) return;
+    SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMesh( helper.GetSubShape() );
 
-    SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
-    double prevArea2D = 0;
-    vector< const SMDS_MeshNode* > nodes;
-    vector< gp_XY >                uv;
-    while ( faceIt->more() && !haveBadFaces )
-    {
-      const SMDS_MeshElement* face = faceIt->next();
-
-      // get nodes
-      nodes.resize( face->NbCornerNodes() );
-      SMDS_MeshElement::iterator n = face->begin_nodes();
-      for ( size_t i = 0; i < nodes.size(); ++n, ++i )
-        nodes[ i ] = *n;
-
-      // get UVs
-      const SMDS_MeshNode* inFaceNode = 0;
-      if ( helper.HasSeam() )
-        for ( size_t i = 0; ( i < nodes.size() && !inFaceNode ); ++i )
-          if ( !helper.IsSeamShape( nodes[ i ]->getshapeId() ))
-            inFaceNode = nodes[ i ];
-
-      uv.resize( nodes.size() );
-      for ( size_t i = 0; i < nodes.size(); ++i )
-        uv[ i ] = helper.GetNodeUV( F, nodes[ i ], inFaceNode );
-
-      // compare orientation of triangles
-      for ( int iT = 0, nbT = nodes.size()-2; iT < nbT; ++iT )
-      {
-        gp_XY v1 = uv[ iT+1 ] - uv[ 0 ];
-        gp_XY v2 = uv[ iT+2 ] - uv[ 0 ];
-        double area2D = v2 ^ v1;
-        if (( haveBadFaces = ( area2D * prevArea2D < 0 )))
-          break;
-        prevArea2D = area2D;
-      }
-    }
-
-    // Fix faces
-
-    if ( haveBadFaces )
+    if ( helper.IsDistorted2D( faceSM, /*checkUV=*/false ))
     {
       SMESH_MeshEditor editor( helper.GetMesh() );
+      SMESHDS_SubMesh* smDS = faceSM->GetSubMeshDS();
+      const TopoDS_Face&  F = TopoDS::Face( faceSM->GetSubShape() );
 
       TIDSortedElemSet faces;
+      SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
       for ( faceIt = smDS->GetElements(); faceIt->more(); )
         faces.insert( faces.end(), faceIt->next() );
 
+      // choose smoothing algo
+      //SMESH_MeshEditor:: SmoothMethod algo = SMESH_MeshEditor::CENTROIDAL;
+      bool isConcaveBoundary = false;
+      for ( size_t iW = 0; iW < tgtWires.size() && !isConcaveBoundary; ++iW )
+      {
+        TopoDS_Edge prevEdge = tgtWires[iW]->Edge( tgtWires[iW]->NbEdges() - 1 );
+        for ( int iE = 0; iE < tgtWires[iW]->NbEdges() && !isConcaveBoundary; ++iE )
+        {
+          double angle = helper.GetAngle( prevEdge, tgtWires[iW]->Edge( iE ),
+                                          F,        tgtWires[iW]->FirstVertex( iE ));
+          isConcaveBoundary = ( angle < -5. * M_PI / 180. );
+
+          prevEdge = tgtWires[iW]->Edge( iE );
+        }
+      }
+      SMESH_MeshEditor:: SmoothMethod algo =
+        isConcaveBoundary ? SMESH_MeshEditor::CENTROIDAL : SMESH_MeshEditor::LAPLACIAN;
+
+      // smooth in 2D or 3D?
+      TopLoc_Location loc;
+      Handle(Geom_Surface) surface = BRep_Tool::Surface( F, loc );
+      bool isPlanar = GeomLib_IsPlanarSurface( surface ).IsPlanar();
+
+      // smoothing
       set<const SMDS_MeshNode*> fixedNodes;
-      editor.Smooth( faces, fixedNodes, SMESH_MeshEditor::CENTROIDAL, 5 );
+      editor.Smooth( faces, fixedNodes, algo, /*nbIterations=*/ 10,
+                     /*theTgtAspectRatio=*/1.0, /*the2D=*/!isPlanar);
+
+      helper.ToFixNodeParameters( true );
+
+      return !helper.IsDistorted2D( faceSM, /*checkUV=*/true );
     }
+    return true;
   }
-  
+
 } // namespace
 
 
 //=======================================================================
 //function : Compute
-//purpose  : 
+//purpose  :
 //=======================================================================
 
 bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
@@ -1072,42 +1049,36 @@ bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape&
   // Projection
   // ===========
 
-  // find out if EDGEs are meshed or not
-  bool is1DComputed = false;
-  SMESH_subMeshIteratorPtr smIt = tgtSubMesh->getDependsOnIterator(/*includeSelf=*/false,
-                                                                   /*complexShapeFirst=*/true);
-  while ( smIt->more() && !is1DComputed )
-  {
-    SMESH_subMesh* sm = smIt->next();
-    if ( sm->GetSubShape().ShapeType() == TopAbs_EDGE )
-      is1DComputed = sm->IsMeshComputed();
-  }
-
   // get ordered src and tgt EDGEs
   TSideVector srcWires, tgtWires;
-  if ( !getWires( tgtFace, srcFace, tgtMesh, srcMesh,
-                  shape2ShapeMap, srcWires, tgtWires, is1DComputed ))
-    return false;
+  bool is1DComputed = false; // if any tgt EDGE is meshed
+  TError err = getWires( tgtFace, srcFace, tgtMesh, srcMesh,
+                         shape2ShapeMap, srcWires, tgtWires, _src2tgtNodes, is1DComputed );
+  if ( err && !err->IsOK() )
+    return error( err );
 
-  bool done = false;
+  bool projDone = false;
 
if ( !done )
 if ( !projDone )
   {
     // try to project from the same face with different location
-    done = projectPartner( tgtFace, srcFace, tgtWires, srcWires,
-                           shape2ShapeMap, _src2tgtNodes );
+    projDone = projectPartner( tgtFace, srcFace, tgtWires, srcWires,
+                               shape2ShapeMap, _src2tgtNodes, is1DComputed );
   }
-  if ( !done )
+  if ( !projDone )
   {
     // projection in case if the faces are similar in 2D space
-    done = projectBy2DSimilarity( tgtFace, srcFace, tgtWires, srcWires,
-                                  shape2ShapeMap, is1DComputed, _src2tgtNodes);
+    projDone = projectBy2DSimilarity( tgtFace, srcFace, tgtWires, srcWires,
+                                      shape2ShapeMap, _src2tgtNodes, is1DComputed);
   }
 
   SMESH_MesherHelper helper( theMesh );
   helper.SetSubShape( tgtFace );
 
-  if ( !done )
+  // it will remove mesh built on edges and vertices in failure case
+  MeshCleaner cleaner( tgtSubMesh );
+
+  if ( !projDone )
   {
     _src2tgtNodes.clear();
     // --------------------
@@ -1207,13 +1178,9 @@ bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape&
     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
       return error("Can't make mesh by source mesh pattern");
 
-    // it will remove mesh built by pattern mapper on edges and vertices
-    // in failure case
-    MeshCleaner cleaner( tgtSubMesh );
-
     // -------------------------------------------------------------------------
     // mapper doesn't take care of nodes already existing on edges and vertices,
-    // so we must merge nodes created by it with existing ones 
+    // so we must merge nodes created by it with existing ones
     // -------------------------------------------------------------------------
 
     SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
@@ -1221,7 +1188,8 @@ bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape&
     // Make groups of nodes to merge
 
     // loop on EDGE and VERTEX sub-meshes of a target FACE
-    smIt = tgtSubMesh->getDependsOnIterator(/*includeSelf=*/false,/*complexShapeFirst=*/false);
+    SMESH_subMeshIteratorPtr smIt = tgtSubMesh->getDependsOnIterator(/*includeSelf=*/false,
+                                                                     /*complexShapeFirst=*/false);
     while ( smIt->more() )
     {
       SMESH_subMesh*     sm = smIt->next();
@@ -1229,7 +1197,7 @@ bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape&
       if ( !smDS || smDS->NbNodes() == 0 )
         continue;
       //if ( !is1DComputed && sm->GetSubShape().ShapeType() == TopAbs_EDGE )
-      //break;
+      //  break;
 
       if ( helper.IsDegenShape( sm->GetId() ) ) // to merge all nodes on degenerated
       {
@@ -1369,14 +1337,6 @@ bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape&
     if ( nbFaceBeforeMerge != nbFaceAtferMerge && !helper.HasDegeneratedEdges() )
       return error(COMPERR_BAD_INPUT_MESH, "Probably invalid node parameters on geom faces");
 
-
-    // ----------------------------------------------------------------
-    // The mapper can create distorted faces by placing nodes out of the FACE
-    // boundary -- fix bad faces by smoothing
-    // ----------------------------------------------------------------
-
-    fixDistortedFaces( helper );
-
     // ----------------------------------------------------------------
     // The mapper can't create quadratic elements, so convert if needed
     // ----------------------------------------------------------------
@@ -1395,11 +1355,18 @@ bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape&
       editor.ConvertToQuadratic(/*theForce3d=*/false, tgtFaces, false);
     }
 
-    cleaner.Release(); // not to remove mesh
-
   } // end of projection using Pattern mapping
 
 
+  if ( !projDone || is1DComputed )
+    // ----------------------------------------------------------------
+    // The mapper can create distorted faces by placing nodes out of the FACE
+    // boundary, also bad face can be created if EDGEs already discretized
+    // --> fix bad faces by smoothing
+    // ----------------------------------------------------------------
+    if ( !fixDistortedFaces( helper, tgtWires ))
+      return error("Invalid mesh generated");
+
   // ---------------------------
   // Check elements orientation
   // ---------------------------
@@ -1445,6 +1412,8 @@ bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape&
     }
   }
 
+  cleaner.Release(); // not to remove mesh
+
   return true;
 }