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