Salome HOME
23050: EDF 10631 SMESH: Nodes outside the plane after ConvertToQuadratic
[modules/smesh.git] / src / StdMeshers / StdMeshers_Projection_2D.cxx
1 // Copyright (C) 2007-2015  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SMESH SMESH : implementaion of SMESH idl descriptions
24 // File      : StdMeshers_Projection_2D.cxx
25 // Module    : SMESH
26 // Created   : Fri Oct 20 11:37:07 2006
27 // Author    : Edward AGAPOV (eap)
28 //
29 #include "StdMeshers_Projection_2D.hxx"
30
31 #include "StdMeshers_ProjectionSource2D.hxx"
32 #include "StdMeshers_ProjectionUtils.hxx"
33 #include "StdMeshers_FaceSide.hxx"
34
35 #include "SMDS_EdgePosition.hxx"
36 #include "SMDS_FacePosition.hxx"
37 #include "SMESHDS_Hypothesis.hxx"
38 #include "SMESHDS_SubMesh.hxx"
39 #include "SMESH_Block.hxx"
40 #include "SMESH_Comment.hxx"
41 #include "SMESH_Gen.hxx"
42 #include "SMESH_Mesh.hxx"
43 #include "SMESH_MesherHelper.hxx"
44 #include "SMESH_Pattern.hxx"
45 #include "SMESH_subMesh.hxx"
46 #include "SMESH_subMeshEventListener.hxx"
47
48 #include "utilities.h"
49
50 #include <BRepAdaptor_Surface.hxx>
51 #include <BRep_Tool.hxx>
52 #include <Bnd_B2d.hxx>
53 #include <GeomAPI_ProjectPointOnSurf.hxx>
54 #include <GeomLib_IsPlanarSurface.hxx>
55 #include <TopExp.hxx>
56 #include <TopExp_Explorer.hxx>
57 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
58 #include <TopTools_ListIteratorOfListOfShape.hxx>
59 #include <TopTools_MapOfShape.hxx>
60 #include <TopoDS.hxx>
61 #include <gp_Ax2.hxx>
62 #include <gp_Ax3.hxx>
63 #include <gp_GTrsf.hxx>
64
65
66 using namespace std;
67
68 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
69
70 namespace TAssocTool = StdMeshers_ProjectionUtils;
71 //typedef StdMeshers_ProjectionUtils TAssocTool;
72
73 //=======================================================================
74 //function : StdMeshers_Projection_2D
75 //purpose  : 
76 //=======================================================================
77
78 StdMeshers_Projection_2D::StdMeshers_Projection_2D(int hypId, int studyId, SMESH_Gen* gen)
79   :SMESH_2D_Algo(hypId, studyId, gen)
80 {
81   _name = "Projection_2D";
82   _compatibleHypothesis.push_back("ProjectionSource2D");
83   _sourceHypo = 0;
84 }
85
86 //================================================================================
87 /*!
88  * \brief Destructor
89  */
90 //================================================================================
91
92 StdMeshers_Projection_2D::~StdMeshers_Projection_2D()
93 {}
94
95 //=======================================================================
96 //function : CheckHypothesis
97 //purpose  : 
98 //=======================================================================
99
100 bool StdMeshers_Projection_2D::CheckHypothesis(SMESH_Mesh&                          theMesh,
101                                                const TopoDS_Shape&                  theShape,
102                                                SMESH_Hypothesis::Hypothesis_Status& theStatus)
103 {
104   list <const SMESHDS_Hypothesis * >::const_iterator itl;
105
106   const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(theMesh, theShape);
107   if ( hyps.size() == 0 )
108   {
109     theStatus = HYP_MISSING;
110     return false;  // can't work with no hypothesis
111   }
112
113   if ( hyps.size() > 1 )
114   {
115     theStatus = HYP_ALREADY_EXIST;
116     return false;
117   }
118
119   const SMESHDS_Hypothesis *theHyp = hyps.front();
120
121   string hypName = theHyp->GetName();
122
123   theStatus = HYP_OK;
124
125   if (hypName == "ProjectionSource2D")
126   {
127     _sourceHypo = static_cast<const StdMeshers_ProjectionSource2D *>(theHyp);
128
129     // Check hypo parameters
130
131     SMESH_Mesh* srcMesh = _sourceHypo->GetSourceMesh();
132     SMESH_Mesh* tgtMesh = & theMesh;
133     if ( !srcMesh )
134       srcMesh = tgtMesh;
135
136     // check vertices
137     if ( _sourceHypo->HasVertexAssociation() )
138     {
139       // source vertices
140       TopoDS_Shape edge = TAssocTool::GetEdgeByVertices
141         ( srcMesh, _sourceHypo->GetSourceVertex(1), _sourceHypo->GetSourceVertex(2) );
142       if ( edge.IsNull() ||
143            !SMESH_MesherHelper::IsSubShape( edge, srcMesh ) ||
144            !SMESH_MesherHelper::IsSubShape( edge, _sourceHypo->GetSourceFace() ))
145       {
146         theStatus = HYP_BAD_PARAMETER;
147         error("Invalid source vertices");
148         SCRUTE((edge.IsNull()));
149         SCRUTE((SMESH_MesherHelper::IsSubShape( edge, srcMesh )));
150         SCRUTE((SMESH_MesherHelper::IsSubShape( edge, _sourceHypo->GetSourceFace() )));
151       }
152       else
153       {
154         // target vertices
155         edge = TAssocTool::GetEdgeByVertices
156           ( tgtMesh, _sourceHypo->GetTargetVertex(1), _sourceHypo->GetTargetVertex(2) );
157         if ( edge.IsNull() || !SMESH_MesherHelper::IsSubShape( edge, tgtMesh ))
158         {
159           theStatus = HYP_BAD_PARAMETER;
160           error("Invalid target vertices");
161           SCRUTE((edge.IsNull()));
162           SCRUTE((SMESH_MesherHelper::IsSubShape( edge, tgtMesh )));
163         }
164         // PAL16203
165         else if ( !_sourceHypo->IsCompoundSource() &&
166                   !SMESH_MesherHelper::IsSubShape( edge, theShape ))
167         {
168           theStatus = HYP_BAD_PARAMETER;
169           error("Invalid target vertices");
170           SCRUTE((SMESH_MesherHelper::IsSubShape( edge, theShape )));
171         }
172       }
173     }
174     // check a source face
175     if ( !SMESH_MesherHelper::IsSubShape( _sourceHypo->GetSourceFace(), srcMesh ) ||
176          ( srcMesh == tgtMesh && theShape == _sourceHypo->GetSourceFace() ))
177     {
178       theStatus = HYP_BAD_PARAMETER;
179       error("Invalid source face");
180       SCRUTE((SMESH_MesherHelper::IsSubShape( _sourceHypo->GetSourceFace(), srcMesh )));
181       SCRUTE((srcMesh == tgtMesh));
182       SCRUTE(( theShape == _sourceHypo->GetSourceFace() ));
183     }
184   }
185   else
186   {
187     theStatus = HYP_INCOMPATIBLE;
188   }
189   return ( theStatus == HYP_OK );
190 }
191
192 namespace {
193
194   //================================================================================
195   /*!
196    * \brief define if a node is new or old
197    * \param node - node to check
198    * \retval bool - true if the node existed before Compute() is called
199    */
200   //================================================================================
201
202   bool isOldNode( const SMDS_MeshNode* node )
203   {
204     // old nodes are shared by edges and new ones are shared
205     // only by faces created by mapper
206     //if ( is1DComputed )
207     {
208       bool isOld = node->NbInverseElements(SMDSAbs_Edge) > 0;
209       return isOld;
210     }
211     // else
212     // {
213     //   SMDS_ElemIteratorPtr invFace = node->GetInverseElementIterator(SMDSAbs_Face);
214     //   bool isNew = invFace->more();
215     //   return !isNew;
216     // }
217   }
218
219   //================================================================================
220   /*!
221    * \brief Class to remove mesh built by pattern mapper on edges
222    * and vertices in the case of failure of projection algo.
223    * It does it's job at destruction
224    */
225   //================================================================================
226
227   class MeshCleaner {
228     SMESH_subMesh* sm;
229   public:
230     MeshCleaner( SMESH_subMesh* faceSubMesh ): sm(faceSubMesh) {}
231     ~MeshCleaner() { Clean(sm); }
232     void Release() { sm = 0; } // mesh will not be removed
233     static void Clean( SMESH_subMesh* sm, bool withSub=true )
234     {
235       if ( !sm || !sm->GetSubMeshDS() ) return;
236       // PAL16567, 18920. Remove face nodes as well
237 //       switch ( sm->GetSubShape().ShapeType() ) {
238 //       case TopAbs_VERTEX:
239 //       case TopAbs_EDGE: {
240         SMDS_NodeIteratorPtr nIt = sm->GetSubMeshDS()->GetNodes();
241         SMESHDS_Mesh* mesh = sm->GetFather()->GetMeshDS();
242         while ( nIt->more() ) {
243           const SMDS_MeshNode* node = nIt->next();
244           if ( !isOldNode( node ) )
245             mesh->RemoveNode( node );
246         }
247         // do not break but iterate over DependsOn()
248 //       }
249 //       default:
250         if ( !withSub ) return;
251         SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,false);
252         while ( smIt->more() )
253           Clean( smIt->next(), false );
254 //       }
255     }
256   };
257
258   //================================================================================
259   /*!
260    * \brief find new nodes belonging to one free border of mesh on face
261     * \param sm - submesh on edge or vertex containg nodes to choose from
262     * \param face - the face bound by the submesh
263     * \param u2nodes - map to fill with nodes
264     * \param seamNodes - set of found nodes
265     * \retval bool - is a success
266    */
267   //================================================================================
268
269   bool getBoundaryNodes ( SMESH_subMesh*                        sm,
270                           const TopoDS_Face&                    face,
271                           map< double, const SMDS_MeshNode* > & u2nodes,
272                           set< const SMDS_MeshNode* > &         seamNodes)
273   {
274     u2nodes.clear();
275     seamNodes.clear();
276     if ( !sm || !sm->GetSubMeshDS() )
277       RETURN_BAD_RESULT("Null submesh");
278
279     SMDS_NodeIteratorPtr nIt = sm->GetSubMeshDS()->GetNodes();
280     switch ( sm->GetSubShape().ShapeType() ) {
281
282     case TopAbs_VERTEX: {
283       while ( nIt->more() ) {
284         const SMDS_MeshNode* node = nIt->next();
285         if ( isOldNode( node ) ) continue;
286         u2nodes.insert( make_pair( 0., node ));
287         seamNodes.insert( node );
288         return true;
289       }
290       break;
291     }
292     case TopAbs_EDGE: {
293       
294       // Get submeshes of sub-vertices
295       const map< int, SMESH_subMesh * >& subSM = sm->DependsOn();
296       if ( subSM.size() != 2 )
297         RETURN_BAD_RESULT("there must be 2 submeshes of sub-vertices"
298                           " but we have " << subSM.size());
299       SMESH_subMesh* smV1 = subSM.begin()->second;
300       SMESH_subMesh* smV2 = subSM.rbegin()->second;
301       if ( !smV1->IsMeshComputed() || !smV2->IsMeshComputed() )
302         RETURN_BAD_RESULT("Empty vertex submeshes");
303
304       const SMDS_MeshNode* nV1 = 0;
305       const SMDS_MeshNode* nE = 0;
306
307       // Look for nV1 - a new node on V1
308       nIt = smV1->GetSubMeshDS()->GetNodes();
309       while ( nIt->more() && !nE ) {
310         const SMDS_MeshNode* node = nIt->next();
311         if ( isOldNode( node ) ) continue;
312         nV1 = node;
313
314         // Find nE - a new node connected to nV1 and belonging to edge submesh;
315         SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
316         SMDS_ElemIteratorPtr vElems = nV1->GetInverseElementIterator(SMDSAbs_Face);
317         while ( vElems->more() && !nE ) {
318           const SMDS_MeshElement* elem = vElems->next();
319           int nbNodes = elem->NbNodes();
320           if ( elem->IsQuadratic() )
321             nbNodes /= 2;
322           int iV1 = elem->GetNodeIndex( nV1 );
323           // try next after nV1
324           int iE = SMESH_MesherHelper::WrapIndex( iV1 + 1, nbNodes );
325           if ( smDS->Contains( elem->GetNode( iE ) ))
326             nE = elem->GetNode( iE );
327           if ( !nE ) {
328             // try node before nV1
329             iE = SMESH_MesherHelper::WrapIndex( iV1 - 1, nbNodes );
330             if ( smDS->Contains( elem->GetNode( iE )))
331               nE = elem->GetNode( iE );
332           }
333           if ( nE && elem->IsQuadratic() ) { // find medium node between nV1 and nE
334             if ( Abs( iV1 - iE ) == 1 )
335               nE = elem->GetNode( Min ( iV1, iE ) + nbNodes );
336             else
337               nE = elem->GetNode( elem->NbNodes() - 1 );
338           }
339         }
340       }
341       if ( !nV1 )
342         RETURN_BAD_RESULT("No new node found on V1");
343       if ( !nE )
344         RETURN_BAD_RESULT("new node on edge not found");
345
346       // Get the whole free border of a face
347       list< const SMDS_MeshNode* > bordNodes;
348       list< const SMDS_MeshElement* > bordFaces;
349       if ( !SMESH_MeshEditor::FindFreeBorder (nV1, nE, nV1, bordNodes, bordFaces ))
350         RETURN_BAD_RESULT("free border of a face not found by nodes " <<
351                           nV1->GetID() << " " << nE->GetID() );
352
353       // Insert nodes of the free border to the map until node on V2 encountered
354       SMESHDS_SubMesh* v2smDS = smV2->GetSubMeshDS();
355       list< const SMDS_MeshNode* >::iterator bordIt = bordNodes.begin();
356       bordIt++; // skip nV1
357       for ( ; bordIt != bordNodes.end(); ++bordIt ) {
358         const SMDS_MeshNode* node = *bordIt;
359         if ( v2smDS->Contains( node ))
360           break;
361         if ( node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
362           RETURN_BAD_RESULT("Bad node position type: node " << node->GetID() <<
363                             " pos type " << node->GetPosition()->GetTypeOfPosition());
364         const SMDS_EdgePosition* pos =
365           static_cast<const SMDS_EdgePosition*>(node->GetPosition());
366         u2nodes.insert( make_pair( pos->GetUParameter(), node ));
367         seamNodes.insert( node );
368       }
369       if ( u2nodes.size() != seamNodes.size() )
370         RETURN_BAD_RESULT("Bad node params on edge " << sm->GetId() <<
371                           ", " << u2nodes.size() << " != " << seamNodes.size() );
372       return true;
373     }
374     default:;
375     }
376     RETURN_BAD_RESULT ("Unexpected submesh type");
377
378   } // bool getBoundaryNodes()
379
380   //================================================================================
381   /*!
382    * \brief Check if two consecutive EDGEs are connected in 2D
383    *  \param [in] E1 - a well oriented non-seam EDGE
384    *  \param [in] E2 - a possibly well oriented seam EDGE
385    *  \param [in] F - a FACE
386    *  \return bool - result
387    */
388   //================================================================================
389
390   bool are2dConnected( const TopoDS_Edge & E1,
391                        const TopoDS_Edge & E2,
392                        const TopoDS_Face & F )
393   {
394     double f,l;
395     Handle(Geom2d_Curve) c1 = BRep_Tool::CurveOnSurface( E1, F, f, l );
396     gp_Pnt2d uvLast1 = c1->Value( E1.Orientation() == TopAbs_REVERSED ? f : l );
397
398     Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( E2, F, f, l );
399     gp_Pnt2d uvFirst2 = c2->Value( f );
400     gp_Pnt2d uvLast2  = c2->Value( l );
401     double tol2 = 1e-5 * uvLast2.SquareDistance( uvFirst2 );
402
403     return (( uvLast1.SquareDistance( uvFirst2 ) < tol2 ) ||
404             ( uvLast1.SquareDistance( uvLast2 ) < tol2 ));
405   }
406
407   //================================================================================
408   /*!
409    * \brief Compose TSideVector for both FACEs keeping matching order of EDGEs
410    *        and fill src2tgtNodes map
411    */
412   //================================================================================
413
414   TError getWires(const TopoDS_Face&                 tgtFace,
415                   const TopoDS_Face&                 srcFace,
416                   SMESH_Mesh *                       tgtMesh,
417                   SMESH_Mesh *                       srcMesh,
418                   const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
419                   TSideVector&                       srcWires,
420                   TSideVector&                       tgtWires,
421                   TAssocTool::TNodeNodeMap&          src2tgtNodes,
422                   bool&                              is1DComputed)
423   {
424     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
425     SMESHDS_Mesh* srcMeshDS = srcMesh->GetMeshDS();
426
427     src2tgtNodes.clear();
428
429     // get ordered src EDGEs
430     TError err;
431     srcWires = StdMeshers_FaceSide::GetFaceWires( srcFace, *srcMesh,/*skipMediumNodes=*/0, err);
432     if ( err && !err->IsOK() || srcWires.empty() )
433       return err;
434
435     SMESH_MesherHelper srcHelper( *srcMesh );
436     srcHelper.SetSubShape( srcFace );
437
438     // make corresponding sequence of tgt EDGEs
439     tgtWires.resize( srcWires.size() );
440     for ( size_t iW = 0; iW < srcWires.size(); ++iW )
441     {
442       // check ori
443       bool reverse = false;
444       StdMeshers_FaceSidePtr srcWire = srcWires[iW];
445       // for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
446       // {
447       //   if ( srcHelper.IsRealSeam( srcWire->EdgeID( iE )))
448       //     continue;
449       //   TopoDS_Shape srcE = srcWire->Edge( iE );
450       //   TopoDS_Shape tgtE = shape2ShapeMap( srcE, /*isSrc=*/true);
451       //   if ( shape2ShapeMap._assocType == TShapeShapeMap::PROPAGATION ||
452       //        shape2ShapeMap._assocType == TShapeShapeMap::PROPAGATION)
453       //   {
454       //     reverse = false;
455       //   }
456       //   else if ( tgtMesh == srcMesh )
457       //   {
458       //     reverse = (( srcE.Orientation() == srcHelper.GetSubShapeOri( srcFace, srcE )) !=
459       //                ( tgtE.Orientation() == srcHelper.GetSubShapeOri( tgtFace, tgtE )));
460       //   }
461       //   else
462       //   {
463       //     TopoDS_Shape srcEbis = shape2ShapeMap( tgtE, /*isSrc=*/false );
464       //     reverse = ( srcE.Orientation() != srcEbis.Orientation() );
465       //   }
466       //   break;
467       // }
468
469       list< TopoDS_Edge > tgtEdges;
470       TopTools_IndexedMapOfShape edgeMap; // to detect seam edges
471       for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
472       {
473         TopoDS_Edge     srcE = srcWire->Edge( iE );
474         TopoDS_Edge     tgtE = TopoDS::Edge( shape2ShapeMap( srcE, /*isSrc=*/true));
475         TopoDS_Shape srcEbis = shape2ShapeMap( tgtE, /*isSrc=*/false );
476         if ( srcE.Orientation() != srcEbis.Orientation() )
477           //if ( reverse )
478           tgtE.Reverse();
479         // reverse a seam edge encountered for the second time
480         const int index = edgeMap.Add( tgtE );
481         if ( index < edgeMap.Extent() ) // E is a seam
482         {
483           // check which of edges to reverse, E or one already being in tgtEdges
484           if ( are2dConnected( tgtEdges.back(), tgtE, tgtFace ))
485           {
486             list< TopoDS_Edge >::iterator eIt = tgtEdges.begin();
487             std::advance( eIt, index-1 );
488             eIt->Reverse();
489           }
490           else
491           {
492             tgtE.Reverse();
493           }
494         }
495         if ( srcWire->NbEdges() == 1 && tgtMesh == srcMesh ) // circle
496         {
497           // try to verify ori by propagation
498           pair<int,TopoDS_Edge> nE =
499             StdMeshers_ProjectionUtils::GetPropagationEdge( srcMesh, tgtE, srcE );
500           if ( !nE.second.IsNull() )
501             tgtE = nE.second;
502         }
503         tgtEdges.push_back( tgtE );
504
505
506         // Fill map of src to tgt nodes with nodes on edges
507
508         if ( srcMesh->GetSubMesh( srcE )->IsEmpty() ||
509              tgtMesh->GetSubMesh( tgtE )->IsEmpty() )
510         {
511           // add nodes on VERTEXes for a case of not meshes EDGEs
512           const TopoDS_Shape&  srcV = SMESH_MesherHelper::IthVertex( 0, srcE );
513           const TopoDS_Shape&  tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
514           const SMDS_MeshNode* srcN = SMESH_Algo::VertexNode( TopoDS::Vertex( srcV ), srcMeshDS );
515           const SMDS_MeshNode* tgtN = SMESH_Algo::VertexNode( TopoDS::Vertex( tgtV ), tgtMeshDS );
516           if ( srcN && tgtN )
517             src2tgtNodes.insert( make_pair( srcN, tgtN ));
518         }
519         else
520         {
521           const bool skipMediumNodes = true;
522           map< double, const SMDS_MeshNode* > srcNodes, tgtNodes;
523           if ( !SMESH_Algo::GetSortedNodesOnEdge( srcMeshDS, srcE, skipMediumNodes, srcNodes) ||
524                !SMESH_Algo::GetSortedNodesOnEdge( tgtMeshDS, tgtE, skipMediumNodes, tgtNodes ))
525             return SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH,
526                                             "Invalid node parameters on edges");
527
528           if (( srcNodes.size() != tgtNodes.size() ) && tgtNodes.size() > 0 )
529             return SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH,
530                                             "Different number of nodes on edges");
531           if ( !tgtNodes.empty() )
532           {
533             map< double, const SMDS_MeshNode* >::iterator u_tn = tgtNodes.begin();
534             if ( srcE.Orientation() == tgtE.Orientation() )
535             {
536               map< double, const SMDS_MeshNode* >::iterator u_sn = srcNodes.begin();
537               for ( ; u_tn != tgtNodes.end(); ++u_tn, ++u_sn)
538                 src2tgtNodes.insert( make_pair( u_sn->second, u_tn->second ));
539             }
540             else
541             {
542               map< double, const SMDS_MeshNode* >::reverse_iterator u_sn = srcNodes.rbegin();
543               for ( ; u_tn != tgtNodes.end(); ++u_tn, ++u_sn)
544                 src2tgtNodes.insert( make_pair( u_sn->second, u_tn->second ));
545             }
546             is1DComputed = true;
547           }
548         }
549       } // loop on EDGEs of a WIRE
550
551       tgtWires[ iW ].reset( new StdMeshers_FaceSide( tgtFace, tgtEdges, tgtMesh,
552                                                      /*theIsForward = */ true,
553                                                      /*theIgnoreMediumNodes = */false));
554     } // loop on WIREs
555
556     return TError();
557   }
558
559   //================================================================================
560   /*!
561    * \brief Preform projection in case if tgtFace.IsPartner( srcFace ) and in case
562    * if projection by 3D transformation is possible
563    */
564   //================================================================================
565
566   bool projectPartner(const TopoDS_Face&                 tgtFace,
567                       const TopoDS_Face&                 srcFace,
568                       const TSideVector&                 tgtWires,
569                       const TSideVector&                 srcWires,
570                       const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
571                       TAssocTool::TNodeNodeMap&          src2tgtNodes,
572                       const bool                         is1DComputed)
573   {
574     SMESH_Mesh *    tgtMesh = tgtWires[0]->GetMesh();
575     SMESH_Mesh *    srcMesh = srcWires[0]->GetMesh();
576     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
577     SMESHDS_Mesh* srcMeshDS = srcMesh->GetMeshDS();
578     SMESH_MesherHelper helper( *tgtMesh );
579
580     const double tol = 1.e-7 * srcMeshDS->getMaxDim();
581
582     // transformation to get location of target nodes from source ones
583     StdMeshers_ProjectionUtils::TrsfFinder3D trsf;
584     bool trsfIsOK = true;
585     if ( tgtFace.IsPartner( srcFace ))
586     {
587       gp_GTrsf srcTrsf = srcFace.Location().Transformation();
588       gp_GTrsf tgtTrsf = tgtFace.Location().Transformation();
589       gp_GTrsf t = srcTrsf.Inverted().Multiplied( tgtTrsf );
590       trsf.Set( t );
591       // check
592       gp_Pnt srcP = BRep_Tool::Pnt( srcWires[0]->FirstVertex() );
593       gp_Pnt tgtP = BRep_Tool::Pnt( tgtWires[0]->FirstVertex() );
594       trsfIsOK = ( tgtP.Distance( trsf.Transform( srcP )) < tol );
595       if ( !trsfIsOK )
596       {
597         trsf.Set( tgtTrsf.Inverted().Multiplied( srcTrsf ));
598         trsfIsOK = ( tgtP.Distance( trsf.Transform( srcP )) < tol );
599       }
600     }
601     if ( !trsfIsOK )
602     {
603       // Try to find the 3D transformation
604
605       const int totNbSeg = 50;
606       vector< gp_XYZ > srcPnts, tgtPnts;
607       srcPnts.reserve( totNbSeg );
608       tgtPnts.reserve( totNbSeg );
609       gp_XYZ srcBC( 0,0,0 ), tgtBC( 0,0,0 );
610       for ( size_t iW = 0; iW < srcWires.size(); ++iW )
611       {
612         const double minSegLen = srcWires[iW]->Length() / totNbSeg;
613         for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
614         {
615           int nbSeg    = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
616           double srcU  = srcWires[iW]->FirstParameter( iE );
617           double tgtU  = tgtWires[iW]->FirstParameter( iE );
618           double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
619           double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
620           for ( size_t i = 0; i < nbSeg; ++i  )
621           {
622             srcPnts.push_back( srcWires[iW]->Value3d( srcU ).XYZ() );
623             tgtPnts.push_back( tgtWires[iW]->Value3d( tgtU ).XYZ() );
624             srcU += srcDu;
625             tgtU += tgtDu;
626             srcBC += srcPnts.back();
627             tgtBC += tgtPnts.back();
628           }
629         }
630       }
631       if ( !trsf.Solve( srcPnts, tgtPnts ))
632         return false;
633
634       // check trsf
635
636       const int nbTestPnt = 20;
637       const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
638       // check boundary
639       gp_Pnt trsfTgt = trsf.Transform( srcBC / srcPnts.size() );
640       trsfIsOK = ( trsfTgt.SquareDistance( tgtBC / tgtPnts.size() ) < tol*tol );
641       for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
642       {
643         gp_Pnt trsfTgt = trsf.Transform( srcPnts[i] );
644         trsfIsOK = ( trsfTgt.SquareDistance( tgtPnts[i] ) < tol*tol );
645       }
646       // check an in-FACE point
647       if ( trsfIsOK )
648       {
649         BRepAdaptor_Surface srcSurf( srcFace );
650         gp_Pnt srcP =
651           srcSurf.Value( 0.321 * ( srcSurf.FirstUParameter() + srcSurf.LastUParameter() ),
652                          0.123 * ( srcSurf.FirstVParameter() + srcSurf.LastVParameter() ));
653         gp_Pnt tgtTrsfP = trsf.Transform( srcP );
654         TopLoc_Location loc;
655         GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( tgtFace, loc, 0.1*tol );
656         if ( !loc.IsIdentity() )
657           tgtTrsfP.Transform( loc.Transformation().Inverted() );
658         proj.Perform( tgtTrsfP );
659         trsfIsOK = ( proj.IsDone() &&
660                      proj.NbPoints() > 0 &&
661                      proj.LowerDistance() < tol );
662       }
663       if ( !trsfIsOK )
664         return false;
665     }
666
667     // Make new faces
668
669     // prepare the helper to adding quadratic elements if necessary
670     helper.SetSubShape( tgtFace );
671     helper.IsQuadraticSubMesh( tgtFace );
672
673     SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
674     if ( !is1DComputed && srcSubDS->NbElements() )
675       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
676
677     SMESH_MesherHelper srcHelper( *srcMesh );
678     srcHelper.SetSubShape( srcFace );
679
680     const SMDS_MeshNode* nullNode = 0;
681     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
682
683     // indices of nodes to create properly oriented faces
684     bool isReverse = ( !trsf.IsIdentity() );
685     int tri1 = 1, tri2 = 2, quad1 = 1, quad3 = 3;
686     if ( isReverse )
687       std::swap( tri1, tri2 ), std::swap( quad1, quad3 );
688
689     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
690     vector< const SMDS_MeshNode* > tgtNodes;
691     while ( elemIt->more() ) // loop on all mesh faces on srcFace
692     {
693       const SMDS_MeshElement* elem = elemIt->next();
694       const int nbN = elem->NbCornerNodes(); 
695       tgtNodes.resize( nbN );
696       helper.SetElementsOnShape( false );
697       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
698       {
699         const SMDS_MeshNode* srcNode = elem->GetNode(i);
700         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
701         if ( srcN_tgtN->second == nullNode )
702         {
703           // create a new node
704           gp_Pnt tgtP = trsf.Transform( SMESH_TNodeXYZ( srcNode ));
705           SMDS_MeshNode* n = helper.AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
706           srcN_tgtN->second = n;
707           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
708           {
709           case SMDS_TOP_FACE:
710           {
711             gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode );
712             tgtMeshDS->SetNodeOnFace( n, helper.GetSubShapeID(), srcUV.X(), srcUV.Y() );
713             break;
714           }
715           case SMDS_TOP_EDGE:
716           {
717             const TopoDS_Shape & srcE = srcMeshDS->IndexToShape( srcNode->getshapeId() );
718             const TopoDS_Shape & tgtE = shape2ShapeMap( srcE, /*isSrc=*/true );
719             double srcU = srcHelper.GetNodeU( TopoDS::Edge( srcE ), srcNode );
720             tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtE ), srcU );
721             break;
722           }
723           case SMDS_TOP_VERTEX:
724           {
725             const TopoDS_Shape & srcV = srcMeshDS->IndexToShape( srcNode->getshapeId() );
726             const TopoDS_Shape & tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
727             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
728             break;
729           }
730           default:;
731           }
732         }
733         tgtNodes[i] = srcN_tgtN->second;
734       }
735       // create a new face
736       helper.SetElementsOnShape( true );
737       switch ( nbN )
738       {
739       case 3: helper.AddFace(tgtNodes[0], tgtNodes[tri1], tgtNodes[tri2]); break;
740       case 4: helper.AddFace(tgtNodes[0], tgtNodes[quad1], tgtNodes[2], tgtNodes[quad3]); break;
741       default:
742         if ( isReverse ) std::reverse( tgtNodes.begin(), tgtNodes.end() );
743         helper.AddPolygonalFace( tgtNodes );
744       }
745     }
746
747     // check node positions
748
749     if ( !tgtFace.IsPartner( srcFace ) )
750     {
751       SMESH_MesherHelper edgeHelper( *tgtMesh );
752       edgeHelper.ToFixNodeParameters( true );
753       helper.ToFixNodeParameters( true );
754
755       int nbOkPos = 0;
756       bool toCheck = true;
757       const double tol2d = 1e-12;
758       srcN_tgtN = src2tgtNodes.begin();
759       for ( ; srcN_tgtN != src2tgtNodes.end(); ++srcN_tgtN )
760       {
761         const SMDS_MeshNode* n = srcN_tgtN->second;
762         switch ( n->GetPosition()->GetTypeOfPosition() )
763         {
764         case SMDS_TOP_FACE:
765         {
766           if ( nbOkPos > 10 ) break;
767           gp_XY uv = helper.GetNodeUV( tgtFace, n ), uvBis = uv;
768           if (( helper.CheckNodeUV( tgtFace, n, uv, tol )) &&
769               (( uv - uvBis ).SquareModulus() < tol2d ))
770             ++nbOkPos;
771           else
772             nbOkPos = -((int) src2tgtNodes.size() );
773           break;
774         }
775         case SMDS_TOP_EDGE:
776         {
777           const TopoDS_Edge & tgtE = TopoDS::Edge( tgtMeshDS->IndexToShape( n->getshapeId() ));
778           edgeHelper.SetSubShape( tgtE );
779           edgeHelper.GetNodeU( tgtE, n, 0, &toCheck );
780           break;
781         }
782         default:;
783         }
784       }
785     }
786
787     return true;
788
789   } //   bool projectPartner()
790
791   //================================================================================
792   /*!
793    * \brief Preform projection in case if the faces are similar in 2D space
794    */
795   //================================================================================
796
797   bool projectBy2DSimilarity(const TopoDS_Face&                 tgtFace,
798                              const TopoDS_Face&                 srcFace,
799                              const TSideVector&                 tgtWires,
800                              const TSideVector&                 srcWires,
801                              const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
802                              TAssocTool::TNodeNodeMap&          src2tgtNodes,
803                              const bool                         is1DComputed)
804   {
805     SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
806     SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
807
808     // WARNING: we can have problems if the FACE is symmetrical in 2D,
809     // then the projection can be mirrored relating to what is expected
810
811     // 1) Find 2D transformation
812
813     StdMeshers_ProjectionUtils::TrsfFinder2D trsf;
814     {
815       // get 2 pairs of corresponding UVs
816       gp_Pnt2d srcP0 = srcWires[0]->Value2d(0.0);
817       gp_Pnt2d srcP1 = srcWires[0]->Value2d(0.333);
818       gp_Pnt2d tgtP0 = tgtWires[0]->Value2d(0.0);
819       gp_Pnt2d tgtP1 = tgtWires[0]->Value2d(0.333);
820
821       // make transformation
822       gp_Trsf2d fromTgtCS, toSrcCS; // from/to global CS
823       gp_Ax2d srcCS( srcP0, gp_Vec2d( srcP0, srcP1 ));
824       gp_Ax2d tgtCS( tgtP0, gp_Vec2d( tgtP0, tgtP1 ));
825       toSrcCS  .SetTransformation( srcCS );
826       fromTgtCS.SetTransformation( tgtCS );
827       fromTgtCS.Invert();
828       trsf.Set( fromTgtCS * toSrcCS );
829
830       // check transformation
831       bool trsfIsOK = true;
832       const double tol = 1e-5 * gp_Vec2d( srcP0, srcP1 ).Magnitude();
833       for ( double u = 0.12; ( u < 1. && trsfIsOK ); u += 0.1 )
834       {
835         gp_Pnt2d srcUV  = srcWires[0]->Value2d( u );
836         gp_Pnt2d tgtUV  = tgtWires[0]->Value2d( u );
837         gp_Pnt2d tgtUV2 = trsf.Transform( srcUV );
838         trsfIsOK = ( tgtUV.Distance( tgtUV2 ) < tol );
839       }
840
841       // Find trsf using a least-square approximation
842       if ( !trsfIsOK )
843       {
844         // find trsf
845         const int totNbSeg = 50;
846         vector< gp_XY > srcPnts, tgtPnts;
847         srcPnts.resize( totNbSeg );
848         tgtPnts.resize( totNbSeg );
849         for ( size_t iW = 0; iW < srcWires.size(); ++iW )
850         {
851           const double minSegLen = srcWires[iW]->Length() / totNbSeg;
852           for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
853           {
854             int nbSeg    = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
855             double srcU  = srcWires[iW]->FirstParameter( iE );
856             double tgtU  = tgtWires[iW]->FirstParameter( iE );
857             double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
858             double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
859             for ( size_t i = 0; i < nbSeg; ++i, srcU += srcDu, tgtU += tgtDu  )
860             {
861               srcPnts.push_back( srcWires[iW]->Value2d( srcU ).XY() );
862               tgtPnts.push_back( tgtWires[iW]->Value2d( tgtU ).XY() );
863             }
864           }
865         }
866         if ( !trsf.Solve( srcPnts, tgtPnts ))
867           return false;
868
869         // check trsf
870
871         trsfIsOK = true;
872         const int nbTestPnt = 10;
873         const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
874         for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
875         {
876           gp_Pnt2d trsfTgt = trsf.Transform( srcPnts[i] );
877           trsfIsOK = ( trsfTgt.Distance( tgtPnts[i] ) < tol );
878         }
879         if ( !trsfIsOK )
880           return false;
881       }
882     } // "Find transformation" block
883
884     // 2) Projection
885
886     SMESHDS_SubMesh* srcSubDS = srcMesh->GetMeshDS()->MeshElements( srcFace );
887
888     SMESH_MesherHelper helper( *tgtMesh );
889     helper.SetSubShape( tgtFace );
890     if ( is1DComputed )
891       helper.IsQuadraticSubMesh( tgtFace );
892     else
893       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
894     helper.SetElementsOnShape( true );
895     Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
896     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
897
898     SMESH_MesherHelper srcHelper( *srcMesh );
899     srcHelper.SetSubShape( srcFace );
900
901     const SMDS_MeshNode* nullNode = 0;
902     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
903
904     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
905     vector< const SMDS_MeshNode* > tgtNodes;
906     bool uvOK;
907     while ( elemIt->more() ) // loop on all mesh faces on srcFace
908     {
909       const SMDS_MeshElement* elem = elemIt->next();
910       const int nbN = elem->NbCornerNodes(); 
911       tgtNodes.resize( nbN );
912       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
913       {
914         const SMDS_MeshNode* srcNode = elem->GetNode(i);
915         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
916         if ( srcN_tgtN->second == nullNode )
917         {
918           // create a new node
919           gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode,
920                                                 elem->GetNode( helper.WrapIndex(i+1,nbN)), &uvOK);
921           gp_Pnt2d   tgtUV = trsf.Transform( srcUV );
922           gp_Pnt      tgtP = tgtSurface->Value( tgtUV.X(), tgtUV.Y() );
923           SMDS_MeshNode* n = tgtMeshDS->AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
924           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
925           {
926           case SMDS_TOP_FACE: {
927             tgtMeshDS->SetNodeOnFace( n, helper.GetSubShapeID(), tgtUV.X(), tgtUV.Y() );
928             break;
929           }
930           case SMDS_TOP_EDGE: {
931             TopoDS_Shape srcEdge = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
932             TopoDS_Edge  tgtEdge = TopoDS::Edge( shape2ShapeMap( srcEdge, /*isSrc=*/true ));
933             double U = Precision::Infinite();
934             helper.CheckNodeU( tgtEdge, n, U, Precision::PConfusion());
935             tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtEdge ), U );
936             break;
937           }
938           case SMDS_TOP_VERTEX: {
939             TopoDS_Shape srcV = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
940             TopoDS_Shape tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
941             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
942             break;
943           }
944           }
945           srcN_tgtN->second = n;
946         }
947         tgtNodes[i] = srcN_tgtN->second;
948       }
949       // create a new face (with reversed orientation)
950       switch ( nbN )
951       {
952       case 3: helper.AddFace(tgtNodes[0], tgtNodes[2], tgtNodes[1]); break;
953       case 4: helper.AddFace(tgtNodes[0], tgtNodes[3], tgtNodes[2], tgtNodes[1]); break;
954       }
955     }
956     return true;
957
958   } // bool projectBy2DSimilarity(...)
959
960   //================================================================================
961   /*!
962    * \brief Fix bad faces by smoothing
963    */
964   //================================================================================
965
966   bool fixDistortedFaces( SMESH_MesherHelper& helper,
967                           TSideVector&        tgtWires )
968   {
969     SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMesh( helper.GetSubShape() );
970
971     if ( helper.IsDistorted2D( faceSM, /*checkUV=*/false ))
972     {
973       SMESH_MeshEditor editor( helper.GetMesh() );
974       SMESHDS_SubMesh* smDS = faceSM->GetSubMeshDS();
975       const TopoDS_Face&  F = TopoDS::Face( faceSM->GetSubShape() );
976
977       TIDSortedElemSet faces;
978       SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
979       for ( faceIt = smDS->GetElements(); faceIt->more(); )
980         faces.insert( faces.end(), faceIt->next() );
981
982       // choose smoothing algo
983       //SMESH_MeshEditor:: SmoothMethod algo = SMESH_MeshEditor::CENTROIDAL;
984       bool isConcaveBoundary = false;
985       for ( size_t iW = 0; iW < tgtWires.size() && !isConcaveBoundary; ++iW )
986       {
987         TopoDS_Edge prevEdge = tgtWires[iW]->Edge( tgtWires[iW]->NbEdges() - 1 );
988         for ( int iE = 0; iE < tgtWires[iW]->NbEdges() && !isConcaveBoundary; ++iE )
989         {
990           double angle = helper.GetAngle( prevEdge, tgtWires[iW]->Edge( iE ),
991                                           F,        tgtWires[iW]->FirstVertex( iE ));
992           isConcaveBoundary = ( angle < -5. * M_PI / 180. );
993
994           prevEdge = tgtWires[iW]->Edge( iE );
995         }
996       }
997       SMESH_MeshEditor:: SmoothMethod algo =
998         isConcaveBoundary ? SMESH_MeshEditor::CENTROIDAL : SMESH_MeshEditor::LAPLACIAN;
999
1000       // smooth in 2D or 3D?
1001       TopLoc_Location loc;
1002       Handle(Geom_Surface) surface = BRep_Tool::Surface( F, loc );
1003       bool isPlanar = GeomLib_IsPlanarSurface( surface ).IsPlanar();
1004
1005       // smoothing
1006       set<const SMDS_MeshNode*> fixedNodes;
1007       editor.Smooth( faces, fixedNodes, algo, /*nbIterations=*/ 10,
1008                      /*theTgtAspectRatio=*/1.0, /*the2D=*/!isPlanar);
1009
1010       helper.ToFixNodeParameters( true );
1011
1012       return !helper.IsDistorted2D( faceSM, /*checkUV=*/true );
1013     }
1014     return true;
1015   }
1016
1017 } // namespace
1018
1019
1020 //=======================================================================
1021 //function : Compute
1022 //purpose  :
1023 //=======================================================================
1024
1025 bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
1026 {
1027   _src2tgtNodes.clear();
1028
1029   MESSAGE("Projection_2D Compute");
1030   if ( !_sourceHypo )
1031     return false;
1032
1033   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1034   SMESH_Mesh * tgtMesh = & theMesh;
1035   if ( !srcMesh )
1036     srcMesh = tgtMesh;
1037
1038   SMESHDS_Mesh * meshDS = theMesh.GetMeshDS();
1039   SMESH_MesherHelper helper( theMesh );
1040
1041   // ---------------------------
1042   // Make sub-shapes association
1043   // ---------------------------
1044
1045   TopoDS_Face   tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
1046   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
1047
1048   TAssocTool::TShapeShapeMap shape2ShapeMap;
1049   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
1050   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
1051                                              shape2ShapeMap)  ||
1052        !shape2ShapeMap.IsBound( tgtFace ))
1053   {
1054     if ( srcShape.ShapeType() == TopAbs_FACE )
1055     {
1056       int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1057       int nbE2 = helper.Count( srcShape, TopAbs_EDGE, /*ignoreSame=*/true );
1058       if ( nbE1 != nbE2 )
1059         return error(COMPERR_BAD_SHAPE,
1060                      SMESH_Comment("Different number of edges in source and target faces: ")
1061                      << nbE2 << " and " << nbE1 );
1062     }
1063     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
1064   }
1065   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
1066
1067   // orient faces
1068   // if ( srcMesh == tgtMesh )
1069   // {
1070   //   TopoDS_Shape solid =
1071   //     helper.GetCommonAncestor( srcFace, tgtFace, *tgtMesh, TopAbs_SOLID );
1072   //   if ( !solid.IsNull() )
1073   //   {
1074   //     srcFace.Orientation( helper.GetSubShapeOri( solid, srcFace ));
1075   //     tgtFace.Orientation( helper.GetSubShapeOri( solid, tgtFace ));
1076   //   }
1077   //   else if ( helper.NbAncestors( srcFace, *tgtMesh, TopAbs_SOLID ) == 1 &&
1078   //             helper.NbAncestors( tgtFace, *tgtMesh, TopAbs_SOLID ) == 1 )
1079   //   {
1080   //     srcFace.Orientation( helper.GetSubShapeOri( tgtMesh->GetShapeToMesh(), srcFace ));
1081   //     tgtFace.Orientation( helper.GetSubShapeOri( tgtMesh->GetShapeToMesh(), tgtFace ));
1082   //   }
1083   // }
1084   // ----------------------------------------------
1085   // Assure that mesh on a source Face is computed
1086   // ----------------------------------------------
1087
1088   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
1089   SMESH_subMesh* tgtSubMesh = tgtMesh->GetSubMesh( tgtFace );
1090
1091   string srcMeshError;
1092   if ( tgtMesh == srcMesh ) {
1093     if ( !TAssocTool::MakeComputed( srcSubMesh ))
1094       srcMeshError = TAssocTool::SourceNotComputedError( srcSubMesh, this );
1095   }
1096   else {
1097     if ( !srcSubMesh->IsMeshComputed() )
1098       srcMeshError = TAssocTool::SourceNotComputedError();
1099   }
1100   if ( !srcMeshError.empty() )
1101     return error(COMPERR_BAD_INPUT_MESH, srcMeshError );
1102
1103   // ===========
1104   // Projection
1105   // ===========
1106
1107   // get ordered src and tgt EDGEs
1108   TSideVector srcWires, tgtWires;
1109   bool is1DComputed = false; // if any tgt EDGE is meshed
1110   TError err = getWires( tgtFace, srcFace, tgtMesh, srcMesh,
1111                          shape2ShapeMap, srcWires, tgtWires, _src2tgtNodes, is1DComputed );
1112   if ( err && !err->IsOK() )
1113     return error( err );
1114
1115   bool projDone = false;
1116
1117   if ( !projDone )
1118   {
1119     // try to project from the same face with different location
1120     projDone = projectPartner( tgtFace, srcFace, tgtWires, srcWires,
1121                                shape2ShapeMap, _src2tgtNodes, is1DComputed );
1122   }
1123   if ( !projDone )
1124   {
1125     // projection in case if the faces are similar in 2D space
1126     projDone = projectBy2DSimilarity( tgtFace, srcFace, tgtWires, srcWires,
1127                                       shape2ShapeMap, _src2tgtNodes, is1DComputed);
1128   }
1129
1130   helper.SetSubShape( tgtFace );
1131
1132   // it will remove mesh built on edges and vertices in failure case
1133   MeshCleaner cleaner( tgtSubMesh );
1134
1135   if ( !projDone )
1136   {
1137     _src2tgtNodes.clear();
1138     // --------------------
1139     // Prepare to mapping 
1140     // --------------------
1141
1142     // Check if node projection to a face is needed
1143     Bnd_B2d uvBox;
1144     SMDS_ElemIteratorPtr faceIt = srcSubMesh->GetSubMeshDS()->GetElements();
1145     set< const SMDS_MeshNode* > faceNodes;
1146     for ( ; faceNodes.size() < 3 && faceIt->more();  ) {
1147       const SMDS_MeshElement* face = faceIt->next();
1148       SMDS_ElemIteratorPtr nodeIt = face->nodesIterator();
1149       while ( nodeIt->more() ) {
1150         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
1151         if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE &&
1152              faceNodes.insert( node ).second )
1153           uvBox.Add( helper.GetNodeUV( srcFace, node ));
1154       }
1155     }
1156     bool toProjectNodes = false;
1157     if ( faceNodes.size() == 1 )
1158       toProjectNodes = ( uvBox.IsVoid() || uvBox.CornerMin().IsEqual( gp_XY(0,0), 1e-12 ));
1159     else if ( faceNodes.size() > 1 )
1160       toProjectNodes = ( uvBox.IsVoid() || uvBox.SquareExtent() < DBL_MIN );
1161
1162     // Find the corresponding source and target vertex
1163     // and <theReverse> flag needed to call mapper.Apply()
1164
1165     TopoDS_Vertex srcV1, tgtV1;
1166     bool reverse = false;
1167
1168     TopExp_Explorer vSrcExp( srcFace, TopAbs_VERTEX );
1169     srcV1 = TopoDS::Vertex( vSrcExp.Current() );
1170     tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
1171
1172     list< TopoDS_Edge > tgtEdges, srcEdges;
1173     list< int > nbEdgesInWires;
1174     SMESH_Block::GetOrderedEdges( tgtFace, tgtEdges, nbEdgesInWires, tgtV1 );
1175     SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
1176
1177     if ( nbEdgesInWires.front() > 1 ) // possible to find out orientation
1178     {
1179       TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
1180       TopoDS_Shape srcE1bis = shape2ShapeMap( tgtE1 );
1181       reverse = ( ! srcE1.IsSame( srcE1bis ));
1182       if ( reverse &&
1183            //_sourceHypo->HasVertexAssociation() &&
1184            nbEdgesInWires.front() > 2 &&
1185            helper.IsRealSeam( tgtEdges.front() ))
1186       {
1187         // projection to a face with seam EDGE; pb is that GetOrderedEdges()
1188         // always puts a seam EDGE first (if possible) and as a result
1189         // we can't use only theReverse flag to correctly associate source
1190         // and target faces in the mapper. Thus we select srcV1 so that
1191         // GetOrderedEdges() to return EDGEs in a needed order
1192         TopoDS_Face tgtFaceBis = tgtFace;
1193         TopTools_MapOfShape checkedVMap( tgtEdges.size() );
1194         checkedVMap.Add ( srcV1 );
1195         for ( vSrcExp.Next(); vSrcExp.More(); )
1196         {
1197           tgtFaceBis.Reverse();
1198           tgtEdges.clear();
1199           SMESH_Block::GetOrderedEdges( tgtFaceBis, tgtEdges, nbEdgesInWires, tgtV1 );
1200           bool ok = true;
1201           list< TopoDS_Edge >::iterator edgeS = srcEdges.begin(), edgeT = tgtEdges.begin();
1202           for ( ; edgeS != srcEdges.end() && ok ; ++edgeS, ++edgeT )
1203             ok = edgeT->IsSame( shape2ShapeMap( *edgeS, /*isSrc=*/true ));
1204           if ( ok )
1205             break; // FOUND!
1206
1207           reverse = !reverse;
1208           if ( reverse )
1209           {
1210             vSrcExp.Next();
1211             while ( vSrcExp.More() && !checkedVMap.Add( vSrcExp.Current() ))
1212               vSrcExp.Next();
1213           }
1214           else
1215           {
1216             srcV1 = TopoDS::Vertex( vSrcExp.Current() );
1217             tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
1218             srcEdges.clear();
1219             SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
1220           }
1221         }
1222       }
1223       // for the case: project to a closed face from a non-closed face w/o vertex assoc;
1224       // avoid projecting to a seam from two EDGEs with different nb nodes on them
1225       // ( test mesh_Projection_2D_01/B1 )
1226       if ( !_sourceHypo->HasVertexAssociation() &&
1227            nbEdgesInWires.front() > 2 &&
1228            helper.IsRealSeam( tgtEdges.front() ))
1229       {
1230         TopoDS_Shape srcEdge1 = shape2ShapeMap( tgtEdges.front() );
1231         list< TopoDS_Edge >::iterator srcEdge2 =
1232           std::find( srcEdges.begin(), srcEdges.end(), srcEdge1);
1233         list< TopoDS_Edge >::iterator srcEdge3 =
1234           std::find( srcEdges.begin(), srcEdges.end(), srcEdge1.Reversed());
1235         if ( srcEdge2 == srcEdges.end() || srcEdge3 == srcEdges.end() ) // srcEdge1 is not a seam
1236         {
1237           // find srcEdge2 which also will be projected to tgtEdges.front()
1238           for ( srcEdge2 = srcEdges.begin(); srcEdge2 != srcEdges.end(); ++srcEdge2 )
1239             if ( !srcEdge1.IsSame( *srcEdge2 ) &&
1240                  tgtEdges.front().IsSame( shape2ShapeMap( *srcEdge2, /*isSrc=*/true )))
1241               break;
1242           // compare nb nodes on srcEdge1 and srcEdge2
1243           if ( srcEdge2 != srcEdges.end() )
1244           {
1245             int nbN1 = 0, nbN2 = 0;
1246             if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( srcEdge1 ))
1247               nbN1 = sm->NbNodes();
1248             if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( *srcEdge2 ))
1249               nbN2 = sm->NbNodes();
1250             if ( nbN1 != nbN2 )
1251               srcV1 = helper.IthVertex( 1, srcEdges.front() );
1252           }
1253         }
1254       }
1255     }
1256     else if ( nbEdgesInWires.front() == 1 )
1257     {
1258       // TODO::Compare orientation of curves in a sole edge
1259       //RETURN_BAD_RESULT("Not implemented case");
1260     }
1261     else
1262     {
1263       RETURN_BAD_RESULT("Bad result from SMESH_Block::GetOrderedEdges()");
1264     }
1265
1266     // Load pattern from the source face
1267     SMESH_Pattern mapper;
1268     mapper.Load( srcMesh, srcFace, toProjectNodes, srcV1 );
1269     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1270       return error(COMPERR_BAD_INPUT_MESH,"Can't load mesh pattern from the source face");
1271
1272     // --------------------
1273     // Perform 2D mapping
1274     // --------------------
1275
1276     // Compute mesh on a target face
1277
1278     mapper.Apply( tgtFace, tgtV1, reverse );
1279     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK ) {
1280       // std::ofstream file("/tmp/Pattern.smp" );
1281       // mapper.Save( file );
1282       return error("Can't apply source mesh pattern to the face");
1283     }
1284
1285     // Create the mesh
1286
1287     const bool toCreatePolygons = false, toCreatePolyedrs = false;
1288     mapper.MakeMesh( tgtMesh, toCreatePolygons, toCreatePolyedrs );
1289     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1290       return error("Can't make mesh by source mesh pattern");
1291
1292     // -------------------------------------------------------------------------
1293     // mapper doesn't take care of nodes already existing on edges and vertices,
1294     // so we must merge nodes created by it with existing ones
1295     // -------------------------------------------------------------------------
1296
1297     SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
1298
1299     // Make groups of nodes to merge
1300
1301     // loop on EDGE and VERTEX sub-meshes of a target FACE
1302     SMESH_subMeshIteratorPtr smIt = tgtSubMesh->getDependsOnIterator(/*includeSelf=*/false,
1303                                                                      /*complexShapeFirst=*/false);
1304     while ( smIt->more() )
1305     {
1306       SMESH_subMesh*     sm = smIt->next();
1307       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
1308       if ( !smDS || smDS->NbNodes() == 0 )
1309         continue;
1310       //if ( !is1DComputed && sm->GetSubShape().ShapeType() == TopAbs_EDGE )
1311       //  break;
1312
1313       if ( helper.IsDegenShape( sm->GetId() ) ) // to merge all nodes on degenerated
1314       {
1315         if ( sm->GetSubShape().ShapeType() == TopAbs_EDGE )
1316         {
1317           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1318           SMESH_subMeshIteratorPtr smDegenIt
1319             = sm->getDependsOnIterator(/*includeSelf=*/true,/*complexShapeFirst=*/false);
1320           while ( smDegenIt->more() )
1321             if (( smDS = smDegenIt->next()->GetSubMeshDS() ))
1322             {
1323               SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1324               while ( nIt->more() )
1325                 groupsOfNodes.back().push_back( nIt->next() );
1326             }
1327         }
1328         continue; // do not treat sm of degen VERTEX
1329       }
1330
1331       // Sort new and old nodes of a submesh separately
1332
1333       bool isSeam = helper.IsRealSeam( sm->GetId() );
1334
1335       enum { NEW_NODES = 0, OLD_NODES };
1336       map< double, const SMDS_MeshNode* > u2nodesMaps[2], u2nodesOnSeam;
1337       map< double, const SMDS_MeshNode* >::iterator u_oldNode, u_newNode, u_newOnSeam, newEnd;
1338       set< const SMDS_MeshNode* > seamNodes;
1339
1340       // mapper changed, no more "mapper puts on a seam edge nodes from 2 edges"
1341       if ( isSeam && ! getBoundaryNodes ( sm, tgtFace, u2nodesOnSeam, seamNodes ))
1342         ;//RETURN_BAD_RESULT("getBoundaryNodes() failed");
1343
1344       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1345       while ( nIt->more() )
1346       {
1347         const SMDS_MeshNode* node = nIt->next();
1348         bool isOld = isOldNode( node );
1349
1350         if ( !isOld && isSeam ) { // new node on a seam edge
1351           if ( seamNodes.count( node ) )
1352             continue; // node is already in the map
1353         }
1354
1355         // sort nodes on edges by their position
1356         map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[isOld ? OLD_NODES : NEW_NODES];
1357         switch ( node->GetPosition()->GetTypeOfPosition() )
1358         {
1359         case  SMDS_TOP_VERTEX: {
1360           if ( !is1DComputed && !pos2nodes.empty() )
1361             u2nodesMaps[isOld ? NEW_NODES : OLD_NODES].insert( make_pair( 0, node ));
1362           else
1363             pos2nodes.insert( make_pair( 0, node ));
1364           break;
1365         }
1366         case  SMDS_TOP_EDGE:   {
1367           const SMDS_EdgePosition* pos =
1368             static_cast<const SMDS_EdgePosition*>(node->GetPosition());
1369           pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
1370           break;
1371         }
1372         default:
1373           RETURN_BAD_RESULT("Wrong node position type: "<<
1374                             node->GetPosition()->GetTypeOfPosition());
1375         }
1376       }
1377       const bool mergeNewToOld =
1378         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesMaps[ OLD_NODES ].size() );
1379       const bool mergeSeamToNew =
1380         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesOnSeam.size() );
1381
1382       if ( !mergeNewToOld )
1383         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1384              u2nodesMaps[ OLD_NODES ].size() > 0 )
1385         {
1386           u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1387           newEnd    = u2nodesMaps[ OLD_NODES ].end();
1388           for ( ; u_oldNode != newEnd; ++u_oldNode )
1389             SMESH_Algo::addBadInputElement( u_oldNode->second );
1390           return error( COMPERR_BAD_INPUT_MESH,
1391                         SMESH_Comment( "Existing mesh mismatches the projected 2D mesh on " )
1392                         << ( sm->GetSubShape().ShapeType() == TopAbs_EDGE ? "edge" : "vertex" )
1393                         << " #" << sm->GetId() );
1394         }
1395       if ( isSeam && !mergeSeamToNew ) {
1396         const TopoDS_Shape& seam = sm->GetSubShape();
1397         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1398              u2nodesOnSeam.size()            > 0 &&
1399              seam.ShapeType() == TopAbs_EDGE )
1400         {
1401           int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1402           int nbE2 = helper.Count( srcFace, TopAbs_EDGE, /*ignoreSame=*/true );
1403           if ( nbE1 != nbE2 ) // 2 EDGEs are mapped to a seam EDGE
1404           {
1405             // find the 2 EDGEs of srcFace
1406             TopTools_DataMapIteratorOfDataMapOfShapeShape src2tgtIt( shape2ShapeMap._map2to1 );
1407             for ( ; src2tgtIt.More(); src2tgtIt.Next() )
1408               if ( seam.IsSame( src2tgtIt.Value() ))
1409                 SMESH_Algo::addBadInputElements
1410                   ( srcMesh->GetMeshDS()->MeshElements( src2tgtIt.Key() ));
1411             return error( COMPERR_BAD_INPUT_MESH,
1412                           "Different number of nodes on two edges projected to a seam edge" );
1413           }
1414         }
1415       }
1416
1417       // Make groups of nodes to merge
1418
1419       u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1420       u_newNode = u2nodesMaps[ NEW_NODES ].begin();
1421       newEnd    = u2nodesMaps[ NEW_NODES ].end();
1422       u_newOnSeam = u2nodesOnSeam.begin();
1423       if ( mergeNewToOld )
1424         for ( ; u_newNode != newEnd; ++u_newNode, ++u_oldNode )
1425         {
1426           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1427           groupsOfNodes.back().push_back( u_oldNode->second );
1428           groupsOfNodes.back().push_back( u_newNode->second );
1429           if ( mergeSeamToNew )
1430             groupsOfNodes.back().push_back( (u_newOnSeam++)->second );
1431         }
1432       else if ( mergeSeamToNew )
1433         for ( ; u_newNode != newEnd; ++u_newNode, ++u_newOnSeam )
1434         {
1435           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1436           groupsOfNodes.back().push_back( u_newNode->second );
1437           groupsOfNodes.back().push_back( u_newOnSeam->second );
1438         }
1439
1440     } // loop on EDGE and VERTEX submeshes of a target FACE
1441
1442     // Merge
1443
1444     SMESH_MeshEditor editor( tgtMesh );
1445     int nbFaceBeforeMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1446     editor.MergeNodes( groupsOfNodes );
1447     int nbFaceAtferMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1448     if ( nbFaceBeforeMerge != nbFaceAtferMerge && !helper.HasDegeneratedEdges() )
1449       return error(COMPERR_BAD_INPUT_MESH, "Probably invalid node parameters on geom faces");
1450
1451     // ----------------------------------------------------------------
1452     // The mapper can't create quadratic elements, so convert if needed
1453     // ----------------------------------------------------------------
1454
1455     faceIt         = srcSubMesh->GetSubMeshDS()->GetElements();
1456     bool srcIsQuad = faceIt->next()->IsQuadratic();
1457     faceIt         = tgtSubMesh->GetSubMeshDS()->GetElements();
1458     bool tgtIsQuad = faceIt->next()->IsQuadratic();
1459     if ( srcIsQuad && !tgtIsQuad )
1460     {
1461       TIDSortedElemSet tgtFaces;
1462       faceIt = tgtSubMesh->GetSubMeshDS()->GetElements();
1463       while ( faceIt->more() )
1464         tgtFaces.insert( tgtFaces.end(), faceIt->next() );
1465
1466       editor.ConvertToQuadratic(/*theForce3d=*/false, tgtFaces, false);
1467     }
1468
1469   } // end of projection using Pattern mapping
1470
1471
1472   if ( !projDone || is1DComputed )
1473     // ----------------------------------------------------------------
1474     // The mapper can create distorted faces by placing nodes out of the FACE
1475     // boundary, also bad face can be created if EDGEs already discretized
1476     // --> fix bad faces by smoothing
1477     // ----------------------------------------------------------------
1478     if ( !fixDistortedFaces( helper, tgtWires ))
1479       return error("Invalid mesh generated");
1480
1481   // ---------------------------
1482   // Check elements orientation
1483   // ---------------------------
1484
1485   TopoDS_Face face = TopoDS::Face( theShape );
1486   if ( !theMesh.IsMainShape( tgtFace ))
1487   {
1488     // find the main shape
1489     TopoDS_Shape mainShape = meshDS->ShapeToMesh();
1490     switch ( mainShape.ShapeType() ) {
1491     case TopAbs_SHELL:
1492     case TopAbs_SOLID: break;
1493     default:
1494       TopTools_ListIteratorOfListOfShape ancestIt = theMesh.GetAncestors( face );
1495       for ( ; ancestIt.More(); ancestIt.Next() ) {
1496         TopAbs_ShapeEnum type = ancestIt.Value().ShapeType();
1497         if ( type == TopAbs_SOLID ) {
1498           mainShape = ancestIt.Value();
1499           break;
1500         } else if ( type == TopAbs_SHELL ) {
1501           mainShape = ancestIt.Value();
1502         }
1503       }
1504     }
1505     // find tgtFace in the main solid or shell to know it's true orientation.
1506     TopExp_Explorer exp( mainShape, TopAbs_FACE );
1507     for ( ; exp.More(); exp.Next() ) {
1508       if ( tgtFace.IsSame( exp.Current() )) {
1509         face = TopoDS::Face( exp.Current() );
1510         break;
1511       }
1512     }
1513   }
1514   // Fix orientation
1515   if ( helper.IsReversedSubMesh( face ))
1516   {
1517     SMESH_MeshEditor editor( tgtMesh );
1518     SMDS_ElemIteratorPtr eIt = meshDS->MeshElements( face )->GetElements();
1519     while ( eIt->more() ) {
1520       const SMDS_MeshElement* e = eIt->next();
1521       if ( e->GetType() == SMDSAbs_Face && !editor.Reorient( e ))
1522         RETURN_BAD_RESULT("Pb of SMESH_MeshEditor::Reorient()");
1523     }
1524   }
1525
1526   cleaner.Release(); // not to remove mesh
1527
1528   return true;
1529 }
1530
1531
1532 //=======================================================================
1533 //function : Evaluate
1534 //purpose  : 
1535 //=======================================================================
1536
1537 bool StdMeshers_Projection_2D::Evaluate(SMESH_Mesh&         theMesh,
1538                                         const TopoDS_Shape& theShape,
1539                                         MapShapeNbElems&    aResMap)
1540 {
1541   if ( !_sourceHypo )
1542     return false;
1543
1544   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1545   SMESH_Mesh * tgtMesh = & theMesh;
1546   if ( !srcMesh )
1547     srcMesh = tgtMesh;
1548
1549   // ---------------------------
1550   // Make sub-shapes association
1551   // ---------------------------
1552
1553   TopoDS_Face tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
1554   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
1555
1556   TAssocTool::TShapeShapeMap shape2ShapeMap;
1557   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
1558   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
1559                                              shape2ShapeMap)  ||
1560        !shape2ShapeMap.IsBound( tgtFace ))
1561     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
1562
1563   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
1564
1565   // -------------------------------------------------------
1566   // Assure that mesh on a source Face is computed/evaluated
1567   // -------------------------------------------------------
1568
1569   std::vector<int> aVec;
1570
1571   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
1572   if ( srcSubMesh->IsMeshComputed() )
1573   {
1574     aVec.resize( SMDSEntity_Last, 0 );
1575     aVec[SMDSEntity_Node] = srcSubMesh->GetSubMeshDS()->NbNodes();
1576
1577     SMDS_ElemIteratorPtr elemIt = srcSubMesh->GetSubMeshDS()->GetElements();
1578     while ( elemIt->more() )
1579       aVec[ elemIt->next()->GetEntityType() ]++;
1580   }
1581   else
1582   {
1583     MapShapeNbElems  tmpResMap;
1584     MapShapeNbElems& srcResMap = (srcMesh == tgtMesh) ? aResMap : tmpResMap;
1585     if ( !_gen->Evaluate( *srcMesh, srcShape, srcResMap ))
1586       return error(COMPERR_BAD_INPUT_MESH,"Source mesh not evaluatable");
1587     aVec = srcResMap[ srcSubMesh ];
1588     if ( aVec.empty() )
1589       return error(COMPERR_BAD_INPUT_MESH,"Source mesh is wrongly evaluated");
1590   }
1591
1592   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1593   aResMap.insert(std::make_pair(sm,aVec));
1594
1595   return true;
1596 }
1597
1598
1599 //=============================================================================
1600 /*!
1601  * \brief Sets a default event listener to submesh of the source face
1602   * \param subMesh - submesh where algo is set
1603  *
1604  * This method is called when a submesh gets HYP_OK algo_state.
1605  * After being set, event listener is notified on each event of a submesh.
1606  * Arranges that CLEAN event is translated from source submesh to
1607  * the submesh
1608  */
1609 //=============================================================================
1610
1611 void StdMeshers_Projection_2D::SetEventListener(SMESH_subMesh* subMesh)
1612 {
1613   TAssocTool::SetEventListener( subMesh,
1614                                 _sourceHypo->GetSourceFace(),
1615                                 _sourceHypo->GetSourceMesh() );
1616 }