Salome HOME
Merge from V5_1_4_BR 07/05/2010
[modules/smesh.git] / src / StdMeshers / StdMeshers_ProjectionUtils.cxx
1 //  Copyright (C) 2007-2010  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.
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 : idl implementation based on 'SMESH' unit's calsses
24 // File      : StdMeshers_ProjectionUtils.cxx
25 // Created   : Fri Oct 27 10:24:28 2006
26 // Author    : Edward AGAPOV (eap)
27 //
28 #include "StdMeshers_ProjectionUtils.hxx"
29
30 #include "StdMeshers_ProjectionSource1D.hxx"
31 #include "StdMeshers_ProjectionSource2D.hxx"
32 #include "StdMeshers_ProjectionSource3D.hxx"
33
34 #include "SMESH_Algo.hxx"
35 #include "SMESH_Block.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Hypothesis.hxx"
38 #include "SMESH_IndexedDataMapOfShapeIndexedMapOfShape.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MesherHelper.hxx"
41 #include "SMESH_subMesh.hxx"
42 #include "SMESH_subMeshEventListener.hxx"
43 #include "SMDS_EdgePosition.hxx"
44
45 #include "utilities.h"
46
47 #include <BRepTools.hxx>
48 #include <BRepTools_WireExplorer.hxx>
49 #include <BRep_Builder.hxx>
50 #include <BRep_Tool.hxx>
51 #include <Bnd_Box.hxx>
52 #include <TopAbs.hxx>
53 #include <TopExp.hxx>
54 #include <TopExp_Explorer.hxx>
55 #include <TopTools_Array1OfShape.hxx>
56 #include <TopTools_ListIteratorOfListOfShape.hxx>
57 #include <TopTools_ListOfShape.hxx>
58 #include <TopTools_MapOfShape.hxx>
59 #include <TopoDS.hxx>
60 #include <TopoDS_Compound.hxx>
61 #include <TopoDS_Shape.hxx>
62 #include <gp_Pnt.hxx>
63 #include <gp_Vec.hxx>
64 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
65 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
66
67 using namespace std;
68
69
70 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
71 #define CONT_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); continue; }
72 #define SHOW_VERTEX(v,msg) \
73 // { \
74 //  if ( (v).IsNull() ) cout << msg << " NULL SHAPE" << endl; \
75 // else if ((v).ShapeType() == TopAbs_VERTEX) {\
76 //   gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( (v) ));\
77 //   cout<<msg<<" "<<(v).TShape().operator->()<<" ( "<<p.X()<<", "<<p.Y()<<", "<<p.Z()<<" )"<<endl;}\
78 // else {\
79 // cout << msg << " "; TopAbs::Print((v).ShapeType(),cout) <<" "<<(v).TShape().operator->()<<endl;}\
80 // }
81 #define SHOW_LIST(msg,l) \
82 // { \
83 //     cout << msg << " ";\
84 //     list< TopoDS_Edge >::const_iterator e = l.begin();\
85 //     for ( int i = 0; e != l.end(); ++e, ++i ) {\
86 //       cout << i << "V (" << TopExp::FirstVertex( *e, true ).TShape().operator->() << ") "\
87 //            << i << "E (" << e->TShape().operator->() << "); "; }\
88 //     cout << endl;\
89 //   }
90
91 #define HERE StdMeshers_ProjectionUtils
92
93 namespace {
94
95   //================================================================================
96   /*!
97    * \brief Write shape for debug purposes
98    */
99   //================================================================================
100
101   bool _StoreBadShape(const TopoDS_Shape& shape)
102   {
103 #ifdef _DEBUG_
104     const char* type[] ={"COMPOUND","COMPSOLID","SOLID","SHELL","FACE","WIRE","EDGE","VERTEX"};
105     BRepTools::Write( shape, SMESH_Comment("/tmp/") << type[shape.ShapeType()] << "_"
106                       << shape.TShape().operator->() << ".brep");
107 #endif
108     return false;
109   }
110   
111   //================================================================================
112   /*!
113    * \brief Reverse order of edges in a list and their orientation
114     * \param edges - list of edges to reverse
115     * \param nbEdges - number of edges to reverse
116    */
117   //================================================================================
118
119   void Reverse( list< TopoDS_Edge > & edges, const int nbEdges )
120   {
121     SHOW_LIST("BEFORE REVERSE", edges);
122
123     list< TopoDS_Edge >::iterator eIt = edges.begin();
124     if ( edges.size() == nbEdges )
125     {
126       edges.reverse();
127     }
128     else  // reverse only the given nb of edges
129     {
130       // look for the last edge to be reversed
131       list< TopoDS_Edge >::iterator eBackIt = edges.begin();
132       for ( int i = 1; i < nbEdges; ++i )
133         ++eBackIt;
134       // reverse
135       while ( eIt != eBackIt ) {
136         std::swap( *eIt, *eBackIt );
137         SHOW_LIST("# AFTER SWAP", edges)
138         if ( (++eIt) != eBackIt )
139           --eBackIt;
140       }
141     }
142     for ( eIt = edges.begin(); eIt != edges.end(); ++eIt )
143       eIt->Reverse();
144     SHOW_LIST("ATFER REVERSE", edges)
145   }
146
147   //================================================================================
148   /*!
149    * \brief Check if propagation is possible
150     * \param theMesh1 - source mesh
151     * \param theMesh2 - target mesh
152     * \retval bool - true if possible
153    */
154   //================================================================================
155
156   bool IsPropagationPossible( SMESH_Mesh* theMesh1, SMESH_Mesh* theMesh2 )
157   {
158     if ( theMesh1 != theMesh2 ) {
159       TopoDS_Shape mainShape1 = theMesh1->GetMeshDS()->ShapeToMesh();
160       TopoDS_Shape mainShape2 = theMesh2->GetMeshDS()->ShapeToMesh();
161       return mainShape1.IsSame( mainShape2 );
162     }
163     return true;
164   }
165
166   //================================================================================
167   /*!
168    * \brief Fix up association of edges in faces by possible propagation
169     * \param nbEdges - nb of edges in an outer wire
170     * \param edges1 - edges of one face
171     * \param edges2 - matching edges of another face
172     * \param theMesh1 - mesh 1
173     * \param theMesh2 - mesh 2
174     * \retval bool - true if association was fixed
175    */
176   //================================================================================
177
178   bool FixAssocByPropagation( const int             nbEdges,
179                               list< TopoDS_Edge > & edges1,
180                               list< TopoDS_Edge > & edges2,
181                               SMESH_Mesh*           theMesh1,
182                               SMESH_Mesh*           theMesh2)
183   {
184     if ( nbEdges == 2 && IsPropagationPossible( theMesh1, theMesh2 ) )
185     {
186       list< TopoDS_Edge >::iterator eIt2 = ++edges2.begin(); // 2nd edge of the 2nd face
187       TopoDS_Edge edge2 = HERE::GetPropagationEdge( theMesh1, *eIt2, edges1.front() ).second;
188       if ( !edge2.IsNull() ) { // propagation found for the second edge
189         Reverse( edges2, nbEdges );
190         return true;
191       }
192     }
193     return false;
194   }
195
196   //================================================================================
197   /*!
198    * \brief Look for a group containing a target shape and similar to a source group
199     * \param tgtShape - target edge or face
200     * \param tgtMesh1 - target mesh
201     * \param srcGroup - source group
202     * \retval TopoDS_Shape - found target group
203    */
204   //================================================================================
205
206   TopoDS_Shape FindGroupContaining(const TopoDS_Shape& tgtShape,
207                                    const SMESH_Mesh*   tgtMesh1,
208                                    const TopoDS_Shape& srcGroup)
209   {
210     list<SMESH_subMesh*> subMeshes = tgtMesh1->GetGroupSubMeshesContaining(tgtShape);
211     list<SMESH_subMesh*>::iterator sm = subMeshes.begin();
212     int type, last = TopAbs_SHAPE;
213     StdMeshers_ProjectionUtils util;
214     for ( ; sm != subMeshes.end(); ++sm ) {
215       const TopoDS_Shape & group = (*sm)->GetSubShape();
216       // check if group is similar to srcGroup
217       for ( type = srcGroup.ShapeType(); type < last; ++type)
218         if ( util.Count( srcGroup, (TopAbs_ShapeEnum)type, 0) !=
219              util.Count( group,    (TopAbs_ShapeEnum)type, 0))
220           break;
221       if ( type == last )
222         return group;
223     }
224     return TopoDS_Shape();
225   }
226
227   //================================================================================
228   /*!
229    * \brief Find association of groups at top and bottom of prism
230    */
231   //================================================================================
232
233   bool AssocGroupsByPropagation(const TopoDS_Shape&   theGroup1,
234                                 const TopoDS_Shape&   theGroup2,
235                                 SMESH_Mesh&           theMesh,
236                                 HERE::TShapeShapeMap& theMap)
237   {
238     // If groups are on top and bottom of prism then we can associate
239     // them using "vertical" (or "side") edges and faces of prism since
240     // they connect corresponding vertices and edges of groups.
241
242     TopTools_IndexedMapOfShape subshapes1, subshapes2;
243     TopExp::MapShapes( theGroup1, subshapes1 );
244     TopExp::MapShapes( theGroup2, subshapes2 );
245     TopTools_ListIteratorOfListOfShape ancestIt;
246
247     // Iterate on vertices of group1 to find corresponding vertices in group2
248     // and associate adjacent edges and faces
249
250     TopTools_MapOfShape verticShapes;
251     TopExp_Explorer vExp1( theGroup1, TopAbs_VERTEX );
252     for ( ; vExp1.More(); vExp1.Next() )
253     {
254       const TopoDS_Vertex& v1 = TopoDS::Vertex( vExp1.Current() );
255       if ( theMap.IsBound( v1 )) continue; // already processed
256
257       // Find "vertical" edge ending in v1 and whose other vertex belongs to group2
258       TopoDS_Shape verticEdge, v2;
259       ancestIt.Initialize( theMesh.GetAncestors( v1 ));
260       for ( ; verticEdge.IsNull() && ancestIt.More(); ancestIt.Next() )
261       {
262         if ( ancestIt.Value().ShapeType() != TopAbs_EDGE ) continue;
263         v2 = HERE::GetNextVertex( TopoDS::Edge( ancestIt.Value() ), v1 );
264         if ( subshapes2.Contains( v2 ))
265           verticEdge = ancestIt.Value();
266       }
267       if ( verticEdge.IsNull() )
268         return false;
269
270       HERE::InsertAssociation( v1, v2, theMap);
271
272       // Associate edges by vertical faces sharing the found vertical edge
273       ancestIt.Initialize( theMesh.GetAncestors( verticEdge ) );
274       for ( ; ancestIt.More(); ancestIt.Next() )
275       {
276         if ( ancestIt.Value().ShapeType() != TopAbs_FACE ) continue;
277         if ( !verticShapes.Add( ancestIt.Value() )) continue;
278         const TopoDS_Face& face = TopoDS::Face( ancestIt.Value() );
279
280         // get edges of the face
281         TopoDS_Edge edgeGr1, edgeGr2, verticEdge2;
282         list< TopoDS_Edge > edges;    list< int > nbEdgesInWire;
283         SMESH_Block::GetOrderedEdges( face, v1, edges, nbEdgesInWire);
284         if ( nbEdgesInWire.front() != 4 )
285           return _StoreBadShape( face );
286         list< TopoDS_Edge >::iterator edge = edges.begin();
287         if ( verticEdge.IsSame( *edge )) {
288           edgeGr2     = *(++edge);
289           verticEdge2 = *(++edge);
290           edgeGr1     = *(++edge);
291         } else {
292           edgeGr1     = *(edge++);
293           verticEdge2 = *(edge++);
294           edgeGr2     = *(edge++);
295         }
296
297         HERE::InsertAssociation( edgeGr1, edgeGr2.Reversed(), theMap);
298       }
299     }
300
301     // Associate faces
302     TopoDS_Iterator gr1It( theGroup1 );
303     if ( gr1It.Value().ShapeType() == TopAbs_FACE )
304     {
305       // find a boundary edge of group1 to start from
306       TopoDS_Shape bndEdge;
307       TopExp_Explorer edgeExp1( theGroup1, TopAbs_EDGE );
308       for ( ; bndEdge.IsNull() && edgeExp1.More(); edgeExp1.Next())
309         if ( HERE::IsBoundaryEdge( TopoDS::Edge( edgeExp1.Current()), theGroup1, theMesh ))
310           bndEdge = edgeExp1.Current();
311       if ( bndEdge.IsNull() )
312         return false;
313
314       list< TopoDS_Shape > edges(1, bndEdge);
315       list< TopoDS_Shape >::iterator edge1 = edges.begin();
316       for ( ; edge1 != edges.end(); ++edge1 )
317       {
318         // there must be one or zero not associated faces between ancestors of edge
319         // belonging to theGroup1
320         TopoDS_Shape face1;
321         ancestIt.Initialize( theMesh.GetAncestors( *edge1 ) );
322         for ( ; ancestIt.More() && face1.IsNull(); ancestIt.Next() ) {
323           if ( ancestIt.Value().ShapeType() == TopAbs_FACE &&
324                !theMap.IsBound( ancestIt.Value() ) &&
325                subshapes1.Contains( ancestIt.Value() ))
326             face1 = ancestIt.Value();
327
328           // add edges of face1 to start searching for adjacent faces from
329           for ( TopExp_Explorer e(face1, TopAbs_EDGE); e.More(); e.Next())
330             if ( !edge1->IsSame( e.Current() ))
331               edges.push_back( e.Current() );
332         }
333         if ( !face1.IsNull() ) {
334           // find the corresponding face of theGroup2
335           TopoDS_Shape edge2 = theMap( *edge1 );
336           TopoDS_Shape face2;
337           ancestIt.Initialize( theMesh.GetAncestors( edge2 ) );
338           for ( ; ancestIt.More() && face2.IsNull(); ancestIt.Next() ) {
339             if ( ancestIt.Value().ShapeType() == TopAbs_FACE &&
340                  !theMap.IsBound( ancestIt.Value() ) &&
341                  subshapes2.Contains( ancestIt.Value() ))
342               face2 = ancestIt.Value();
343           }
344           if ( face2.IsNull() )
345             return false;
346
347           HERE::InsertAssociation( face1, face2, theMap);
348         }
349       }
350     }
351     return true;
352   }
353
354 } // namespace
355
356 //=======================================================================
357 /*!
358  * \brief Looks for association of all subshapes of two shapes
359  * \param theShape1 - shape 1
360  * \param theMesh1 - mesh built on shape 1
361  * \param theShape2 - shape 2
362  * \param theMesh2 - mesh built on shape 2
363  * \param theAssociation - association map to be filled that may
364  *                         contain association of one or two pairs of vertices
365  * \retval bool - true if association found
366  */
367 //=======================================================================
368
369 bool StdMeshers_ProjectionUtils::FindSubShapeAssociation(const TopoDS_Shape& theShape1,
370                                                          SMESH_Mesh*         theMesh1,
371                                                          const TopoDS_Shape& theShape2,
372                                                          SMESH_Mesh*         theMesh2,
373                                                          TShapeShapeMap &    theMap)
374 {
375   // Structure of this long function is following
376   // 1) Group->group projection: theShape1 is a group member,
377   //    theShape2 is a group. We find a group theShape1 is in and recall self.
378   // 2) Accosiate same shapes with different location (partners).
379   // 3) If vertex association is given, perform accosiation according to shape type:
380   //       switch ( ShapeType ) {
381   //         case TopAbs_EDGE:
382   //         case ...:
383   //       }
384   //    else try to accosiate in different ways:
385   //       a) accosiate shapes by propagation and other simple cases
386   //            switch ( ShapeType ) {
387   //            case TopAbs_EDGE:
388   //            case ...:
389   //            }
390   //       b) find association of a couple of vertices and recall self.
391   //
392
393   // =================================================================================
394   // Is it the case of associating a group member -> another group? (PAL16202, 16203)
395   // =================================================================================
396   if ( theShape1.ShapeType() != theShape2.ShapeType() ) {
397     TopoDS_Shape group1, group2;
398     if ( theShape1.ShapeType() == TopAbs_COMPOUND ) {
399       group1 = theShape1;
400       group2 = FindGroupContaining( theShape2, theMesh2, group1 );
401     }
402     else if ( theShape2.ShapeType() == TopAbs_COMPOUND ) {
403       group2 = theShape2;
404       group1 = FindGroupContaining( theShape1, theMesh1, group2 );
405     }
406     if ( group1.IsNull() || group2.IsNull() )
407       RETURN_BAD_RESULT("Different shape types");
408     // Associate compounds
409     return FindSubShapeAssociation(group1, theMesh1, group2, theMesh2, theMap );
410   }
411
412   bool bidirect = ( !theShape1.IsSame( theShape2 ));
413
414   // ============
415   // Is partner?
416   // ============
417   bool partner = theShape1.IsPartner( theShape2 );
418   TopTools_DataMapIteratorOfDataMapOfShapeShape vvIt( theMap );
419   for ( ; partner && vvIt.More(); vvIt.Next() )
420     partner = vvIt.Key().IsPartner( vvIt.Value() );
421
422   if ( partner ) // Same shape with different location
423   {
424     // recursively associate all subshapes of theShape1 and theShape2
425     typedef list< pair< TopoDS_Shape, TopoDS_Shape > > TShapePairsList;
426     TShapePairsList shapesQueue( 1, make_pair( theShape1, theShape2 ));
427     TShapePairsList::iterator s1_s2 = shapesQueue.begin();
428     for ( ; s1_s2 != shapesQueue.end(); ++s1_s2 )
429     {
430       InsertAssociation( s1_s2->first, s1_s2->second, theMap, bidirect);
431       TopoDS_Iterator s1It( s1_s2->first), s2It( s1_s2->second );
432       for ( ; s1It.More(); s1It.Next(), s2It.Next() )
433         shapesQueue.push_back( make_pair( s1It.Value(), s2It.Value() ));
434     }
435     return true;
436   }
437
438   if ( !theMap.IsEmpty() )
439   {
440     //======================================================================
441     // HAS initial vertex association
442     //======================================================================
443     switch ( theShape1.ShapeType() ) {
444       // ----------------------------------------------------------------------
445     case TopAbs_EDGE: { // TopAbs_EDGE
446       // ----------------------------------------------------------------------
447       if ( theMap.Extent() != 2 )
448         RETURN_BAD_RESULT("Wrong map extent " << theMap.Extent() );
449       TopoDS_Edge edge1 = TopoDS::Edge( theShape1 );
450       TopoDS_Edge edge2 = TopoDS::Edge( theShape2 );
451       TopoDS_Vertex VV1[2], VV2[2];
452       TopExp::Vertices( edge1, VV1[0], VV1[1] );
453       TopExp::Vertices( edge2, VV2[0], VV2[1] );
454       int i1 = 0, i2 = 0;
455       if ( theMap.IsBound( VV1[ i1 ] )) i1 = 1;
456       if ( theMap.IsBound( VV2[ i2 ] )) i2 = 1;
457       InsertAssociation( VV1[ i1 ], VV2[ i2 ], theMap, bidirect);
458       InsertAssociation( theShape1, theShape2, theMap, bidirect );
459       return true;
460     }
461       // ----------------------------------------------------------------------
462     case TopAbs_FACE: { // TopAbs_FACE
463       // ----------------------------------------------------------------------
464       TopoDS_Face face1 = TopoDS::Face( theShape1 );
465       TopoDS_Face face2 = TopoDS::Face( theShape2 );
466
467       TopoDS_Vertex VV1[2], VV2[2];
468       // find a not closed edge of face1 both vertices of which are associated
469       int nbEdges = 0;
470       TopExp_Explorer exp ( face1, TopAbs_EDGE );
471       for ( ; VV2[ 1 ].IsNull() && exp.More(); exp.Next(), ++nbEdges ) {
472         TopExp::Vertices( TopoDS::Edge( exp.Current() ), VV1[0], VV1[1] );
473         if ( theMap.IsBound( VV1[0] ) ) {
474           VV2[ 0 ] = TopoDS::Vertex( theMap( VV1[0] ));
475           if ( theMap.IsBound( VV1[1] ) && !VV1[0].IsSame( VV1[1] ))
476             VV2[ 1 ] = TopoDS::Vertex( theMap( VV1[1] ));
477         }
478       }
479       if ( VV2[ 1 ].IsNull() ) { // 2 bound vertices not found
480         if ( nbEdges > 1 ) {
481           RETURN_BAD_RESULT("2 bound vertices not found" );
482         } else {
483           VV2[ 1 ] = VV2[ 0 ];
484         }
485       }
486       list< TopoDS_Edge > edges1, edges2;
487       int nbE = FindFaceAssociation( face1, VV1, face2, VV2, edges1, edges2 );
488       if ( !nbE ) RETURN_BAD_RESULT("FindFaceAssociation() failed");
489       FixAssocByPropagation( nbE, edges1, edges2, theMesh1, theMesh2 );
490
491       list< TopoDS_Edge >::iterator eIt1 = edges1.begin();
492       list< TopoDS_Edge >::iterator eIt2 = edges2.begin();
493       for ( ; eIt1 != edges1.end(); ++eIt1, ++eIt2 )
494       {
495         InsertAssociation( *eIt1, *eIt2, theMap, bidirect);
496         VV1[0] = TopExp::FirstVertex( *eIt1, true );
497         VV2[0] = TopExp::FirstVertex( *eIt2, true );
498         InsertAssociation( VV1[0], VV2[0], theMap, bidirect);
499       }
500       InsertAssociation( theShape1, theShape2, theMap, bidirect );
501       return true;
502     }
503       // ----------------------------------------------------------------------
504     case TopAbs_SHELL: // TopAbs_SHELL, TopAbs_SOLID
505     case TopAbs_SOLID: {
506       // ----------------------------------------------------------------------
507       TopoDS_Vertex VV1[2], VV2[2];
508       // try to find a not closed edge of shape1 both vertices of which are associated
509       TopoDS_Edge edge1;
510       TopExp_Explorer exp ( theShape1, TopAbs_EDGE );
511       for ( ; VV2[ 1 ].IsNull() && exp.More(); exp.Next() ) {
512         edge1 = TopoDS::Edge( exp.Current() );
513         TopExp::Vertices( edge1 , VV1[0], VV1[1] );
514         if ( theMap.IsBound( VV1[0] )) {
515           VV2[ 0 ] = TopoDS::Vertex( theMap( VV1[0] ));
516           if ( theMap.IsBound( VV1[1] ) && !VV1[0].IsSame( VV1[1] ))
517             VV2[ 1 ] = TopoDS::Vertex( theMap( VV1[1] ));
518         }
519       }
520       if ( VV2[ 1 ].IsNull() ) // 2 bound vertices not found
521         RETURN_BAD_RESULT("2 bound vertices not found" );
522       // get an edge2 of theShape2 corresponding to edge1
523       TopoDS_Edge edge2 = GetEdgeByVertices( theMesh2, VV2[ 0 ], VV2[ 1 ]);
524       if ( edge2.IsNull() )
525         RETURN_BAD_RESULT("GetEdgeByVertices() failed");
526
527       // build map of edge to faces if shapes are not subshapes of main ones
528       bool isSubOfMain = false;
529       if ( SMESHDS_SubMesh * sm = theMesh1->GetMeshDS()->MeshElements( theShape1 ))
530         isSubOfMain = !sm->IsComplexSubmesh();
531       else
532         isSubOfMain = theMesh1->GetMeshDS()->ShapeToIndex( theShape1 );
533       TAncestorMap e2f1, e2f2;
534       const TAncestorMap& edgeToFace1 = isSubOfMain ? theMesh1->GetAncestorMap() : e2f1;
535       const TAncestorMap& edgeToFace2 = isSubOfMain ? theMesh2->GetAncestorMap() : e2f2;
536       if (!isSubOfMain) {
537         TopExp::MapShapesAndAncestors( theShape1, TopAbs_EDGE, TopAbs_FACE, e2f1 );
538         TopExp::MapShapesAndAncestors( theShape2, TopAbs_EDGE, TopAbs_FACE, e2f2 );
539         if ( !edgeToFace1.Contains( edge1 ))
540           RETURN_BAD_RESULT("edge1 does not belong to theShape1");
541         if ( !edgeToFace2.Contains( edge2 ))
542           RETURN_BAD_RESULT("edge2 does not belong to theShape2");
543       }
544       //
545       // Look for 2 corresponing faces:
546       //
547       TopoDS_Shape F1, F2;
548
549       // get a face sharing edge1 (F1)
550       TopoDS_Shape FF2[2];
551       TopTools_ListIteratorOfListOfShape ancestIt1( edgeToFace1.FindFromKey( edge1 ));
552       for ( ; F1.IsNull() && ancestIt1.More(); ancestIt1.Next() )
553         if ( ancestIt1.Value().ShapeType() == TopAbs_FACE )
554           F1 = ancestIt1.Value().Oriented( TopAbs_FORWARD );
555       if ( F1.IsNull() )
556         RETURN_BAD_RESULT(" Face1 not found");
557
558       // get 2 faces sharing edge2 (one of them is F2)
559       TopTools_ListIteratorOfListOfShape ancestIt2( edgeToFace2.FindFromKey( edge2 ));
560       for ( int i = 0; FF2[1].IsNull() && ancestIt2.More(); ancestIt2.Next() )
561         if ( ancestIt2.Value().ShapeType() == TopAbs_FACE )
562           FF2[ i++ ] = ancestIt2.Value().Oriented( TopAbs_FORWARD );
563
564       // get oriented edge1 and edge2 from F1 and FF2[0]
565       for ( exp.Init( F1, TopAbs_EDGE ); exp.More(); exp.Next() )
566         if ( edge1.IsSame( exp.Current() )) {
567           edge1 = TopoDS::Edge( exp.Current() );
568           break;
569         }
570       for ( exp.Init( FF2[ 0 ], TopAbs_EDGE ); exp.More(); exp.Next() )
571         if ( edge2.IsSame( exp.Current() )) {
572           edge2 = TopoDS::Edge( exp.Current() );
573           break;
574         }
575
576       // compare first vertices of edge1 and edge2
577       TopExp::Vertices( edge1, VV1[0], VV1[1], true );
578       TopExp::Vertices( edge2, VV2[0], VV2[1], true );
579       F2 = FF2[ 0 ]; // (F2 !)
580       if ( !VV1[ 0 ].IsSame( theMap( VV2[ 0 ]))) {
581         edge2.Reverse();
582         if ( FF2[ 1 ].IsNull() )
583           F2.Reverse();
584         else
585           F2 = FF2[ 1 ];
586       }
587
588       TopTools_MapOfShape boundEdges;
589
590       // association of face subshapes and neighbour faces
591       list< pair < TopoDS_Face, TopoDS_Edge > > FE1, FE2;
592       list< pair < TopoDS_Face, TopoDS_Edge > >::iterator fe1, fe2;
593       FE1.push_back( make_pair( TopoDS::Face( F1 ), edge1 ));
594       FE2.push_back( make_pair( TopoDS::Face( F2 ), edge2 ));
595       for ( fe1 = FE1.begin(), fe2 = FE2.begin(); fe1 != FE1.end(); ++fe1, ++fe2 )
596       {
597         const TopoDS_Face& face1 = fe1->first;
598         if ( theMap.IsBound( face1 ) ) continue;
599         const TopoDS_Face& face2 = fe2->first;
600         edge1 = fe1->second;
601         edge2 = fe2->second;
602         TopExp::Vertices( edge1, VV1[0], VV1[1], true );
603         TopExp::Vertices( edge2, VV2[0], VV2[1], true );
604         list< TopoDS_Edge > edges1, edges2;
605         int nbE = FindFaceAssociation( face1, VV1, face2, VV2, edges1, edges2 );
606         if ( !nbE ) RETURN_BAD_RESULT("FindFaceAssociation() failed");
607         InsertAssociation( face1, face2, theMap, bidirect); // assoc faces
608         MESSAGE("Assoc FACE " << theMesh1->GetMeshDS()->ShapeToIndex( face1 )<<
609                 " to "        << theMesh2->GetMeshDS()->ShapeToIndex( face2 ));
610         if ( nbE == 2 && (edge1.IsSame( edges1.front())) != (edge2.IsSame( edges2.front())))
611         {
612           Reverse( edges2, nbE );
613         }
614         list< TopoDS_Edge >::iterator eIt1 = edges1.begin();
615         list< TopoDS_Edge >::iterator eIt2 = edges2.begin();
616         for ( ; eIt1 != edges1.end(); ++eIt1, ++eIt2 )
617         {
618           if ( !boundEdges.Add( *eIt1 )) continue; // already associated
619           InsertAssociation( *eIt1, *eIt2, theMap, bidirect);  // assoc edges
620           MESSAGE("Assoc edge " << theMesh1->GetMeshDS()->ShapeToIndex( *eIt1 )<<
621                   " to "        << theMesh2->GetMeshDS()->ShapeToIndex( *eIt2 ));
622           VV1[0] = TopExp::FirstVertex( *eIt1, true );
623           VV2[0] = TopExp::FirstVertex( *eIt2, true );
624           InsertAssociation( VV1[0], VV2[0], theMap, bidirect); // assoc vertices
625           MESSAGE("Assoc vertex " << theMesh1->GetMeshDS()->ShapeToIndex( VV1[0] )<<
626                   " to "          << theMesh2->GetMeshDS()->ShapeToIndex( VV2[0] ));
627
628           // add adjacent faces to process
629           TopoDS_Face nextFace1 = GetNextFace( edgeToFace1, *eIt1, face1 );
630           TopoDS_Face nextFace2 = GetNextFace( edgeToFace2, *eIt2, face2 );
631           if ( !nextFace1.IsNull() && !nextFace2.IsNull() ) {
632             FE1.push_back( make_pair( nextFace1, *eIt1 ));
633             FE2.push_back( make_pair( nextFace2, *eIt2 ));
634           }
635         }
636       }
637       InsertAssociation( theShape1, theShape2, theMap, bidirect );
638       return true;
639     }
640       // ----------------------------------------------------------------------
641     case TopAbs_COMPOUND: { // GROUP
642       // ----------------------------------------------------------------------
643       // Maybe groups contain only one member
644       TopoDS_Iterator it1( theShape1 ), it2( theShape2 );
645       TopAbs_ShapeEnum memberType = it1.Value().ShapeType();
646       int nbMembers = Count( theShape1, memberType, true );
647       if ( nbMembers == 0 ) return true;
648       if ( nbMembers == 1 ) {
649         return FindSubShapeAssociation( it1.Value(), theMesh1, it2.Value(), theMesh2, theMap );
650       }
651       // Try to make shells of faces
652       //
653       BRep_Builder builder;
654       TopoDS_Shell shell1, shell2;
655       builder.MakeShell(shell1); builder.MakeShell(shell2);
656       if ( memberType == TopAbs_FACE ) {
657         // just add faces of groups to shells
658         for (; it1.More(); it1.Next(), it2.Next() )
659           builder.Add( shell1, it1.Value() ), builder.Add( shell2, it2.Value() );
660       }
661       else if ( memberType == TopAbs_EDGE ) {
662         // Try to add faces sharing more than one edge of a group or
663         // sharing all its vertices with the group
664         TopTools_IndexedMapOfShape groupVertices[2];
665         TopExp::MapShapes( theShape1, TopAbs_VERTEX, groupVertices[0]);
666         TopExp::MapShapes( theShape2, TopAbs_VERTEX, groupVertices[1]);
667         //
668         TopTools_MapOfShape groupEdges[2], addedFaces[2];
669         bool hasInitAssoc = (!theMap.IsEmpty()), initAssocOK = !hasInitAssoc;
670         for (; it1.More(); it1.Next(), it2.Next() ) {
671           groupEdges[0].Add( it1.Value() );
672           groupEdges[1].Add( it2.Value() );
673           if ( !initAssocOK ) {
674             // for shell association there must be an edge with both vertices bound
675             TopoDS_Vertex v1, v2;
676             TopExp::Vertices( TopoDS::Edge( it1.Value()), v1, v2 );
677             initAssocOK = ( theMap.IsBound( v1 ) && theMap.IsBound( v2 ));
678           }
679         }
680         for (int is2ndGroup = 0; initAssocOK && is2ndGroup < 2; ++is2ndGroup) {
681           const TopoDS_Shape& group = is2ndGroup ? theShape2: theShape1;
682           SMESH_Mesh*         mesh  = is2ndGroup ? theMesh2 : theMesh1;
683           TopoDS_Shell&       shell = is2ndGroup ? shell2   : shell1;
684           for ( TopoDS_Iterator it( group ); it.More(); it.Next() ) {
685             const TopoDS_Edge& edge = TopoDS::Edge( it.Value() );
686             TopoDS_Face face;
687             for ( int iF = 0; iF < 2; ++iF ) { // loop on 2 faces sharing edge
688               face = GetNextFace(mesh->GetAncestorMap(), edge, face);
689               if ( !face.IsNull() ) {
690                 int nbGroupEdges = 0;
691                 for ( TopExp_Explorer f( face, TopAbs_EDGE ); f.More(); f.Next())
692                   if ( groupEdges[ is2ndGroup ].Contains( f.Current() ))
693                     if ( ++nbGroupEdges > 1 )
694                       break;
695                 bool add = (nbGroupEdges > 1 || Count( face, TopAbs_EDGE, true ) == 1 );
696                 if ( !add ) {
697                   add = true;
698                   for ( TopExp_Explorer v( face, TopAbs_VERTEX ); add && v.More(); v.Next())
699                     add = groupVertices[ is2ndGroup ].Contains( v.Current() );
700                 }
701                 if ( add && addedFaces[ is2ndGroup ].Add( face ))
702                   builder.Add( shell, face );
703               }
704             }
705           }
706         }
707       } else {
708         RETURN_BAD_RESULT("Unexpected group type");
709       }
710       // Associate shells
711       //
712       int nbFaces1 = Count( shell1, TopAbs_FACE, 0 );
713       int nbFaces2 = Count( shell2, TopAbs_FACE, 0 );
714       if ( nbFaces1 != nbFaces2 )
715         RETURN_BAD_RESULT("Different nb of faces found for shells");
716       if ( nbFaces1 > 0 ) {
717         bool ok = false;
718         if ( nbFaces1 == 1 ) {
719           TopoDS_Shape F1 = TopoDS_Iterator( shell1 ).Value();
720           TopoDS_Shape F2 = TopoDS_Iterator( shell2 ).Value();
721           ok = FindSubShapeAssociation( F1, theMesh1, F2, theMesh2, theMap );
722         }
723         else {
724           ok = FindSubShapeAssociation(shell1, theMesh1, shell2, theMesh2, theMap );
725         }
726         // Check if all members are mapped 
727         if ( ok ) {
728           TopTools_MapOfShape boundMembers[2];
729           TopoDS_Iterator mIt;
730           for ( mIt.Initialize( theShape1 ); mIt.More(); mIt.Next())
731             if ( theMap.IsBound( mIt.Value() )) {
732               boundMembers[0].Add( mIt.Value() );
733               boundMembers[1].Add( theMap( mIt.Value() ));
734             }
735           if ( boundMembers[0].Extent() != nbMembers ) {
736             // make compounds of not bound members
737             TopoDS_Compound comp[2];
738             for ( int is2ndGroup = 0; is2ndGroup < 2; ++is2ndGroup ) {
739               builder.MakeCompound( comp[is2ndGroup] );
740               for ( mIt.Initialize( is2ndGroup ? theShape2:theShape1 ); mIt.More(); mIt.Next())
741                 if ( ! boundMembers[ is2ndGroup ].Contains( mIt.Value() ))
742                   builder.Add( comp[ is2ndGroup ], mIt.Value() );
743             }
744             // check if theMap contains initial association for the comp's
745             bool hasInitialAssoc = false;
746             if ( memberType == TopAbs_EDGE ) {
747               for ( TopExp_Explorer v( comp[0], TopAbs_VERTEX ); v.More(); v.Next())
748                 if ( theMap.IsBound( v.Current() )) {
749                   hasInitialAssoc = true;
750                   break;
751                 }
752             }
753             if ( hasInitialAssoc == bool( !theMap.IsEmpty() ))
754               ok = FindSubShapeAssociation( comp[0], theMesh1, comp[1], theMesh2, theMap );
755             else {
756               TShapeShapeMap tmpMap;
757               ok = FindSubShapeAssociation( comp[0], theMesh1, comp[1], theMesh2, tmpMap );
758               if ( ok ) {
759                 TopTools_DataMapIteratorOfDataMapOfShapeShape mapIt( tmpMap );
760                 for ( ; mapIt.More(); mapIt.Next() )
761                   theMap.Bind( mapIt.Key(), mapIt.Value());
762               }
763             }
764           }
765         }
766         return ok;
767       }
768       // Each edge of an edge group is shared by own faces
769       // ------------------------------------------------------------------
770       //
771       // map vertices to edges sharing them, avoid doubling edges in lists
772       TopTools_DataMapOfShapeListOfShape v2e[2];
773       for (int isFirst = 0; isFirst < 2; ++isFirst ) {
774         const TopoDS_Shape& group = isFirst ? theShape1 : theShape2;
775         TopTools_DataMapOfShapeListOfShape& veMap = v2e[ isFirst ? 0 : 1 ];
776         TopTools_MapOfShape addedEdges;
777         for ( TopExp_Explorer e( group, TopAbs_EDGE ); e.More(); e.Next() ) {
778           const TopoDS_Shape& edge = e.Current();
779           if ( addedEdges.Add( edge )) {
780             for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next()) {
781               const TopoDS_Shape& vertex = v.Current();
782               if ( !veMap.IsBound( vertex )) {
783                 TopTools_ListOfShape l;
784                 veMap.Bind( vertex, l );
785               }
786               veMap( vertex ).Append( edge );
787             }
788           }
789         }   
790       }
791       while ( !v2e[0].IsEmpty() )
792       {
793         // find a bound vertex
794         TopoDS_Vertex V[2];
795         TopTools_DataMapIteratorOfDataMapOfShapeListOfShape v2eIt( v2e[0] );
796         for ( ; v2eIt.More(); v2eIt.Next())
797           if ( theMap.IsBound( v2eIt.Key() )) {
798             V[0] = TopoDS::Vertex( v2eIt.Key() );
799             V[1] = TopoDS::Vertex( theMap( V[0] ));
800             break;
801           }
802         if ( V[0].IsNull() )
803           RETURN_BAD_RESULT("No more bound vertices");
804
805         while ( !V[0].IsNull() && v2e[0].IsBound( V[0] )) {
806           TopTools_ListOfShape& edges0 = v2e[0]( V[0] );
807           TopTools_ListOfShape& edges1 = v2e[1]( V[1] );
808           int nbE0 = edges0.Extent(), nbE1 = edges1.Extent();
809           if ( nbE0 != nbE1 )
810             RETURN_BAD_RESULT("Different nb of edges: "<< nbE0 << " != " << nbE1);
811
812           if ( nbE0 == 1 )
813           {
814             TopoDS_Edge e0 = TopoDS::Edge( edges0.First() );
815             TopoDS_Edge e1 = TopoDS::Edge( edges1.First() );
816             v2e[0].UnBind( V[0] );
817             v2e[1].UnBind( V[1] );
818             InsertAssociation( e0, e1, theMap, bidirect );
819             MESSAGE("Assoc edge " << theMesh1->GetMeshDS()->ShapeToIndex( e0 )<<
820                     " to "        << theMesh2->GetMeshDS()->ShapeToIndex( e1 ));
821             V[0] = GetNextVertex( e0, V[0] );
822             V[1] = GetNextVertex( e1, V[1] );
823             if ( !V[0].IsNull() ) {
824               InsertAssociation( V[0], V[1], theMap, bidirect );
825               MESSAGE("Assoc vertex " << theMesh1->GetMeshDS()->ShapeToIndex( V[0] )<<
826                       " to "          << theMesh2->GetMeshDS()->ShapeToIndex( V[1] ));
827             }
828           }
829           else if ( nbE0 == 2 )
830           {
831             // one of edges must have both ends bound
832             TopoDS_Vertex v0e0 = GetNextVertex( TopoDS::Edge( edges0.First() ), V[0] );
833             TopoDS_Vertex v1e0 = GetNextVertex( TopoDS::Edge( edges0.Last() ),  V[0] );
834             TopoDS_Vertex v0e1 = GetNextVertex( TopoDS::Edge( edges1.First() ), V[1] );
835             TopoDS_Vertex v1e1 = GetNextVertex( TopoDS::Edge( edges1.Last() ),  V[1] );
836             TopoDS_Shape e0b, e1b, e0n, e1n, v1b; // bound and not-bound
837             TopoDS_Vertex v0n, v1n;
838             if ( theMap.IsBound( v0e0 )) {
839               v0n = v1e0; e0b = edges0.First(); e0n = edges0.Last(); v1b = theMap( v0e0 );
840             } else if ( theMap.IsBound( v1e0 )) {
841               v0n = v0e0; e0n = edges0.First(); e0b = edges0.Last(); v1b = theMap( v1e0 );
842             } else {
843               RETURN_BAD_RESULT("None of vertices bound");
844             }
845             if ( v1b.IsSame( v1e1 )) {
846               v1n = v0e1; e1n = edges1.First(); e1b = edges1.Last();
847             } else {
848               v1n = v1e1; e1b = edges1.First(); e1n = edges1.Last();
849             }
850             InsertAssociation( e0b, e1b, theMap, bidirect );
851             InsertAssociation( e0n, e1n, theMap, bidirect );
852             InsertAssociation( v0n, v1n, theMap, bidirect );
853             MESSAGE("Assoc edge " << theMesh1->GetMeshDS()->ShapeToIndex( e0b )<<
854                     " to "        << theMesh2->GetMeshDS()->ShapeToIndex( e1b ));
855             MESSAGE("Assoc edge " << theMesh1->GetMeshDS()->ShapeToIndex( e0n )<<
856                     " to "        << theMesh2->GetMeshDS()->ShapeToIndex( e1n ));
857             MESSAGE("Assoc vertex " << theMesh1->GetMeshDS()->ShapeToIndex( v0n )<<
858                     " to "          << theMesh2->GetMeshDS()->ShapeToIndex( v1n ));
859             v2e[0].UnBind( V[0] );
860             v2e[1].UnBind( V[1] );
861             V[0] = v0n;
862             V[1] = v1n;
863           }
864           else {
865             RETURN_BAD_RESULT("Not implemented");
866           }
867         }
868       } //while ( !v2e[0].IsEmpty() )
869       return true;
870     }
871
872     default:
873       RETURN_BAD_RESULT("Unexpected shape type");
874
875     } // end switch by shape type
876   } // end case of available initial vertex association
877
878   //======================================================================
879   // NO INITIAL VERTEX ASSOCIATION
880   //======================================================================
881
882   switch ( theShape1.ShapeType() ) {
883
884   case TopAbs_EDGE: {
885     // ----------------------------------------------------------------------
886     TopoDS_Edge edge1 = TopoDS::Edge( theShape1 );
887     TopoDS_Edge edge2 = TopoDS::Edge( theShape2 );
888     if ( IsPropagationPossible( theMesh1, theMesh2 ))
889     {
890       TopoDS_Edge prpEdge = GetPropagationEdge( theMesh1, edge2, edge1 ).second;
891       if ( !prpEdge.IsNull() )
892       {
893         TopoDS_Vertex VV1[2], VV2[2];
894         TopExp::Vertices( edge1,   VV1[0], VV1[1], true );
895         TopExp::Vertices( prpEdge, VV2[0], VV2[1], true );
896         InsertAssociation( VV1[ 0 ], VV2[ 0 ], theMap, bidirect);
897         InsertAssociation( VV1[ 1 ], VV2[ 1 ], theMap, bidirect);
898         if ( VV1[0].IsSame( VV1[1] ) || // one of edges is closed
899              VV2[0].IsSame( VV2[1] ) )
900         {
901           InsertAssociation( edge1, prpEdge, theMap, bidirect); // insert with a proper orientation
902         }
903         InsertAssociation( theShape1, theShape2, theMap, bidirect );
904         return true; // done
905       }
906     }
907     if ( IsClosedEdge( edge1 ) && IsClosedEdge( edge2 ))
908     {
909       // TODO: find out a proper orientation (is it possible?)
910       InsertAssociation( edge1, edge2, theMap, bidirect); // insert with a proper orientation
911       InsertAssociation( TopExp::FirstVertex(edge1), TopExp::FirstVertex(edge2),
912                          theMap, bidirect);
913       InsertAssociation( theShape1, theShape2, theMap, bidirect );
914       return true; // done
915     }
916     break; // try by vertex closeness
917   }
918
919   case TopAbs_FACE: {
920     // ----------------------------------------------------------------------
921     if ( IsPropagationPossible( theMesh1, theMesh2 )) // try by propagation in one mesh
922     {
923       TopoDS_Face face1 = TopoDS::Face(theShape1);
924       TopoDS_Face face2 = TopoDS::Face(theShape2);
925       TopoDS_Edge edge1, edge2;
926       // get outer edge of theShape1
927       edge1 = TopoDS::Edge( OuterShape( face1, TopAbs_EDGE ));
928       // find out if any edge of face2 is a propagation edge of outer edge1
929       map<int,TopoDS_Edge> propag_edges; // use map to find the closest propagation edge
930       for ( TopExp_Explorer exp( face2, TopAbs_EDGE ); exp.More(); exp.Next() ) {
931         edge2 = TopoDS::Edge( exp.Current() );
932         pair<int,TopoDS_Edge> step_edge = GetPropagationEdge( theMesh1, edge2, edge1 );
933         if ( !step_edge.second.IsNull() ) { // propagation found
934           propag_edges.insert( step_edge );
935           if ( step_edge.first == 1 ) break; // most close found
936         }
937       }
938       if ( !propag_edges.empty() ) // propagation found
939       {
940         edge2 = propag_edges.begin()->second;
941         TopoDS_Vertex VV1[2], VV2[2];
942         TopExp::Vertices( edge1, VV1[0], VV1[1], true );
943         TopExp::Vertices( edge2, VV2[0], VV2[1], true );
944         list< TopoDS_Edge > edges1, edges2;
945         int nbE = FindFaceAssociation( face1, VV1, face2, VV2, edges1, edges2 );
946         if ( !nbE ) RETURN_BAD_RESULT("FindFaceAssociation() failed");
947         if ( nbE == 2 ) // only 2 edges
948         {
949           // take care of proper association of propagated edges
950           bool same1 = edge1.IsSame( edges1.front() );
951           bool same2 = edge2.IsSame( edges2.front() );
952           if ( same1 != same2 )
953             Reverse(edges2, nbE);
954         }
955         // store association
956         list< TopoDS_Edge >::iterator eIt1 = edges1.begin();
957         list< TopoDS_Edge >::iterator eIt2 = edges2.begin();
958         for ( ; eIt1 != edges1.end(); ++eIt1, ++eIt2 )
959         {
960           InsertAssociation( *eIt1, *eIt2, theMap, bidirect);
961           VV1[0] = TopExp::FirstVertex( *eIt1, true );
962           VV2[0] = TopExp::FirstVertex( *eIt2, true );
963           InsertAssociation( VV1[0], VV2[0], theMap, bidirect);
964         }
965         InsertAssociation( theShape1, theShape2, theMap, bidirect );
966         return true;
967       }
968     }
969     break; // try by vertex closeness
970   }
971   case TopAbs_COMPOUND: {
972     // ----------------------------------------------------------------------
973     if ( IsPropagationPossible( theMesh1, theMesh2 )) {
974
975       // try to accosiate all using propagation
976       if ( AssocGroupsByPropagation( theShape1, theShape2, *theMesh1, theMap ))
977         return true;
978
979       // find a boundary edge for theShape1
980       TopoDS_Edge E;
981       for(TopExp_Explorer exp(theShape1, TopAbs_EDGE); exp.More(); exp.Next() ) {
982         E = TopoDS::Edge( exp.Current() );
983         if ( IsBoundaryEdge( E, theShape1, *theMesh1 ))
984           break;
985         else
986           E.Nullify();
987       }
988       if ( E.IsNull() )
989         break; // try by vertex closeness
990
991       // find association for vertices of edge E
992       TopoDS_Vertex VV1[2], VV2[2];
993       for(TopExp_Explorer eexp(E, TopAbs_VERTEX); eexp.More(); eexp.Next()) {
994         TopoDS_Vertex V1 = TopoDS::Vertex( eexp.Current() );
995         // look for an edge ending in E whose one vertex is in theShape1
996         // and the other, in theShape2
997         const TopTools_ListOfShape& Ancestors = theMesh1->GetAncestors(V1);
998         TopTools_ListIteratorOfListOfShape ita(Ancestors);
999         for(; ita.More(); ita.Next()) {
1000           if( ita.Value().ShapeType() != TopAbs_EDGE ) continue;
1001           TopoDS_Edge edge = TopoDS::Edge(ita.Value());
1002           bool FromShape1 = false;
1003           for(TopExp_Explorer expe(theShape1, TopAbs_EDGE); expe.More(); expe.Next() ) {
1004             if(edge.IsSame(expe.Current())) {
1005               FromShape1 = true;
1006               break;
1007             }
1008           }
1009           if(!FromShape1) {
1010             // is it an edge between theShape1 and theShape2?
1011             TopExp_Explorer expv(edge, TopAbs_VERTEX);
1012             TopoDS_Vertex V2 = TopoDS::Vertex( expv.Current() );
1013             if(V2.IsSame(V1)) {
1014               expv.Next();
1015               V2 = TopoDS::Vertex( expv.Current() );
1016             }
1017             bool FromShape2 = false;
1018             for ( expv.Init( theShape2, TopAbs_VERTEX ); expv.More(); expv.Next()) {
1019               if ( V2.IsSame( expv.Current() )) {
1020                 FromShape2 = true;
1021                 break;
1022               }
1023             }
1024             if ( FromShape2 ) {
1025               if ( VV1[0].IsNull() )
1026                 VV1[0] = V1, VV2[0] = V2;
1027               else
1028                 VV1[1] = V1, VV2[1] = V2;
1029               break; // from loop on ancestors of V1
1030             }
1031           }
1032         }
1033       }
1034       if ( !VV1[1].IsNull() ) {
1035         InsertAssociation( VV1[0], VV2[0], theMap, bidirect);
1036         InsertAssociation( VV1[1], VV2[1], theMap, bidirect);
1037         return FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap);
1038       }
1039     }
1040     break; // try by vertex closeness
1041   }
1042   default:;
1043   }
1044
1045   // Find association by closeness of vertices
1046   // ------------------------------------------
1047
1048   TopTools_IndexedMapOfShape vMap1, vMap2;
1049   TopExp::MapShapes( theShape1, TopAbs_VERTEX, vMap1 );
1050   TopExp::MapShapes( theShape2, TopAbs_VERTEX, vMap2 );
1051
1052   if ( vMap1.Extent() != vMap2.Extent() )
1053     RETURN_BAD_RESULT("Different nb of vertices");
1054
1055   if ( vMap1.Extent() == 1 ) {
1056     InsertAssociation( vMap1(1), vMap2(1), theMap, bidirect);
1057     if ( theShape1.ShapeType() == TopAbs_EDGE ) {
1058       InsertAssociation( theShape1, theShape2, theMap, bidirect );
1059       return true;
1060     }
1061     return FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap);
1062   }
1063
1064   // Find transformation to make the shapes be of similar size at same location
1065
1066   Bnd_Box box[2];
1067   for ( int i = 1; i <= vMap1.Extent(); ++i ) {
1068     box[ 0 ].Add( BRep_Tool::Pnt ( TopoDS::Vertex( vMap1( i ))));
1069     box[ 1 ].Add( BRep_Tool::Pnt ( TopoDS::Vertex( vMap2( i ))));
1070   }
1071
1072   gp_Pnt gc[2]; // box center
1073   double x0,y0,z0, x1,y1,z1;
1074   box[0].Get( x0,y0,z0, x1,y1,z1 );
1075   gc[0] = 0.5 * ( gp_XYZ( x0,y0,z0 ) + gp_XYZ( x1,y1,z1 ));
1076   box[1].Get( x0,y0,z0, x1,y1,z1 );
1077   gc[1] = 0.5 * ( gp_XYZ( x0,y0,z0 ) + gp_XYZ( x1,y1,z1 ));
1078
1079   // 1 -> 2
1080   gp_Vec vec01( gc[0], gc[1] );
1081   double scale = sqrt( box[1].SquareExtent() / box[0].SquareExtent() );
1082
1083   // Find 2 closest vertices
1084
1085   TopoDS_Vertex VV1[2], VV2[2];
1086   // get 2 linked vertices of shape 1 not belonging to an inner wire of a face
1087   TopoDS_Shape edge = theShape1;
1088   TopExp_Explorer expF( theShape1, TopAbs_FACE ), expE;
1089   if ( expF.More() ) {
1090     for ( ; expF.More(); expF.Next() ) {
1091       edge.Nullify();
1092       TopoDS_Shape wire = OuterShape( TopoDS::Face( expF.Current() ), TopAbs_WIRE );
1093       for ( expE.Init( wire, TopAbs_EDGE ); edge.IsNull() && expE.More(); expE.Next() )
1094         if ( !IsClosedEdge( TopoDS::Edge( expE.Current() )))
1095           edge = expE.Current();
1096       if ( !edge.IsNull() )
1097         break;
1098     }
1099   } else if (edge.ShapeType() != TopAbs_EDGE) { // no faces
1100     edge.Nullify();
1101     for ( expE.Init( theShape1, TopAbs_EDGE ); edge.IsNull() && expE.More(); expE.Next() )
1102       if ( !IsClosedEdge( TopoDS::Edge( expE.Current() )))
1103         edge = expE.Current();
1104   }
1105   if ( edge.IsNull() || edge.ShapeType() != TopAbs_EDGE )
1106     RETURN_BAD_RESULT("Edge not found");
1107
1108   TopExp::Vertices( TopoDS::Edge( edge ), VV1[0], VV1[1]);
1109   if ( VV1[0].IsSame( VV1[1] ))
1110     RETURN_BAD_RESULT("Only closed edges");
1111
1112   // find vertices closest to 2 linked vertices of shape 1
1113   for ( int i1 = 0; i1 < 2; ++i1 )
1114   {
1115     double dist2 = DBL_MAX;
1116     gp_Pnt p1 = BRep_Tool::Pnt( VV1[ i1 ]);
1117     p1.Translate( vec01 );
1118     p1.Scale( gc[1], scale );
1119     for ( int i2 = 1; i2 <= vMap2.Extent(); ++i2 )
1120     {
1121       TopoDS_Vertex V2 = TopoDS::Vertex( vMap2( i2 ));
1122       gp_Pnt p2 = BRep_Tool::Pnt ( V2 );
1123       double d2 = p1.SquareDistance( p2 );
1124       if ( d2 < dist2 && !V2.IsSame( VV2[ 0 ])) {
1125         VV2[ i1 ] = V2; dist2 = d2;
1126       }
1127     }
1128   }
1129
1130   InsertAssociation( VV1[ 0 ], VV2[ 0 ], theMap, bidirect);
1131   InsertAssociation( VV1[ 1 ], VV2[ 1 ], theMap, bidirect);
1132   MESSAGE("Initial assoc VERT " << theMesh1->GetMeshDS()->ShapeToIndex( VV1[ 0 ] )<<
1133           " to "                << theMesh2->GetMeshDS()->ShapeToIndex( VV2[ 0 ] )<<
1134           "\nand         VERT " << theMesh1->GetMeshDS()->ShapeToIndex( VV1[ 1 ] )<<
1135           " to "                << theMesh2->GetMeshDS()->ShapeToIndex( VV2[ 1 ] ));
1136   if ( theShape1.ShapeType() == TopAbs_EDGE ) {
1137     InsertAssociation( theShape1, theShape2, theMap, bidirect );
1138     return true;
1139   }
1140
1141   return FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap );
1142 }
1143
1144 //================================================================================
1145 /*!
1146  * \brief Find association of edges of faces
1147  * \param face1 - face 1
1148  * \param VV1 - vertices of face 1
1149  * \param face2 - face 2
1150  * \param VV2 - vertices of face 2 associated with ones of face 1
1151  * \param edges1 - out list of edges of face 1
1152  * \param edges2 - out list of edges of face 2
1153  * \retval int - nb of edges in an outer wire in a success case, else zero
1154  */
1155 //================================================================================
1156
1157 int StdMeshers_ProjectionUtils::FindFaceAssociation(const TopoDS_Face&    face1,
1158                                                     TopoDS_Vertex         VV1[2],
1159                                                     const TopoDS_Face&    face2,
1160                                                     TopoDS_Vertex         VV2[2],
1161                                                     list< TopoDS_Edge > & edges1,
1162                                                     list< TopoDS_Edge > & edges2)
1163 {
1164   list< int > nbVInW1, nbVInW2;
1165   for ( int outer_wire_algo = 0; outer_wire_algo < 2; ++outer_wire_algo )
1166   {
1167     edges1.clear();
1168     edges2.clear();
1169
1170     if ( SMESH_Block::GetOrderedEdges( face1, VV1[0], edges1, nbVInW1, outer_wire_algo) !=
1171          SMESH_Block::GetOrderedEdges( face2, VV2[0], edges2, nbVInW2, outer_wire_algo) )
1172       CONT_BAD_RESULT("Different number of wires in faces ");
1173
1174     if ( nbVInW1.front() != nbVInW2.front() )
1175       CONT_BAD_RESULT("Different number of edges in faces: " <<
1176                       nbVInW1.front() << " != " << nbVInW2.front());
1177
1178     // Define if we need to reverse one of wires to make edges in lists match each other
1179
1180     bool reverse = false;
1181
1182     list< TopoDS_Edge >::iterator edgeIt;
1183     if ( !VV1[1].IsSame( TopExp::LastVertex( edges1.front(), true ))) {
1184       reverse = true;
1185       edgeIt = --edges1.end();
1186       // check if the second vertex belongs to the first or last edge in the wire
1187       if ( !VV1[1].IsSame( TopExp::FirstVertex( *edgeIt, true ))) {
1188         bool KO = true; // belongs to none
1189         if ( nbVInW1.size() > 1 ) { // several wires
1190           edgeIt = edges1.begin();
1191           for ( int i = 1; i < nbVInW1.front(); ++i ) ++edgeIt;
1192           KO = !VV1[1].IsSame( TopExp::FirstVertex( *edgeIt, true ));
1193         }
1194         if ( KO )
1195           CONT_BAD_RESULT("GetOrderedEdges() failed");
1196       }
1197     }
1198     edgeIt = --edges2.end();
1199     if ( !VV2[1].IsSame( TopExp::LastVertex( edges2.front(), true ))) {
1200       reverse = !reverse;
1201       // check if the second vertex belongs to the first or last edge in the wire
1202       if ( !VV2[1].IsSame( TopExp::FirstVertex( *edgeIt, true ))) {
1203         bool KO = true; // belongs to none
1204         if ( nbVInW2.size() > 1 ) { // several wires
1205           edgeIt = edges2.begin();
1206           for ( int i = 1; i < nbVInW2.front(); ++i ) ++edgeIt;
1207           KO = !VV2[1].IsSame( TopExp::FirstVertex( *edgeIt, true ));
1208         }
1209         if ( KO )
1210           CONT_BAD_RESULT("GetOrderedEdges() failed");
1211       }
1212     }
1213     if ( reverse )
1214     {
1215       Reverse( edges2 , nbVInW2.front());
1216       if (( VV1[1].IsSame( TopExp::LastVertex( edges1.front(), true ))) !=
1217           ( VV2[1].IsSame( TopExp::LastVertex( edges2.front(), true ))))
1218         CONT_BAD_RESULT("GetOrderedEdges() failed");
1219     }
1220   }
1221   return nbVInW2.front();
1222 }
1223
1224 //=======================================================================
1225 //function : InitVertexAssociation
1226 //purpose  : 
1227 //=======================================================================
1228
1229 void StdMeshers_ProjectionUtils::InitVertexAssociation( const SMESH_Hypothesis* theHyp,
1230                                                         TShapeShapeMap &        theAssociationMap,
1231                                                         const TopoDS_Shape&     theTargetShape)
1232 {
1233   string hypName = theHyp->GetName();
1234   if ( hypName == "ProjectionSource1D" ) {
1235     const StdMeshers_ProjectionSource1D * hyp =
1236       static_cast<const StdMeshers_ProjectionSource1D*>( theHyp );
1237     if ( hyp->HasVertexAssociation() )
1238       InsertAssociation( hyp->GetSourceVertex(),hyp->GetTargetVertex(),theAssociationMap);
1239   }
1240   else if ( hypName == "ProjectionSource2D" ) {
1241     const StdMeshers_ProjectionSource2D * hyp =
1242       static_cast<const StdMeshers_ProjectionSource2D*>( theHyp );
1243     if ( hyp->HasVertexAssociation() ) {
1244       InsertAssociation( hyp->GetSourceVertex(1),hyp->GetTargetVertex(1),theAssociationMap);
1245       InsertAssociation( hyp->GetSourceVertex(2),hyp->GetTargetVertex(2),theAssociationMap);
1246     }
1247   }
1248   else if ( hypName == "ProjectionSource3D" ) {
1249     const StdMeshers_ProjectionSource3D * hyp =
1250       static_cast<const StdMeshers_ProjectionSource3D*>( theHyp );
1251     if ( hyp->HasVertexAssociation() ) {
1252       InsertAssociation( hyp->GetSourceVertex(1),hyp->GetTargetVertex(1),theAssociationMap);
1253       InsertAssociation( hyp->GetSourceVertex(2),hyp->GetTargetVertex(2),theAssociationMap);
1254     }
1255   }
1256 }
1257
1258 //=======================================================================
1259 /*!
1260  * \brief Inserts association theShape1 <-> theShape2 to TShapeShapeMap
1261  * \param theShape1 - shape 1
1262  * \param theShape2 - shape 2
1263  * \param theAssociationMap - association map 
1264  * \retval bool - true if there was no association for these shapes before
1265  */
1266 //=======================================================================
1267
1268 bool StdMeshers_ProjectionUtils::InsertAssociation( const TopoDS_Shape& theShape1,
1269                                                     const TopoDS_Shape& theShape2,
1270                                                     TShapeShapeMap &    theAssociationMap,
1271                                                     const bool          theBidirectional)
1272 {
1273   if ( !theShape1.IsNull() && !theShape2.IsNull() ) {
1274     SHOW_VERTEX(theShape1,"Assoc ");
1275     SHOW_VERTEX(theShape2," to ");
1276     bool isNew = ( theAssociationMap.Bind( theShape1, theShape2 ));
1277     if ( theBidirectional )
1278       theAssociationMap.Bind( theShape2, theShape1 );
1279     return isNew;
1280   }
1281   else {
1282     throw SALOME_Exception("StdMeshers_ProjectionUtils: attempt to associate NULL shape");
1283   }
1284   return false;
1285 }
1286
1287 //=======================================================================
1288 /*!
1289  * \brief Finds an edge by its vertices in a main shape of the mesh
1290  * \param aMesh - the mesh
1291  * \param V1 - vertex 1
1292  * \param V2 - vertex 2
1293  * \retval TopoDS_Edge - found edge
1294  */
1295 //=======================================================================
1296
1297 TopoDS_Edge StdMeshers_ProjectionUtils::GetEdgeByVertices( SMESH_Mesh*          theMesh,
1298                                                            const TopoDS_Vertex& theV1,
1299                                                            const TopoDS_Vertex& theV2)
1300 {
1301   if ( theMesh && !theV1.IsNull() && !theV2.IsNull() )
1302   {
1303     TopTools_ListIteratorOfListOfShape ancestorIt( theMesh->GetAncestors( theV1 ));
1304     for ( ; ancestorIt.More(); ancestorIt.Next() )
1305       if ( ancestorIt.Value().ShapeType() == TopAbs_EDGE )
1306         for ( TopExp_Explorer expV ( ancestorIt.Value(), TopAbs_VERTEX );
1307               expV.More();
1308               expV.Next() )
1309           if ( theV2.IsSame( expV.Current() ))
1310             return TopoDS::Edge( ancestorIt.Value() );
1311   }
1312   return TopoDS_Edge();
1313 }
1314
1315 //================================================================================
1316 /*!
1317  * \brief Return another face sharing an edge
1318  * \param edgeToFaces - data map of descendants to ancestors
1319  * \param edge - edge
1320  * \param face - face
1321  * \retval TopoDS_Face - found face
1322  */
1323 //================================================================================
1324
1325 TopoDS_Face StdMeshers_ProjectionUtils::GetNextFace( const TAncestorMap& edgeToFaces,
1326                                                      const TopoDS_Edge&  edge,
1327                                                      const TopoDS_Face&  face)
1328 {
1329 //   if ( !edge.IsNull() && !face.IsNull() && edgeToFaces.Contains( edge ))
1330   if ( !edge.IsNull() && edgeToFaces.Contains( edge )) // PAL16202
1331   {
1332     TopTools_ListIteratorOfListOfShape ancestorIt( edgeToFaces.FindFromKey( edge ));
1333     for ( ; ancestorIt.More(); ancestorIt.Next() )
1334       if ( ancestorIt.Value().ShapeType() == TopAbs_FACE &&
1335            !face.IsSame( ancestorIt.Value() ))
1336         return TopoDS::Face( ancestorIt.Value() );
1337   }
1338   return TopoDS_Face();
1339 }
1340
1341 //================================================================================
1342 /*!
1343  * \brief Return other vertex of an edge
1344  */
1345 //================================================================================
1346
1347 TopoDS_Vertex StdMeshers_ProjectionUtils::GetNextVertex(const TopoDS_Edge&   edge,
1348                                                         const TopoDS_Vertex& vertex)
1349 {
1350   TopoDS_Vertex vF,vL;
1351   TopExp::Vertices(edge,vF,vL);
1352   if ( vF.IsSame( vL ))
1353     return TopoDS_Vertex();
1354   return vertex.IsSame( vF ) ? vL : vF; 
1355 }
1356
1357 //================================================================================
1358 /*!
1359  * \brief Return a propagation edge
1360  * \param aMesh - mesh
1361  * \param theEdge - edge to find by propagation
1362  * \param fromEdge - start edge for propagation
1363  * \retval pair<int,TopoDS_Edge> - propagation step and found edge
1364  */
1365 //================================================================================
1366
1367 pair<int,TopoDS_Edge>
1368 StdMeshers_ProjectionUtils::GetPropagationEdge( SMESH_Mesh*        aMesh,
1369                                                 const TopoDS_Edge& theEdge,
1370                                                 const TopoDS_Edge& fromEdge)
1371 {
1372   SMESH_IndexedMapOfShape aChain;
1373   int step = 0;
1374
1375   // List of edges, added to chain on the previous cycle pass
1376   TopTools_ListOfShape listPrevEdges;
1377   listPrevEdges.Append(fromEdge);
1378
1379   // Collect all edges pass by pass
1380   while (listPrevEdges.Extent() > 0) {
1381     step++;
1382     // List of edges, added to chain on this cycle pass
1383     TopTools_ListOfShape listCurEdges;
1384
1385     // Find the next portion of edges
1386     TopTools_ListIteratorOfListOfShape itE (listPrevEdges);
1387     for (; itE.More(); itE.Next()) {
1388       TopoDS_Shape anE = itE.Value();
1389
1390       // Iterate on faces, having edge <anE>
1391       TopTools_ListIteratorOfListOfShape itA (aMesh->GetAncestors(anE));
1392       for (; itA.More(); itA.Next()) {
1393         TopoDS_Shape aW = itA.Value();
1394
1395         // There are objects of different type among the ancestors of edge
1396         if (aW.ShapeType() == TopAbs_WIRE) {
1397           TopoDS_Shape anOppE;
1398
1399           BRepTools_WireExplorer aWE (TopoDS::Wire(aW));
1400           Standard_Integer nb = 1, found = 0;
1401           TopTools_Array1OfShape anEdges (1,4);
1402           for (; aWE.More(); aWE.Next(), nb++) {
1403             if (nb > 4) {
1404               found = 0;
1405               break;
1406             }
1407             anEdges(nb) = aWE.Current();
1408             if (anEdges(nb).IsSame(anE)) found = nb;
1409           }
1410
1411           if (nb == 5 && found > 0) {
1412             // Quadrangle face found, get an opposite edge
1413             Standard_Integer opp = found + 2;
1414             if (opp > 4) opp -= 4;
1415             anOppE = anEdges(opp);
1416
1417             // add anOppE to aChain if ...
1418             if (!aChain.Contains(anOppE)) { // ... anOppE is not in aChain
1419               // Add found edge to the chain oriented so that to
1420               // have it co-directed with a forward MainEdge
1421               TopAbs_Orientation ori = anE.Orientation();
1422               if ( anEdges(opp).Orientation() == anEdges(found).Orientation() )
1423                 ori = TopAbs::Reverse( ori );
1424               anOppE.Orientation( ori );
1425               if ( anOppE.IsSame( theEdge ))
1426                 return make_pair( step, TopoDS::Edge( anOppE ));
1427               aChain.Add(anOppE);
1428               listCurEdges.Append(anOppE);
1429             }
1430           } // if (nb == 5 && found > 0)
1431         } // if (aF.ShapeType() == TopAbs_WIRE)
1432       } // for (; itF.More(); itF.Next())
1433     } // for (; itE.More(); itE.Next())
1434
1435     listPrevEdges = listCurEdges;
1436   } // while (listPrevEdges.Extent() > 0)
1437
1438   return make_pair( INT_MAX, TopoDS_Edge());
1439 }
1440
1441 //================================================================================
1442   /*!
1443    * \brief Find corresponding nodes on two faces
1444     * \param face1 - the first face
1445     * \param mesh1 - mesh containing elements on the first face
1446     * \param face2 - the second face
1447     * \param mesh2 - mesh containing elements on the second face
1448     * \param assocMap - map associating subshapes of the faces
1449     * \param node1To2Map - map containing found matching nodes
1450     * \retval bool - is a success
1451    */
1452 //================================================================================
1453
1454 bool StdMeshers_ProjectionUtils::
1455 FindMatchingNodesOnFaces( const TopoDS_Face&     face1,
1456                           SMESH_Mesh*            mesh1,
1457                           const TopoDS_Face&     face2,
1458                           SMESH_Mesh*            mesh2,
1459                           const TShapeShapeMap & assocMap,
1460                           TNodeNodeMap &         node1To2Map)
1461 {
1462   SMESHDS_Mesh* meshDS1 = mesh1->GetMeshDS();
1463   SMESHDS_Mesh* meshDS2 = mesh2->GetMeshDS();
1464   
1465   SMESH_MesherHelper helper1( *mesh1 );
1466   SMESH_MesherHelper helper2( *mesh2 );
1467
1468   // Get corresponding submeshes and roughly check match of meshes
1469
1470   SMESHDS_SubMesh * SM2 = meshDS2->MeshElements( face2 );
1471   SMESHDS_SubMesh * SM1 = meshDS1->MeshElements( face1 );
1472   if ( !SM2 || !SM1 )
1473     RETURN_BAD_RESULT("Empty submeshes");
1474   if ( SM2->NbNodes()    != SM1->NbNodes() ||
1475        SM2->NbElements() != SM1->NbElements() )
1476     RETURN_BAD_RESULT("Different meshes on corresponding faces "
1477                       << meshDS1->ShapeToIndex( face1 ) << " and "
1478                       << meshDS2->ShapeToIndex( face2 ));
1479   if ( SM2->NbElements() == 0 )
1480     RETURN_BAD_RESULT("Empty submeshes");
1481
1482   helper1.SetSubShape( face1 );
1483   helper2.SetSubShape( face2 );
1484   if ( helper1.HasSeam() != helper2.HasSeam() )
1485     RETURN_BAD_RESULT("Different faces' geometry");
1486
1487   // Data to call SMESH_MeshEditor::FindMatchingNodes():
1488
1489   // 1. Nodes of corresponding links:
1490
1491   // get 2 matching edges, try to find not seam ones
1492   TopoDS_Edge edge1, edge2, seam1, seam2, anyEdge1, anyEdge2;
1493   TopExp_Explorer eE( OuterShape( face2, TopAbs_WIRE ), TopAbs_EDGE );
1494   do {
1495     // edge 2
1496     TopoDS_Edge e2 = TopoDS::Edge( eE.Current() );
1497     eE.Next();
1498     // edge 1
1499     if ( !assocMap.IsBound( e2 ))
1500       RETURN_BAD_RESULT("Association not found for edge " << meshDS2->ShapeToIndex( e2 ));
1501     TopoDS_Edge e1 = TopoDS::Edge( assocMap( e2 ));
1502     if ( !helper1.IsSubShape( e1, face1 ))
1503       RETURN_BAD_RESULT("Wrong association, edge " << meshDS1->ShapeToIndex( e1 ) <<
1504                         " isn't a subshape of face " << meshDS1->ShapeToIndex( face1 ));
1505     // check that there are nodes on edges
1506     SMESHDS_SubMesh * eSM1 = meshDS1->MeshElements( e1 );
1507     SMESHDS_SubMesh * eSM2 = meshDS2->MeshElements( e2 );
1508     bool nodesOnEdges = ( eSM1 && eSM2 && eSM1->NbNodes() && eSM2->NbNodes() );
1509     // check that the nodes on edges belong to faces
1510     // (as NETGEN ignores nodes on the degenerated geom edge)
1511     bool nodesOfFaces = false;
1512     if ( nodesOnEdges ) {
1513       const SMDS_MeshNode* n1 = eSM1->GetNodes()->next();
1514       const SMDS_MeshNode* n2 = eSM2->GetNodes()->next();
1515       nodesOfFaces = ( n1->GetInverseElementIterator(SMDSAbs_Face)->more() &&
1516                        n2->GetInverseElementIterator(SMDSAbs_Face)->more() );
1517     }
1518     if ( nodesOfFaces )
1519     {
1520       if ( helper2.IsRealSeam( e2 )) {
1521         seam1 = e1; seam2 = e2;
1522       }
1523       else {
1524         edge1 = e1; edge2 = e2;
1525       }
1526     }
1527     else {
1528       anyEdge1 = e1; anyEdge2 = e2;
1529     }
1530   } while ( edge2.IsNull() && eE.More() );
1531   //
1532   if ( edge2.IsNull() ) {
1533     edge1 = seam1; edge2 = seam2;
1534   }
1535   bool hasNodesOnEdge = (! edge2.IsNull() );
1536   if ( !hasNodesOnEdge ) {
1537     // 0020338 - nb segments == 1
1538     edge1 = anyEdge1; edge2 = anyEdge2;
1539   }
1540
1541   // get 2 matching vertices
1542   TopoDS_Vertex V2 = TopExp::FirstVertex( TopoDS::Edge( edge2 ));
1543   if ( !assocMap.IsBound( V2 ))
1544     RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
1545   TopoDS_Vertex V1 = TopoDS::Vertex( assocMap( V2 ));
1546
1547   // nodes on vertices
1548   const SMDS_MeshNode* vNode1 = SMESH_Algo::VertexNode( V1, meshDS1 );
1549   const SMDS_MeshNode* vNode2 = SMESH_Algo::VertexNode( V2, meshDS2 );
1550   if ( !vNode1 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS1->ShapeToIndex( V1 ));
1551   if ( !vNode2 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS2->ShapeToIndex( V2 ));
1552
1553   // nodes on edges linked with nodes on vertices
1554   const SMDS_MeshNode* nullNode = 0;
1555   vector< const SMDS_MeshNode*> eNode1( 2, nullNode );
1556   vector< const SMDS_MeshNode*> eNode2( 2, nullNode );
1557   if ( hasNodesOnEdge )
1558   {
1559     int nbNodeToGet = 1;
1560     if ( IsClosedEdge( edge1 ) || IsClosedEdge( edge2 ) )
1561       nbNodeToGet = 2;
1562     for ( int is2 = 0; is2 < 2; ++is2 )
1563     {
1564       TopoDS_Edge &     edge  = is2 ? edge2 : edge1;
1565       SMESHDS_Mesh *    smDS  = is2 ? meshDS2 : meshDS1;
1566       SMESHDS_SubMesh* edgeSM = smDS->MeshElements( edge );
1567       // nodes linked with ones on vertices
1568       const SMDS_MeshNode*           vNode = is2 ? vNode2 : vNode1;
1569       vector< const SMDS_MeshNode*>& eNode = is2 ? eNode2 : eNode1;
1570       int nbGotNode = 0;
1571       SMDS_ElemIteratorPtr vElem = vNode->GetInverseElementIterator(SMDSAbs_Edge);
1572       while ( vElem->more() && nbGotNode != nbNodeToGet ) {
1573         const SMDS_MeshElement* elem = vElem->next();
1574         if ( edgeSM->Contains( elem ))
1575           eNode[ nbGotNode++ ] = 
1576             ( elem->GetNode(0) == vNode ) ? elem->GetNode(1) : elem->GetNode(0);
1577       }
1578       if ( nbGotNode > 1 ) // sort found nodes by param on edge
1579       {
1580         SMESH_MesherHelper* helper = is2 ? &helper2 : &helper1;
1581         double u0 = helper->GetNodeU( edge, eNode[ 0 ]);
1582         double u1 = helper->GetNodeU( edge, eNode[ 1 ]);
1583         if ( u0 > u1 ) std::swap( eNode[ 0 ], eNode[ 1 ]);
1584       }
1585       if ( nbGotNode == 0 )
1586         RETURN_BAD_RESULT("Found no nodes on edge " << smDS->ShapeToIndex( edge ) <<
1587                           " linked to " << vNode );
1588     }
1589   }
1590   else // 0020338 - nb segments == 1
1591   {
1592     // get 2 other matching vertices
1593     V2 = TopExp::LastVertex( TopoDS::Edge( edge2 ));
1594     if ( !assocMap.IsBound( V2 ))
1595       RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
1596     V1 = TopoDS::Vertex( assocMap( V2 ));
1597
1598     // nodes on vertices
1599     eNode1[0] = SMESH_Algo::VertexNode( V1, meshDS1 );
1600     eNode2[0] = SMESH_Algo::VertexNode( V2, meshDS2 );
1601     if ( !eNode1[0] ) RETURN_BAD_RESULT("No node on vertex #" << meshDS1->ShapeToIndex( V1 ));
1602     if ( !eNode2[0] ) RETURN_BAD_RESULT("No node on vertex #" << meshDS2->ShapeToIndex( V2 ));
1603   }
1604
1605   // 2. face sets
1606
1607   set<const SMDS_MeshElement*> Elems1, Elems2;
1608   for ( int is2 = 0; is2 < 2; ++is2 )
1609   {
1610     set<const SMDS_MeshElement*> & elems = is2 ? Elems2 : Elems1;
1611     SMESHDS_SubMesh*                  sm = is2 ? SM2 : SM1;
1612     SMESH_MesherHelper*           helper = is2 ? &helper2 : &helper1;
1613     const TopoDS_Face &             face = is2 ? face2 : face1;
1614     SMDS_ElemIteratorPtr eIt = sm->GetElements();
1615
1616     if ( !helper->IsRealSeam( is2 ? edge2 : edge1 ))
1617     {
1618       while ( eIt->more() ) elems.insert( eIt->next() );
1619     }
1620     else
1621     {
1622       // the only suitable edge is seam, i.e. it is a sphere.
1623       // FindMatchingNodes() will not know which way to go from any edge.
1624       // So we ignore all faces having nodes on edges or vertices except
1625       // one of faces sharing current start nodes
1626
1627       // find a face to keep
1628       const SMDS_MeshElement* faceToKeep = 0;
1629       const SMDS_MeshNode* vNode = is2 ? vNode2 : vNode1;
1630       const SMDS_MeshNode* eNode = is2 ? eNode2[0] : eNode1[0];
1631       TIDSortedElemSet inSet, notInSet;
1632
1633       const SMDS_MeshElement* f1 =
1634         SMESH_MeshEditor::FindFaceInSet( vNode, eNode, inSet, notInSet );
1635       if ( !f1 ) RETURN_BAD_RESULT("The first face on seam not found");
1636       notInSet.insert( f1 );
1637
1638       const SMDS_MeshElement* f2 =
1639         SMESH_MeshEditor::FindFaceInSet( vNode, eNode, inSet, notInSet );
1640       if ( !f2 ) RETURN_BAD_RESULT("The second face on seam not found");
1641
1642       // select a face with less UV of vNode
1643       const SMDS_MeshNode* notSeamNode[2] = {0, 0};
1644       for ( int iF = 0; iF < 2; ++iF ) {
1645         const SMDS_MeshElement* f = ( iF ? f2 : f1 );
1646         for ( int i = 0; !notSeamNode[ iF ] && i < f->NbNodes(); ++i ) {
1647           const SMDS_MeshNode* node = f->GetNode( i );
1648           if ( !helper->IsSeamShape( node->GetPosition()->GetShapeId() ))
1649             notSeamNode[ iF ] = node;
1650         }
1651       }
1652       gp_Pnt2d uv1 = helper->GetNodeUV( face, vNode, notSeamNode[0] );
1653       gp_Pnt2d uv2 = helper->GetNodeUV( face, vNode, notSeamNode[1] );
1654       if ( uv1.X() + uv1.Y() > uv2.X() + uv2.Y() )
1655         faceToKeep = f2;
1656       else
1657         faceToKeep = f1;
1658
1659       // fill elem set
1660       elems.insert( faceToKeep );
1661       while ( eIt->more() ) {
1662         const SMDS_MeshElement* f = eIt->next();
1663         int nbNodes = f->NbNodes();
1664         if ( f->IsQuadratic() )
1665           nbNodes /= 2;
1666         bool onBnd = false;
1667         for ( int i = 0; !onBnd && i < nbNodes; ++i ) {
1668           const SMDS_MeshNode* node = f->GetNode( i );
1669           onBnd = ( node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE);
1670         }
1671         if ( !onBnd )
1672           elems.insert( f );
1673       }
1674       // add also faces adjacent to faceToKeep
1675       int nbNodes = faceToKeep->NbNodes();
1676       if ( faceToKeep->IsQuadratic() ) nbNodes /= 2;
1677       notInSet.insert( f1 );
1678       notInSet.insert( f2 );
1679       for ( int i = 0; i < nbNodes; ++i ) {
1680         const SMDS_MeshNode* n1 = faceToKeep->GetNode( i );
1681         const SMDS_MeshNode* n2 = faceToKeep->GetNode( i+1 % nbNodes );
1682         f1 = SMESH_MeshEditor::FindFaceInSet( n1, n2, inSet, notInSet );
1683         if ( f1 )
1684           elems.insert( f1 );
1685       }
1686     } // case on a sphere
1687   } // loop on 2 faces
1688
1689   //  int quadFactor = (*Elems1.begin())->IsQuadratic() ? 2 : 1;
1690
1691   node1To2Map.clear();
1692   int res = SMESH_MeshEditor::FindMatchingNodes( Elems1, Elems2,
1693                                                  vNode1, vNode2,
1694                                                  eNode1[0], eNode2[0],
1695                                                  node1To2Map);
1696   if ( res != SMESH_MeshEditor::SEW_OK )
1697     RETURN_BAD_RESULT("FindMatchingNodes() result " << res );
1698
1699   // On a sphere, add matching nodes on the edge
1700
1701   if ( helper1.IsRealSeam( edge1 ))
1702   {
1703     // sort nodes on edges by param on edge
1704     map< double, const SMDS_MeshNode* > u2nodesMaps[2];
1705     for ( int is2 = 0; is2 < 2; ++is2 )
1706     {
1707       TopoDS_Edge &     edge  = is2 ? edge2 : edge1;
1708       SMESHDS_Mesh *    smDS  = is2 ? meshDS2 : meshDS1;
1709       SMESHDS_SubMesh* edgeSM = smDS->MeshElements( edge );
1710       map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[ is2 ];
1711
1712       SMDS_NodeIteratorPtr nIt = edgeSM->GetNodes();
1713       while ( nIt->more() ) {
1714         const SMDS_MeshNode* node = nIt->next();
1715         const SMDS_EdgePosition* pos =
1716           static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
1717         pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
1718       }
1719       if ( pos2nodes.size() != edgeSM->NbNodes() )
1720         RETURN_BAD_RESULT("Equal params of nodes on edge "
1721                           << smDS->ShapeToIndex( edge ) << " of face " << is2 );
1722     }
1723     if ( u2nodesMaps[0].size() != u2nodesMaps[1].size() )
1724       RETURN_BAD_RESULT("Different nb of new nodes on edges or wrong params");
1725
1726     // compare edge orientation
1727     double u1 = helper1.GetNodeU( edge1, vNode1 );
1728     double u2 = helper2.GetNodeU( edge2, vNode2 );
1729     bool isFirst1 = ( u1 < u2nodesMaps[0].begin()->first );
1730     bool isFirst2 = ( u2 < u2nodesMaps[1].begin()->first );
1731     bool reverse ( isFirst1 != isFirst2 );
1732
1733     // associate matching nodes
1734     map< double, const SMDS_MeshNode* >::iterator u_Node1, u_Node2, end1;
1735     map< double, const SMDS_MeshNode* >::reverse_iterator uR_Node2;
1736     u_Node1 = u2nodesMaps[0].begin();
1737     u_Node2 = u2nodesMaps[1].begin();
1738     uR_Node2 = u2nodesMaps[1].rbegin();
1739     end1 = u2nodesMaps[0].end();
1740     for ( ; u_Node1 != end1; ++u_Node1 ) {
1741       const SMDS_MeshNode* n1 = u_Node1->second;
1742       const SMDS_MeshNode* n2 = ( reverse ? (uR_Node2++)->second : (u_Node2++)->second );
1743       node1To2Map.insert( make_pair( n1, n2 ));
1744     }
1745
1746     // associate matching nodes on the last vertices
1747     V2 = TopExp::LastVertex( TopoDS::Edge( edge2 ));
1748     if ( !assocMap.IsBound( V2 ))
1749       RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
1750     V1 = TopoDS::Vertex( assocMap( V2 ));
1751     vNode1 = SMESH_Algo::VertexNode( V1, meshDS1 );
1752     vNode2 = SMESH_Algo::VertexNode( V2, meshDS2 );
1753     if ( !vNode1 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS1->ShapeToIndex( V1 ));
1754     if ( !vNode2 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS2->ShapeToIndex( V2 ));
1755     node1To2Map.insert( make_pair( vNode1, vNode2 ));
1756   }
1757
1758 // don't know why this condition is usually true :(
1759 //   if ( node1To2Map.size() * quadFactor < SM1->NbNodes() )
1760 //     MESSAGE("FindMatchingNodes() found too few node pairs starting from nodes ("
1761 //             << vNode1->GetID() << " - " << eNode1[0]->GetID() << ") ("
1762 //             << vNode2->GetID() << " - " << eNode2[0]->GetID() << "):"
1763 //             << node1To2Map.size() * quadFactor << " < " << SM1->NbNodes());
1764   
1765   return true;
1766 }
1767
1768 //================================================================================
1769 /*!
1770  * \brief Check if the first and last vertices of an edge are the same
1771  * \param anEdge - the edge to check
1772  * \retval bool - true if same
1773  */
1774 //================================================================================
1775
1776 bool StdMeshers_ProjectionUtils::IsClosedEdge( const TopoDS_Edge& anEdge )
1777 {
1778   return TopExp::FirstVertex( anEdge ).IsSame( TopExp::LastVertex( anEdge ));
1779 }
1780
1781 //================================================================================
1782   /*!
1783    * \brief Return any subshape of a face belonging to the outer wire
1784     * \param face - the face
1785     * \param type - type of subshape to return
1786     * \retval TopoDS_Shape - the found subshape
1787    */
1788 //================================================================================
1789
1790 TopoDS_Shape StdMeshers_ProjectionUtils::OuterShape( const TopoDS_Face& face,
1791                                                      TopAbs_ShapeEnum   type)
1792 {
1793   TopExp_Explorer exp( BRepTools::OuterWire( face ), type );
1794   if ( exp.More() )
1795     return exp.Current();
1796   return TopoDS_Shape();
1797 }
1798
1799 //================================================================================
1800   /*!
1801    * \brief Check that submesh is computed and try to compute it if is not
1802     * \param sm - submesh to compute
1803     * \param iterationNb - int used to stop infinite recursive call
1804     * \retval bool - true if computed
1805    */
1806 //================================================================================
1807
1808 bool StdMeshers_ProjectionUtils::MakeComputed(SMESH_subMesh * sm, const int iterationNb)
1809 {
1810   if ( iterationNb > 10 )
1811     RETURN_BAD_RESULT("Infinite recursive projection");
1812   if ( !sm )
1813     RETURN_BAD_RESULT("NULL submesh");
1814   if ( sm->IsMeshComputed() )
1815     return true;
1816
1817   SMESH_Mesh* mesh = sm->GetFather();
1818   SMESH_Gen* gen   = mesh->GetGen();
1819   SMESH_Algo* algo = gen->GetAlgo( *mesh, sm->GetSubShape() );
1820   if ( !algo )
1821   {
1822     if ( sm->GetSubShape().ShapeType() != TopAbs_COMPOUND )
1823       RETURN_BAD_RESULT("No algo assigned to submesh " << sm->GetId());
1824     // group
1825     bool computed = true;
1826     for ( TopoDS_Iterator grMember( sm->GetSubShape() ); grMember.More(); grMember.Next())
1827       if ( SMESH_subMesh* grSub = mesh->GetSubMesh( grMember.Value() ))
1828         if ( !MakeComputed( grSub, iterationNb + 1 ))
1829           computed = false;
1830     return computed;
1831   }
1832
1833   string algoType = algo->GetName();
1834   if ( algoType.substr(0, 11) != "Projection_")
1835     return gen->Compute( *mesh, sm->GetSubShape() );
1836
1837   // try to compute source mesh
1838
1839   const list <const SMESHDS_Hypothesis *> & hyps =
1840     algo->GetUsedHypothesis( *mesh, sm->GetSubShape() );
1841
1842   TopoDS_Shape srcShape;
1843   SMESH_Mesh* srcMesh = 0;
1844   list <const SMESHDS_Hypothesis*>::const_iterator hIt = hyps.begin();
1845   for ( ; srcShape.IsNull() && hIt != hyps.end(); ++hIt ) {
1846     string hypName = (*hIt)->GetName();
1847     if ( hypName == "ProjectionSource1D" ) {
1848       const StdMeshers_ProjectionSource1D * hyp =
1849         static_cast<const StdMeshers_ProjectionSource1D*>( *hIt );
1850       srcShape = hyp->GetSourceEdge();
1851       srcMesh = hyp->GetSourceMesh();
1852     }
1853     else if ( hypName == "ProjectionSource2D" ) {
1854       const StdMeshers_ProjectionSource2D * hyp =
1855         static_cast<const StdMeshers_ProjectionSource2D*>( *hIt );
1856       srcShape = hyp->GetSourceFace();
1857       srcMesh = hyp->GetSourceMesh();
1858     }
1859     else if ( hypName == "ProjectionSource3D" ) {
1860       const StdMeshers_ProjectionSource3D * hyp =
1861         static_cast<const StdMeshers_ProjectionSource3D*>( *hIt );
1862       srcShape = hyp->GetSource3DShape();
1863       srcMesh = hyp->GetSourceMesh();
1864     }
1865   }
1866   if ( srcShape.IsNull() ) // no projection source defined
1867     return gen->Compute( *mesh, sm->GetSubShape() );
1868
1869   if ( srcShape.IsSame( sm->GetSubShape() ))
1870     RETURN_BAD_RESULT("Projection from self");
1871     
1872   if ( !srcMesh )
1873     srcMesh = mesh;
1874
1875   if ( MakeComputed( srcMesh->GetSubMesh( srcShape ), iterationNb + 1 ))
1876     return gen->Compute( *mesh, sm->GetSubShape() );
1877
1878   return false;
1879 }
1880
1881 //================================================================================
1882 /*!
1883  * \brief Count nb of subshapes
1884  * \param shape - the shape
1885  * \param type - the type of subshapes to count
1886  * \retval int - the calculated number
1887  */
1888 //================================================================================
1889
1890 int StdMeshers_ProjectionUtils::Count(const TopoDS_Shape&    shape,
1891                                       const TopAbs_ShapeEnum type,
1892                                       const bool             ignoreSame)
1893 {
1894   if ( ignoreSame ) {
1895     TopTools_IndexedMapOfShape map;
1896     TopExp::MapShapes( shape, type, map );
1897     return map.Extent();
1898   }
1899   else {
1900     int nb = 0;
1901     for ( TopExp_Explorer exp( shape, type ); exp.More(); exp.Next() )
1902       ++nb;
1903     return nb;
1904   }
1905 }
1906
1907 //================================================================================
1908 /*!
1909  * \brief Return true if edge is a boundary of edgeContainer
1910  */
1911 //================================================================================
1912
1913 bool StdMeshers_ProjectionUtils::IsBoundaryEdge(const TopoDS_Edge&  edge,
1914                                                 const TopoDS_Shape& edgeContainer,
1915                                                 SMESH_Mesh&         mesh)
1916 {
1917   TopTools_IndexedMapOfShape facesOfEdgeContainer, facesNearEdge;
1918   TopExp::MapShapes( edgeContainer, TopAbs_FACE, facesOfEdgeContainer );
1919
1920   const TopTools_ListOfShape& EAncestors = mesh.GetAncestors(edge);
1921   TopTools_ListIteratorOfListOfShape itea(EAncestors);
1922   for(; itea.More(); itea.Next()) {
1923     if( itea.Value().ShapeType() == TopAbs_FACE &&
1924         facesOfEdgeContainer.Contains( itea.Value() ))
1925     {
1926       facesNearEdge.Add( itea.Value() );
1927       if ( facesNearEdge.Extent() > 1 )
1928         return false;
1929     }
1930   }
1931   return ( facesNearEdge.Extent() == 1 );
1932 }
1933
1934
1935 namespace {
1936
1937   SMESH_subMeshEventListener* GetSrcSubMeshListener();
1938
1939   //================================================================================
1940   /*!
1941    * \brief Listener that resets an event listener on source submesh when 
1942    * "ProjectionSource*D" hypothesis is modified
1943    */
1944   //================================================================================
1945
1946   struct HypModifWaiter: SMESH_subMeshEventListener
1947   {
1948     HypModifWaiter():SMESH_subMeshEventListener(0){} // won't be deleted by submesh
1949
1950     void ProcessEvent(const int event, const int eventType, SMESH_subMesh* subMesh,
1951                       EventListenerData*, const SMESH_Hypothesis*)
1952     {
1953       if ( event     == SMESH_subMesh::MODIF_HYP &&
1954            eventType == SMESH_subMesh::ALGO_EVENT)
1955       {
1956         // delete current source listener
1957         subMesh->DeleteEventListener( GetSrcSubMeshListener() );
1958         // let algo set a new one
1959         SMESH_Gen* gen = subMesh->GetFather()->GetGen();
1960         if ( SMESH_Algo* algo = gen->GetAlgo( *subMesh->GetFather(),
1961                                               subMesh->GetSubShape() ))
1962           algo->SetEventListener( subMesh );
1963       }
1964     }
1965   };
1966   //================================================================================
1967   /*!
1968    * \brief return static HypModifWaiter
1969    */
1970   //================================================================================
1971
1972   SMESH_subMeshEventListener* GetHypModifWaiter() {
1973     static HypModifWaiter aHypModifWaiter;
1974     return &aHypModifWaiter;
1975   }
1976   //================================================================================
1977   /*!
1978    * \brief return static listener for source shape submeshes
1979    */
1980   //================================================================================
1981
1982   SMESH_subMeshEventListener* GetSrcSubMeshListener() {
1983     static SMESH_subMeshEventListener srcListener(0); // won't be deleted by submesh
1984     return &srcListener;
1985   }
1986 }
1987
1988 //================================================================================
1989 /*!
1990  * \brief Set event listeners to submesh with projection algo
1991  * \param subMesh - submesh with projection algo
1992  * \param srcShape - source shape
1993  * \param srcMesh - source mesh
1994  */
1995 //================================================================================
1996
1997 void StdMeshers_ProjectionUtils::SetEventListener(SMESH_subMesh* subMesh,
1998                                                   TopoDS_Shape   srcShape,
1999                                                   SMESH_Mesh*    srcMesh)
2000 {
2001   // Set listener that resets an event listener on source submesh when
2002   // "ProjectionSource*D" hypothesis is modified since source shape can be changed
2003   subMesh->SetEventListener( GetHypModifWaiter(),0,subMesh);
2004
2005   // Set an event listener to submesh of the source shape
2006   if ( !srcShape.IsNull() )
2007   {
2008     if ( !srcMesh )
2009       srcMesh = subMesh->GetFather();
2010
2011     SMESH_subMesh* srcShapeSM = srcMesh->GetSubMesh( srcShape );
2012
2013     if ( srcShapeSM != subMesh ) {
2014       if ( srcShapeSM->GetSubMeshDS() &&
2015            srcShapeSM->GetSubMeshDS()->IsComplexSubmesh() )
2016       {  // source shape is a group
2017         TopExp_Explorer it(srcShapeSM->GetSubShape(), // explore the group into subshapes...
2018                            subMesh->GetSubShape().ShapeType()); // ...of target shape type
2019         for (; it.More(); it.Next())
2020         {
2021           SMESH_subMesh* srcSM = srcMesh->GetSubMesh( it.Current() );
2022           if ( srcSM != subMesh )
2023           {
2024             SMESH_subMeshEventListenerData* data =
2025               srcSM->GetEventListenerData(GetSrcSubMeshListener());
2026             if ( data )
2027               data->mySubMeshes.push_back( subMesh );
2028             else
2029               data = SMESH_subMeshEventListenerData::MakeData( subMesh );
2030             subMesh->SetEventListener ( GetSrcSubMeshListener(), data, srcSM );
2031           }
2032         }
2033       }
2034       else
2035       {
2036         subMesh->SetEventListener( GetSrcSubMeshListener(),
2037                                    SMESH_subMeshEventListenerData::MakeData( subMesh ),
2038                                    srcShapeSM );
2039       }
2040     }
2041   }
2042 }