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