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