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