Salome HOME
fix association of faces with 2 edges
[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
29 #include "StdMeshers_ProjectionUtils.hxx"
30
31 #include "StdMeshers_ProjectionSource1D.hxx"
32 #include "StdMeshers_ProjectionSource2D.hxx"
33 #include "StdMeshers_ProjectionSource3D.hxx"
34
35 #include "SMESH_Algo.hxx"
36 #include "SMESH_Block.hxx"
37 #include "SMESH_Gen.hxx"
38 #include "SMESH_Hypothesis.hxx"
39 #include "SMESH_IndexedDataMapOfShapeIndexedMapOfShape.hxx"
40 #include "SMESH_Mesh.hxx"
41 #include "SMESH_MeshEditor.hxx"
42 #include "SMESH_subMesh.hxx"
43 #include "SMESH_subMeshEventListener.hxx"
44 #include "SMDS_EdgePosition.hxx"
45
46 #include "utilities.h"
47
48 #include <BRepAdaptor_Curve.hxx>
49 #include <BRepTools.hxx>
50 #include <BRepTools_WireExplorer.hxx>
51 #include <BRep_Tool.hxx>
52 #include <Bnd_Box.hxx>
53 #include <TopAbs.hxx>
54 #include <TopTools_Array1OfShape.hxx>
55 #include <TopTools_DataMapOfShapeShape.hxx>
56 #include <TopTools_ListIteratorOfListOfShape.hxx>
57 #include <TopTools_ListOfShape.hxx>
58 #include <TopTools_MapOfShape.hxx>
59 #include <TopoDS_Shape.hxx>
60 #include <gp_Ax3.hxx>
61 #include <gp_Pnt.hxx>
62 #include <gp_Trsf.hxx>
63 #include <gp_Vec.hxx>
64
65
66 #define RETURN_BAD_RESULT(msg) { MESSAGE(msg); return false; }
67 #define SHOW_VERTEX(v,msg) // { \
68 //  if ( v.IsNull() ) cout << msg << " NULL SHAPE" << endl; \
69 // else if (v.ShapeType() == TopAbs_VERTEX) {\
70 //   gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( v ));\
71 //   cout << msg << (v).TShape().operator->()<<" ( " <<p.X()<<", "<<p.Y()<<", "<<p.Z()<<" )"<<endl;}\
72 // else {\
73 // cout << msg << " "; TopAbs::Print(v.ShapeType(),cout) <<" "<<(v).TShape().operator->()<<endl;}\
74 // }
75 #define SHOW_LIST(msg,l) \
76 // { \
77 //     cout << msg << " ";\
78 //     list< TopoDS_Edge >::const_iterator e = l.begin();\
79 //     for ( int i = 0; e != l.end(); ++e, ++i ) {\
80 //       cout << i << "V (" << TopExp::FirstVertex( *e, true ).TShape().operator->() << ") "\
81 //            << i << "E (" << e->TShape().operator->() << "); "; }\
82 //     cout << endl;\
83 //   }
84
85 namespace {
86   //================================================================================
87   /*!
88    * \brief Reverse order of edges in a list and their orientation
89     * \param edges - list of edges to reverse
90     * \param nbEdges - number of edges to reverse
91    */
92   //================================================================================
93
94   void Reverse( list< TopoDS_Edge > & edges, const int nbEdges )
95   {
96     SHOW_LIST("BEFORE REVERSE", edges);
97
98     list< TopoDS_Edge >::iterator eIt = edges.begin();
99     if ( edges.size() == nbEdges )
100     {
101       edges.reverse();
102     }
103     else  // reverse only the given nb of edges
104     {
105       // look for the last edge to be reversed
106       list< TopoDS_Edge >::iterator eBackIt = edges.begin();
107       for ( int i = 1; i < nbEdges; ++i )
108         ++eBackIt;
109       // reverse
110       while ( eIt != eBackIt ) {
111         std::swap( *eIt, *eBackIt );
112         SHOW_LIST("# AFTER SWAP", edges)
113         if ( (++eIt) != eBackIt )
114           --eBackIt;
115       }
116     }
117     for ( eIt = edges.begin(); eIt != edges.end(); ++eIt )
118       eIt->Reverse();
119     SHOW_LIST("ATFER REVERSE", edges)
120   }
121
122   //================================================================================
123   /*!
124    * \brief Check if propagation is possible
125     * \param theMesh1 - source mesh
126     * \param theMesh2 - target mesh
127     * \retval bool - true if possible
128    */
129   //================================================================================
130
131   bool IsPropagationPossible( SMESH_Mesh* theMesh1, SMESH_Mesh* theMesh2 )
132   {
133     if ( theMesh1 != theMesh2 ) {
134       TopoDS_Shape mainShape1 = theMesh1->GetMeshDS()->ShapeToMesh();
135       TopoDS_Shape mainShape2 = theMesh2->GetMeshDS()->ShapeToMesh();
136       return mainShape1.IsSame( mainShape2 );
137     }
138     return true;
139   }
140
141   //================================================================================
142   /*!
143    * \brief Fix up association of edges in faces by possible propagation
144     * \param nbEdges - nb of edges in an outer wire
145     * \param edges1 - edges of one face
146     * \param edges2 - matching edges of another face
147     * \param theMesh1 - mesh 1
148     * \param theMesh2 - mesh 2
149     * \retval bool - true if association was fixed
150    */
151   //================================================================================
152
153   bool FixAssocByPropagation( const int             nbEdges,
154                               list< TopoDS_Edge > & edges1,
155                               list< TopoDS_Edge > & edges2,
156                               SMESH_Mesh*           theMesh1,
157                               SMESH_Mesh*           theMesh2)
158   {
159     if ( nbEdges == 2 && IsPropagationPossible( theMesh1, theMesh2 ) )
160     {
161       list< TopoDS_Edge >::iterator eIt2 = ++edges2.begin(); // 2nd edge of the 2nd face
162       TopoDS_Edge edge2 =
163         StdMeshers_ProjectionUtils::GetPropagationEdge( theMesh1, *eIt2, edges1.front() );
164       if ( !edge2.IsNull() ) { // propagation found for the second edge
165         Reverse( edges2, nbEdges );
166         return true;
167       }
168     }
169     return false;
170   }
171 }
172
173 //=======================================================================
174 /*!
175  * \brief Looks for association of all subshapes of two shapes
176  * \param theShape1 - shape 1
177  * \param theMesh1 - mesh built on shape 1
178  * \param theShape2 - shape 2
179  * \param theMesh2 - mesh built on shape 2
180  * \param theAssociation - association map to be filled that may
181  *                         contain association of one or two pairs of vertices
182  * \retval bool - true if association found
183  */
184 //=======================================================================
185
186 bool StdMeshers_ProjectionUtils::FindSubShapeAssociation(const TopoDS_Shape& theShape1,
187                                                          SMESH_Mesh*         theMesh1,
188                                                          const TopoDS_Shape& theShape2,
189                                                          SMESH_Mesh*         theMesh2,
190                                                          TShapeShapeMap &    theMap)
191 {
192   if ( theShape1.ShapeType() != theShape2.ShapeType() )
193     RETURN_BAD_RESULT("Different shape types");
194
195   bool bidirect = ( !theShape1.IsSame( theShape2 ));
196   if ( !theMap.IsEmpty())
197   {
198     switch ( theShape1.ShapeType() ) {
199
200     case TopAbs_EDGE: {
201       // ----------------------------------------------------------------------
202       if ( theMap.Extent() != 2 )
203         RETURN_BAD_RESULT("Wrong map extent " << theMap.Extent() );
204       TopoDS_Edge edge1 = TopoDS::Edge( theShape1 );
205       TopoDS_Edge edge2 = TopoDS::Edge( theShape2 );
206       TopoDS_Vertex VV1[2], VV2[2];
207       TopExp::Vertices( edge1, VV1[0], VV1[1] );
208       TopExp::Vertices( edge2, VV2[0], VV2[1] );
209       int i1 = 0, i2 = 0;
210       if ( theMap.IsBound( VV1[ i1 ] )) i1 = 1;
211       if ( theMap.IsBound( VV2[ i2 ] )) i2 = 1;
212       InsertAssociation( VV1[ i1 ], VV2[ i2 ], theMap, bidirect);
213       return true;
214     }
215
216     case TopAbs_FACE: {
217       // ----------------------------------------------------------------------
218       TopoDS_Face face1 = TopoDS::Face( theShape1 );
219       TopoDS_Face face2 = TopoDS::Face( theShape2 );
220
221       TopoDS_Vertex VV1[2], VV2[2];
222       // find a not closed edge of face1 both vertices of which are associated
223       int nbEdges = 0;
224       TopExp_Explorer exp ( face1, TopAbs_EDGE );
225       for ( ; VV2[ 1 ].IsNull() && exp.More(); exp.Next(), ++nbEdges ) {
226         TopExp::Vertices( TopoDS::Edge( exp.Current() ), VV1[0], VV1[1] );
227         if ( theMap.IsBound( VV1[0] ) ) {
228           VV2[ 0 ] = TopoDS::Vertex( theMap( VV1[0] ));
229           if ( theMap.IsBound( VV1[1] ) && !VV1[0].IsSame( VV1[1] ))
230             VV2[ 1 ] = TopoDS::Vertex( theMap( VV1[1] ));
231         }
232       }
233       if ( VV2[ 1 ].IsNull() ) { // 2 bound vertices not found
234         if ( nbEdges > 1 ) {
235           RETURN_BAD_RESULT("2 bound vertices not found" );
236         } else {
237           VV2[ 1 ] = VV2[ 0 ];
238         }
239       }
240       list< TopoDS_Edge > edges1, edges2;
241       int nbE = FindFaceAssociation( face1, VV1, face2, VV2, edges1, edges2 );
242       if ( !nbE ) RETURN_BAD_RESULT("FindFaceAssociation() failed");
243       FixAssocByPropagation( nbE, edges1, edges2, theMesh1, theMesh2 );
244
245       list< TopoDS_Edge >::iterator eIt1 = edges1.begin();
246       list< TopoDS_Edge >::iterator eIt2 = edges2.begin();
247       for ( ; eIt1 != edges1.end(); ++eIt1, ++eIt2 )
248       {
249         InsertAssociation( *eIt1, *eIt2, theMap, bidirect);
250         VV1[0] = TopExp::FirstVertex( *eIt1, true );
251         VV2[0] = TopExp::FirstVertex( *eIt2, true );
252         InsertAssociation( VV1[0], VV2[0], theMap, bidirect);
253       }
254       return true;
255     }
256
257     case TopAbs_SHELL:
258     case TopAbs_SOLID: {
259       // ----------------------------------------------------------------------
260       TopoDS_Vertex VV1[2], VV2[2];
261       // find a not closed edge of shape1 both vertices of which are associated
262       TopoDS_Edge edge1;
263       TopExp_Explorer exp ( theShape1, TopAbs_EDGE );
264       for ( ; VV2[ 1 ].IsNull() && exp.More(); exp.Next() ) {
265         edge1 = TopoDS::Edge( exp.Current() );
266         TopExp::Vertices( edge1 , VV1[0], VV1[1] );
267         if ( theMap.IsBound( VV1[0] )) {
268           VV2[ 0 ] = TopoDS::Vertex( theMap( VV1[0] ));
269           if ( theMap.IsBound( VV1[1] ) && !VV1[0].IsSame( VV1[1] ))
270             VV2[ 1 ] = TopoDS::Vertex( theMap( VV1[1] ));
271         }
272       }
273       if ( VV2[ 1 ].IsNull() ) // 2 bound vertices not found
274         RETURN_BAD_RESULT("2 bound vertices not found" );
275       TopoDS_Edge edge2 = GetEdgeByVertices( theMesh2, VV2[ 0 ], VV2[ 1 ]);
276       if ( edge2.IsNull() )
277         RETURN_BAD_RESULT("GetEdgeByVertices() failed");
278
279       // get a face sharing edge1
280       TopoDS_Shape F1, F2, FF2[2];
281       TopTools_ListIteratorOfListOfShape ancestIt = theMesh1->GetAncestors( edge1 );
282       for ( ; F1.IsNull() && ancestIt.More(); ancestIt.Next() )
283         if ( ancestIt.Value().ShapeType() == TopAbs_FACE )
284           F1 = ancestIt.Value().Oriented( TopAbs_FORWARD );
285       if ( F1.IsNull() )
286         RETURN_BAD_RESULT(" Face1 not found");
287
288       // get 2 faces sharing edge2
289       ancestIt = theMesh2->GetAncestors( edge2 );
290       for ( int i = 0; FF2[1].IsNull() && ancestIt.More(); ancestIt.Next() )
291         if ( ancestIt.Value().ShapeType() == TopAbs_FACE )
292           FF2[ i++ ] = ancestIt.Value().Oriented( TopAbs_FORWARD );
293       if ( FF2[1].IsNull() )
294         RETURN_BAD_RESULT("2 faces not found");
295
296       // get oriented edge1 and edge2 from F1 and FF2[0]
297       for ( exp.Init( F1, TopAbs_EDGE ); exp.More(); exp.Next() )
298         if ( edge1.IsSame( exp.Current() )) {
299           edge1 = TopoDS::Edge( exp.Current() );
300           break;
301         }
302       
303       for ( exp.Init( FF2[ 0 ], TopAbs_EDGE ); exp.More(); exp.Next() )
304         if ( edge2.IsSame( exp.Current() )) {
305           edge2 = TopoDS::Edge( exp.Current() );
306           break;
307         }
308
309       // compare first vertices of edge1 and edge2
310       TopExp::Vertices( edge1, VV1[0], VV1[1], true );
311       TopExp::Vertices( edge2, VV2[0], VV2[1], true );
312       F2 = FF2[ 0 ];
313       if ( !VV1[ 0 ].IsSame( theMap( VV2[ 0 ]))) {
314         F2 = FF2[ 1 ];
315         edge2.Reverse();
316       }
317
318       TopTools_MapOfShape boundEdges; 
319
320       // association of face subshapes and neighbour faces
321       list< pair < TopoDS_Face, TopoDS_Edge > > FE1, FE2;
322       list< pair < TopoDS_Face, TopoDS_Edge > >::iterator fe1, fe2;
323       FE1.push_back( make_pair( TopoDS::Face( F1 ), edge1 ));
324       FE2.push_back( make_pair( TopoDS::Face( F2 ), edge2 ));
325       for ( fe1 = FE1.begin(), fe2 = FE2.begin(); fe1 != FE1.end(); ++fe1, ++fe2 )
326       {
327         const TopoDS_Face& face1 = fe1->first;
328         if ( theMap.IsBound( face1 ) ) continue;
329         const TopoDS_Face& face2 = fe2->first;
330         edge1 = fe1->second;
331         edge2 = fe2->second;
332         TopExp::Vertices( edge1, VV1[0], VV1[1], true );
333         TopExp::Vertices( edge2, VV2[0], VV2[1], true );
334         list< TopoDS_Edge > edges1, edges2;
335         int nbE = FindFaceAssociation( face1, VV1, face2, VV2, edges1, edges2 );
336         if ( !nbE ) RETURN_BAD_RESULT("FindFaceAssociation() failed");
337         InsertAssociation( face1, face2, theMap, bidirect); // assoc faces
338         MESSAGE("Assoc FACE " << theMesh1->GetMeshDS()->ShapeToIndex( face1 )<<
339                 " to "        << theMesh2->GetMeshDS()->ShapeToIndex( face2 ));
340         if ( nbE == 2 && (edge1.IsSame( edges1.front())) != (edge2.IsSame( edges2.front())))
341         {
342           Reverse( edges2, nbE );
343         }
344         list< TopoDS_Edge >::iterator eIt1 = edges1.begin();
345         list< TopoDS_Edge >::iterator eIt2 = edges2.begin();
346         for ( ; eIt1 != edges1.end(); ++eIt1, ++eIt2 )
347         {
348           if ( !boundEdges.Add( *eIt1 )) continue; // already associated
349           InsertAssociation( *eIt1, *eIt2, theMap, bidirect);  // assoc edges
350           MESSAGE("Assoc edge " << theMesh1->GetMeshDS()->ShapeToIndex( *eIt1 )<<
351                   " to "        << theMesh2->GetMeshDS()->ShapeToIndex( *eIt2 ));
352           VV1[0] = TopExp::FirstVertex( *eIt1, true );
353           VV2[0] = TopExp::FirstVertex( *eIt2, true );
354           InsertAssociation( VV1[0], VV2[0], theMap, bidirect); // assoc vertices
355
356           // add adjacent faces to process
357           TopoDS_Face nextFace1 = GetNextFace( theMesh1, *eIt1, face1 );
358           TopoDS_Face nextFace2 = GetNextFace( theMesh2, *eIt2, face2 );
359           if ( !nextFace1.IsNull() && !nextFace2.IsNull() ) {
360             FE1.push_back( make_pair( nextFace1, *eIt1 ));
361             FE2.push_back( make_pair( nextFace2, *eIt2 ));
362           }
363         }
364       }
365       return true;
366     }
367     default:
368       RETURN_BAD_RESULT("Unexpected shape type");
369
370     } // end switch by shape type
371   } // end case of available initial vertex association
372
373   //----------------------------------------------------------------------
374   // NO INITIAL VERTEX ASSOCIATION
375   //----------------------------------------------------------------------
376
377   switch ( theShape1.ShapeType() ) {
378
379   case TopAbs_EDGE: {
380     // ----------------------------------------------------------------------
381     TopoDS_Edge edge1 = TopoDS::Edge( theShape1 );
382     TopoDS_Edge edge2 = TopoDS::Edge( theShape2 );
383     if ( IsPropagationPossible( theMesh1, theMesh2 ))
384     {
385       TopoDS_Edge prpEdge = GetPropagationEdge( theMesh1, edge2, edge1 );
386       if ( !prpEdge.IsNull() )
387       {
388         TopoDS_Vertex VV1[2], VV2[2];
389         TopExp::Vertices( edge1,   VV1[0], VV1[1], true );
390         TopExp::Vertices( prpEdge, VV2[0], VV2[1], true );
391         InsertAssociation( VV1[ 0 ], VV2[ 0 ], theMap, bidirect);
392         InsertAssociation( VV1[ 1 ], VV2[ 1 ], theMap, bidirect);
393         if ( VV1[0].IsSame( VV1[1] ) || // one of edges is closed
394              VV2[0].IsSame( VV2[1] ) )
395         {
396           InsertAssociation( edge1, prpEdge, theMap, bidirect); // insert with a proper orientation
397         }
398         return true; // done
399       }
400     }
401     if ( IsClosedEdge( edge1 ) && IsClosedEdge( edge2 ))
402     {
403       // TODO: find out a proper orientation (is it possible?)
404       InsertAssociation( edge1, edge2, theMap, bidirect); // insert with a proper orientation
405       InsertAssociation( TopExp::FirstVertex(edge1), TopExp::FirstVertex(edge2),
406                          theMap, bidirect);
407       return true; // done
408     }
409     break; // try by vertex closeness
410   }
411
412   case TopAbs_FACE: {
413     // ----------------------------------------------------------------------
414     if ( IsPropagationPossible( theMesh1, theMesh2 )) // try by propagation in one mesh
415     {
416       TopoDS_Face face1 = TopoDS::Face(theShape1);
417       TopoDS_Face face2 = TopoDS::Face(theShape2);
418       // get outer edge of theShape1
419       TopoDS_Edge edge1 = TopoDS::Edge( OuterShape( face1, TopAbs_EDGE ));
420       // find out if any edge of face2 is a propagation edge of outer edge1
421       for ( TopExp_Explorer exp( face2, TopAbs_EDGE ); exp.More(); exp.Next() ) {
422         TopoDS_Edge edge2 = TopoDS::Edge( exp.Current() );
423         edge2 = GetPropagationEdge( theMesh1, edge2, edge1 );
424         if ( !edge2.IsNull() ) // propagation found
425         {
426           TopoDS_Vertex VV1[2], VV2[2];
427           TopExp::Vertices( edge1, VV1[0], VV1[1], true );
428           TopExp::Vertices( edge2, VV2[0], VV2[1], true );
429           list< TopoDS_Edge > edges1, edges2;
430           int nbE = FindFaceAssociation( face1, VV1, face2, VV2, edges1, edges2 );
431           if ( !nbE ) RETURN_BAD_RESULT("FindFaceAssociation() failed");
432           if ( nbE == 2 ) // only 2 edges
433           {
434             // take care of proper association of propagated edges
435             bool same1 = edge1.IsSame( edges1.front() );
436             bool same2 = edge2.IsSame( edges2.front() );
437             if ( same1 != same2 )
438               Reverse(edges2, nbE);
439           }
440           // store association
441           list< TopoDS_Edge >::iterator eIt1 = edges1.begin();
442           list< TopoDS_Edge >::iterator eIt2 = edges2.begin();
443           for ( ; eIt1 != edges1.end(); ++eIt1, ++eIt2 )
444           {
445             InsertAssociation( *eIt1, *eIt2, theMap, bidirect);
446             VV1[0] = TopExp::FirstVertex( *eIt1, true );
447             VV2[0] = TopExp::FirstVertex( *eIt2, true );
448             InsertAssociation( VV1[0], VV2[0], theMap, bidirect);
449           }
450           return true;
451         }
452       }
453     }
454     break; // try by vertex closeness
455   }
456   default:;
457   }
458
459   // Find association by closeness of vertices
460   // ------------------------------------------
461
462   TopTools_IndexedMapOfShape vMap1, vMap2;
463   TopExp::MapShapes( theShape1, TopAbs_VERTEX, vMap1 );
464   TopExp::MapShapes( theShape2, TopAbs_VERTEX, vMap2 );
465
466   if ( vMap1.Extent() != vMap2.Extent() )
467     RETURN_BAD_RESULT("Different nb of vertices");
468
469   if ( vMap1.Extent() == 1 ) {
470     InsertAssociation( vMap1(1), vMap2(1), theMap, bidirect);
471     if ( theShape1.ShapeType() == TopAbs_EDGE )
472       return true;
473     return FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap);
474   }
475
476   // Find transformation to make the shapes be of similar size at same location
477
478   Bnd_Box box[2];
479   for ( int i = 1; i <= vMap1.Extent(); ++i ) {
480     box[ 0 ].Add( BRep_Tool::Pnt ( TopoDS::Vertex( vMap1( i ))));
481     box[ 1 ].Add( BRep_Tool::Pnt ( TopoDS::Vertex( vMap2( i ))));
482   }
483
484   gp_Pnt gc[2]; // box center
485   double x0,y0,z0, x1,y1,z1;
486   box[0].Get( x0,y0,z0, x1,y1,z1 );
487   gc[0] = 0.5 * ( gp_XYZ( x0,y0,z0 ) + gp_XYZ( x1,y1,z1 ));
488   box[1].Get( x0,y0,z0, x1,y1,z1 );
489   gc[1] = 0.5 * ( gp_XYZ( x0,y0,z0 ) + gp_XYZ( x1,y1,z1 ));
490
491   // 1 -> 2
492   gp_Vec vec01( gc[0], gc[1] );
493   double scale = sqrt( box[1].SquareExtent() / box[0].SquareExtent() );
494
495   // Find 2 closest vertices
496
497   TopoDS_Vertex VV1[2], VV2[2];
498   // get 2 linked vertices of shape 1 not belonging to an inner wire of a face
499   TopoDS_Shape edge = theShape1;
500   TopExp_Explorer expF( theShape1, TopAbs_FACE ), expE;
501   for ( ; expF.More(); expF.Next() ) {
502     edge.Nullify();
503     TopoDS_Shape wire = OuterShape( TopoDS::Face( expF.Current() ), TopAbs_WIRE );
504     for ( expE.Init( wire, TopAbs_EDGE ); edge.IsNull() && expE.More(); expE.Next() )
505       if ( !IsClosedEdge( TopoDS::Edge( expE.Current() )))
506         edge = expE.Current();
507     if ( !edge.IsNull() )
508       break;
509   }
510   if ( edge.IsNull() || edge.ShapeType() != TopAbs_EDGE )
511     RETURN_BAD_RESULT("Edge not found");
512
513   TopExp::Vertices( TopoDS::Edge( edge ), VV1[0], VV1[1]);
514   if ( VV1[0].IsSame( VV1[1] ))
515     RETURN_BAD_RESULT("Only closed edges");
516
517   // find vertices closest to 2 linked vertices of shape 1
518   for ( int i1 = 0; i1 < 2; ++i1 )
519   {
520     double dist2 = DBL_MAX;
521     gp_Pnt p1 = BRep_Tool::Pnt( VV1[ i1 ]);
522     p1.Translate( vec01 );
523     p1.Scale( gc[1], scale );
524     for ( int i2 = 1; i2 <= vMap2.Extent(); ++i2 )
525     {
526       TopoDS_Vertex V2 = TopoDS::Vertex( vMap2( i2 ));
527       gp_Pnt p2 = BRep_Tool::Pnt ( V2 );
528       double d2 = p1.SquareDistance( p2 );
529       if ( d2 < dist2 && !V2.IsSame( VV2[ 0 ])) {
530         VV2[ i1 ] = V2; dist2 = d2;
531       }
532     }
533   }
534
535   InsertAssociation( VV1[ 0 ], VV2 [ 0 ], theMap, bidirect);
536   InsertAssociation( VV1[ 1 ], VV2 [ 1 ], theMap, bidirect);
537   if ( theShape1.ShapeType() == TopAbs_EDGE )
538     return true;
539
540   return FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap );
541 }
542
543 //================================================================================
544 /*!
545  * \brief Find association of edges of faces
546  * \param face1 - face 1
547  * \param VV1 - vertices of face 1
548  * \param face2 - face 2
549  * \param VV2 - vertices of face 2 associated with oned of face 1
550  * \param edges1 - out list of edges of face 1
551  * \param edges2 - out list of edges of face 2
552  * \retval int - nb of edges in an outer wire in a success case, else zero
553  */
554 //================================================================================
555
556 int StdMeshers_ProjectionUtils::FindFaceAssociation(const TopoDS_Face& face1,
557                                                     TopoDS_Vertex      VV1[2],
558                                                     const TopoDS_Face& face2,
559                                                     TopoDS_Vertex      VV2[2],
560                                                     list< TopoDS_Edge > & edges1,
561                                                     list< TopoDS_Edge > & edges2)
562 {
563   edges1.clear();
564   edges2.clear();
565
566   list< int > nbVInW1, nbVInW2;
567   if ( SMESH_Block::GetOrderedEdges( face1, VV1[0], edges1, nbVInW1) !=
568        SMESH_Block::GetOrderedEdges( face2, VV2[0], edges2, nbVInW2) )
569     RETURN_BAD_RESULT("Different number of wires in faces ");
570
571   if ( nbVInW1.front() != nbVInW2.front() )
572     RETURN_BAD_RESULT("Different number of edges in faces: " <<
573                       nbVInW1.front() << " != " << nbVInW2.front());
574
575   // Define if we need to reverse one of wires to make edges in lists match each other
576
577   bool reverse = false;
578
579   list< TopoDS_Edge >::iterator eBackIt;
580   if ( !VV1[1].IsSame( TopExp::LastVertex( edges1.front(), true ))) {
581     reverse = true;
582     eBackIt = --edges1.end();
583     // check if the second vertex belongs to the first or last edge in the wire
584     if ( !VV1[1].IsSame( TopExp::FirstVertex( *eBackIt, true ))) {
585       bool KO = true; // belongs to none
586       if ( nbVInW1.size() > 1 ) { // several wires
587         eBackIt = edges1.begin();
588         for ( int i = 1; i < nbVInW1.front(); ++i ) ++eBackIt;
589         KO = !VV1[1].IsSame( TopExp::FirstVertex( *eBackIt, true ));
590       }
591       if ( KO )
592         RETURN_BAD_RESULT("GetOrderedEdges() failed");
593     }
594   }
595   eBackIt = --edges2.end();
596   if ( !VV2[1].IsSame( TopExp::LastVertex( edges2.front(), true ))) {
597     reverse = !reverse;
598     // check if the second vertex belongs to the first or last edge in the wire
599     if ( !VV2[1].IsSame( TopExp::FirstVertex( *eBackIt, true ))) {
600       bool KO = true; // belongs to none
601       if ( nbVInW2.size() > 1 ) { // several wires
602         eBackIt = edges2.begin();
603         for ( int i = 1; i < nbVInW2.front(); ++i ) ++eBackIt;
604         KO = !VV2[1].IsSame( TopExp::FirstVertex( *eBackIt, true ));
605       }
606       if ( KO )
607         RETURN_BAD_RESULT("GetOrderedEdges() failed");
608     }
609   }
610   if ( reverse )
611   {
612     Reverse( edges2 , nbVInW2.front());
613     if (( VV1[1].IsSame( TopExp::LastVertex( edges1.front(), true ))) !=
614         ( VV2[1].IsSame( TopExp::LastVertex( edges2.front(), true ))))
615       RETURN_BAD_RESULT("GetOrderedEdges() failed");
616   }
617   return nbVInW2.front();
618 }
619
620 //=======================================================================
621 //function : InitVertexAssociation
622 //purpose  : 
623 //=======================================================================
624
625 void StdMeshers_ProjectionUtils::InitVertexAssociation( const SMESH_Hypothesis* theHyp,
626                                                         TShapeShapeMap &        theAssociationMap)
627 {
628   string hypName = theHyp->GetName();
629   if ( hypName == "ProjectionSource1D" ) {
630     const StdMeshers_ProjectionSource1D * hyp =
631       static_cast<const StdMeshers_ProjectionSource1D*>( theHyp );
632     if ( hyp->HasVertexAssociation() ) {
633       InsertAssociation( hyp->GetSourceVertex(),hyp->GetTargetVertex(),theAssociationMap);
634     }
635   }
636   else if ( hypName == "ProjectionSource2D" ) {
637     const StdMeshers_ProjectionSource2D * hyp =
638       static_cast<const StdMeshers_ProjectionSource2D*>( theHyp );
639     if ( hyp->HasVertexAssociation() ) {
640       InsertAssociation( hyp->GetSourceVertex(1),hyp->GetTargetVertex(1),theAssociationMap);
641       InsertAssociation( hyp->GetSourceVertex(2),hyp->GetTargetVertex(2),theAssociationMap);
642     }
643   }
644   else if ( hypName == "ProjectionSource3D" ) {
645     const StdMeshers_ProjectionSource3D * hyp =
646       static_cast<const StdMeshers_ProjectionSource3D*>( theHyp );
647     if ( hyp->HasVertexAssociation() ) {
648       InsertAssociation( hyp->GetSourceVertex(1),hyp->GetTargetVertex(1),theAssociationMap);
649       InsertAssociation( hyp->GetSourceVertex(2),hyp->GetTargetVertex(2),theAssociationMap);
650     }
651   }
652 }
653
654 //=======================================================================
655 /*!
656  * \brief Inserts association theShape1 <-> theShape2 to TShapeShapeMap
657  * \param theShape1 - shape 1
658  * \param theShape2 - shape 2
659  * \param theAssociationMap - association map 
660  * \retval bool - true if there was no association for these shapes before
661  */
662 //=======================================================================
663
664 bool StdMeshers_ProjectionUtils::InsertAssociation( const TopoDS_Shape& theShape1,
665                                                     const TopoDS_Shape& theShape2,
666                                                     TShapeShapeMap &    theAssociationMap,
667                                                     const bool          theBidirectional)
668 {
669   if ( !theShape1.IsNull() && !theShape2.IsNull() ) {
670     SHOW_VERTEX(theShape1,"Assoc ");
671     SHOW_VERTEX(theShape2," to ");
672     bool isNew = ( theAssociationMap.Bind( theShape1, theShape2 ));
673     if ( theBidirectional )
674       theAssociationMap.Bind( theShape2, theShape1 );
675     return isNew;
676   }
677   return false;
678 }
679
680 //=======================================================================
681 //function : IsSubShape
682 //purpose  : 
683 //=======================================================================
684
685 bool StdMeshers_ProjectionUtils::IsSubShape( const TopoDS_Shape& shape,
686                                              SMESH_Mesh*         aMesh )
687 {
688   if ( shape.IsNull() || !aMesh )
689     return false;
690   return aMesh->GetMeshDS()->ShapeToIndex( shape );
691 }
692
693 //=======================================================================
694 //function : IsSubShape
695 //purpose  : 
696 //=======================================================================
697
698 bool StdMeshers_ProjectionUtils::IsSubShape( const TopoDS_Shape& shape,
699                                              const TopoDS_Shape& mainShape )
700 {
701   if ( !shape.IsNull() && !mainShape.IsNull() )
702   {
703     for ( TopExp_Explorer exp( mainShape, shape.ShapeType());
704           exp.More();
705           exp.Next() )
706       if ( shape.IsSame( exp.Current() ))
707         return true;
708   }
709   SCRUTE((shape.IsNull()));
710   SCRUTE((mainShape.IsNull()));
711   return false;
712 }
713
714
715 //=======================================================================
716 /*!
717  * \brief Finds an edge by its vertices in a main shape of the mesh
718  * \param aMesh - the mesh
719  * \param V1 - vertex 1
720  * \param V2 - vertex 2
721  * \retval TopoDS_Edge - found edge
722  */
723 //=======================================================================
724
725 TopoDS_Edge StdMeshers_ProjectionUtils::GetEdgeByVertices( SMESH_Mesh*          theMesh,
726                                                            const TopoDS_Vertex& theV1,
727                                                            const TopoDS_Vertex& theV2)
728 {
729   if ( theMesh && !theV1.IsNull() && !theV2.IsNull() )
730   {
731     TopTools_ListIteratorOfListOfShape ancestorIt( theMesh->GetAncestors( theV1 ));
732     for ( ; ancestorIt.More(); ancestorIt.Next() )
733       if ( ancestorIt.Value().ShapeType() == TopAbs_EDGE )
734         for ( TopExp_Explorer expV ( ancestorIt.Value(), TopAbs_VERTEX );
735               expV.More();
736               expV.Next() )
737           if ( theV2.IsSame( expV.Current() ))
738             return TopoDS::Edge( ancestorIt.Value() );
739   }
740   return TopoDS_Edge();
741 }
742
743 //================================================================================
744 /*!
745  * \brief Return another face sharing an edge
746  * \param aMesh - mesh
747  * \param edge - edge
748  * \param face - face
749  * \retval TopoDS_Face - found face
750  */
751 //================================================================================
752
753 TopoDS_Face StdMeshers_ProjectionUtils::GetNextFace( SMESH_Mesh*        mesh,
754                                                      const TopoDS_Edge& edge,
755                                                      const TopoDS_Face& face)
756 {
757   if ( mesh && !edge.IsNull() && !face.IsNull() )
758   {
759     TopTools_ListIteratorOfListOfShape ancestorIt( mesh->GetAncestors( edge ));
760     for ( ; ancestorIt.More(); ancestorIt.Next() )
761       if ( ancestorIt.Value().ShapeType() == TopAbs_FACE &&
762            !face.IsSame( ancestorIt.Value() ))
763         return TopoDS::Face( ancestorIt.Value() );
764   }
765   return TopoDS_Face();
766   
767 }
768
769 //================================================================================
770 /*!
771  * \brief Return a propagation edge
772  * \param aMesh - mesh
773  * \param theEdge - edge to find by propagation
774  * \param fromEdge - start edge for propagation
775  * \retval TopoDS_Edge - found edge
776  */
777 //================================================================================
778
779 TopoDS_Edge StdMeshers_ProjectionUtils::GetPropagationEdge( SMESH_Mesh*        aMesh,
780                                                             const TopoDS_Edge& theEdge,
781                                                             const TopoDS_Edge& fromEdge)
782 {
783   SMESH_IndexedMapOfShape aChain;
784   //aChain.Add(fromEdge);
785
786   // List of edges, added to chain on the previous cycle pass
787   TopTools_ListOfShape listPrevEdges;
788   listPrevEdges.Append(fromEdge/*.Oriented( TopAbs_FORWARD )*/);
789
790   // Collect all edges pass by pass
791   while (listPrevEdges.Extent() > 0) {
792     // List of edges, added to chain on this cycle pass
793     TopTools_ListOfShape listCurEdges;
794
795     // Find the next portion of edges
796     TopTools_ListIteratorOfListOfShape itE (listPrevEdges);
797     for (; itE.More(); itE.Next()) {
798       TopoDS_Shape anE = itE.Value();
799
800       // Iterate on faces, having edge <anE>
801       TopTools_ListIteratorOfListOfShape itA (aMesh->GetAncestors(anE));
802       for (; itA.More(); itA.Next()) {
803         TopoDS_Shape aW = itA.Value();
804
805         // There are objects of different type among the ancestors of edge
806         if (aW.ShapeType() == TopAbs_WIRE) {
807           TopoDS_Shape anOppE;
808
809           BRepTools_WireExplorer aWE (TopoDS::Wire(aW));
810           Standard_Integer nb = 1, found = 0;
811           TopTools_Array1OfShape anEdges (1,4);
812           for (; aWE.More(); aWE.Next(), nb++) {
813             if (nb > 4) {
814               found = 0;
815               break;
816             }
817             anEdges(nb) = aWE.Current();
818             if (anEdges(nb).IsSame(anE)) found = nb;
819           }
820
821           if (nb == 5 && found > 0) {
822             // Quadrangle face found, get an opposite edge
823             Standard_Integer opp = found + 2;
824             if (opp > 4) opp -= 4;
825             anOppE = anEdges(opp);
826
827             // add anOppE to aChain if ...
828             if (!aChain.Contains(anOppE)) { // ... anOppE is not in aChain
829               // Add found edge to the chain oriented so that to
830               // have it co-directed with a forward MainEdge
831               TopAbs_Orientation ori = anE.Orientation();
832               if ( anEdges(opp).Orientation() == anEdges(found).Orientation() )
833                 ori = TopAbs::Reverse( ori );
834               anOppE.Orientation( ori );
835               if ( anOppE.IsSame( theEdge ))
836                 return TopoDS::Edge( anOppE );
837               aChain.Add(anOppE);
838               listCurEdges.Append(anOppE);
839             }
840           } // if (nb == 5 && found > 0)
841         } // if (aF.ShapeType() == TopAbs_WIRE)
842       } // for (; itF.More(); itF.Next())
843     } // for (; itE.More(); itE.Next())
844
845     listPrevEdges = listCurEdges;
846   } // while (listPrevEdges.Extent() > 0)
847
848   return TopoDS_Edge();
849 }
850
851 //================================================================================
852   /*!
853    * \brief Find corresponding nodes on two faces
854     * \param face1 - the first face
855     * \param mesh1 - mesh containing elements on the first face
856     * \param face2 - the second face
857     * \param mesh2 - mesh containing elements on the second face
858     * \param assocMap - map associating subshapes of the faces
859     * \param node1To2Map - map containing found matching nodes
860     * \retval bool - is a success
861    */
862 //================================================================================
863
864 bool StdMeshers_ProjectionUtils::
865 FindMatchingNodesOnFaces( const TopoDS_Face&     face1,
866                           SMESH_Mesh*            mesh1,
867                           const TopoDS_Face&     face2,
868                           SMESH_Mesh*            mesh2,
869                           const TShapeShapeMap & assocMap,
870                           TNodeNodeMap &         node1To2Map)
871 {
872   SMESHDS_Mesh* meshDS1 = mesh1->GetMeshDS();
873   SMESHDS_Mesh* meshDS2 = mesh2->GetMeshDS();
874   
875   SMESH_MesherHelper helper1( *mesh1 );
876   SMESH_MesherHelper helper2( *mesh2 );
877
878   // Get corresponding submeshes and roughly check match of meshes
879
880   SMESHDS_SubMesh * SM2 = meshDS2->MeshElements( face2 );
881   SMESHDS_SubMesh * SM1 = meshDS1->MeshElements( face1 );
882   if ( !SM2 || !SM1 )
883     RETURN_BAD_RESULT("Empty submeshes");
884   if ( SM2->NbNodes()    != SM1->NbNodes() ||
885        SM2->NbElements() != SM1->NbElements() )
886     RETURN_BAD_RESULT("Different meshes on corresponding faces "
887                       << meshDS1->ShapeToIndex( face1 ) << " and "
888                       << meshDS2->ShapeToIndex( face2 ));
889   if ( SM2->NbElements() == 0 )
890     RETURN_BAD_RESULT("Empty submeshes");
891
892   helper1.SetSubShape( face1 );
893   helper2.SetSubShape( face2 );
894   if ( helper1.HasSeam() != helper2.HasSeam() )
895     RETURN_BAD_RESULT("Different faces' geometry");
896
897   // Data to call SMESH_MeshEditor::FindMatchingNodes():
898
899   // 1. Nodes of corresponding links:
900
901   // get 2 matching edges, not seam ones
902   TopoDS_Edge edge1, edge2;
903   TopExp_Explorer eE( OuterShape( face2, TopAbs_WIRE ), TopAbs_EDGE );
904   do {
905     edge2 = TopoDS::Edge( eE.Current() );
906     eE.Next();
907   } while ( BRep_Tool::IsClosed( edge2, face2 ) && eE.More());
908   if ( !assocMap.IsBound( edge2 ))
909     RETURN_BAD_RESULT("Association not found for edge " << meshDS2->ShapeToIndex( edge2 ));
910   edge1 = TopoDS::Edge( assocMap( edge2 ));
911   if ( !IsSubShape( edge1, face1 ))
912     RETURN_BAD_RESULT("Wrong association, edge " << meshDS1->ShapeToIndex( edge1 ) <<
913                       " isn't a subshape of face " << meshDS1->ShapeToIndex( face1 ));
914
915   // get 2 matching vertices
916   TopoDS_Shape V2 = TopExp::FirstVertex( TopoDS::Edge( edge2 ));
917   if ( !assocMap.IsBound( V2 ))
918     RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
919   TopoDS_Shape V1 = assocMap( V2 );
920
921   // nodes on vertices
922   SMESHDS_SubMesh * vSM1 = meshDS1->MeshElements( V1 );
923   SMESHDS_SubMesh * vSM2 = meshDS2->MeshElements( V2 );
924   if ( !vSM1 || !vSM2 || vSM1->NbNodes() != 1 || vSM2->NbNodes() != 1 )
925     RETURN_BAD_RESULT("Bad node submesh");
926   const SMDS_MeshNode* vNode1 = vSM1->GetNodes()->next();
927   const SMDS_MeshNode* vNode2 = vSM2->GetNodes()->next();
928
929   // nodes on edges linked with nodes on vertices
930   const SMDS_MeshNode* nullNode = 0;
931   vector< const SMDS_MeshNode*> eNode1( 2, nullNode );
932   vector< const SMDS_MeshNode*> eNode2( 2, nullNode );
933   int nbNodeToGet = 1;
934   if ( IsClosedEdge( edge1 ) || IsClosedEdge( edge2 ) )
935     nbNodeToGet = 2;
936   for ( int is2 = 0; is2 < 2; ++is2 )
937   {
938     TopoDS_Edge &     edge  = is2 ? edge2 : edge1;
939     SMESHDS_Mesh *    smDS  = is2 ? meshDS2 : meshDS1;
940     SMESHDS_SubMesh* edgeSM = smDS->MeshElements( edge );
941     // nodes linked with ones on vertices
942     const SMDS_MeshNode*           vNode = is2 ? vNode2 : vNode1;
943     vector< const SMDS_MeshNode*>& eNode = is2 ? eNode2 : eNode1;
944     int nbGotNode = 0;
945     SMDS_ElemIteratorPtr vElem = vNode->GetInverseElementIterator();
946     while ( vElem->more() && nbGotNode != nbNodeToGet ) {
947       const SMDS_MeshElement* elem = vElem->next();
948       if ( elem->GetType() == SMDSAbs_Edge && edgeSM->Contains( elem ))
949         eNode[ nbGotNode++ ] = 
950           ( elem->GetNode(0) == vNode ) ? elem->GetNode(1) : elem->GetNode(0);
951     }
952     if ( nbGotNode > 1 ) // sort found nodes by param on edge
953     {
954       SMESH_MesherHelper* helper = is2 ? &helper2 : &helper1;
955       double u0 = helper->GetNodeU( edge, eNode[ 0 ]);
956       double u1 = helper->GetNodeU( edge, eNode[ 1 ]);
957       if ( u0 > u1 ) std::swap( eNode[ 0 ], eNode[ 1 ]);
958     }
959     if ( nbGotNode == 0 )
960       RETURN_BAD_RESULT("Found no nodes on edge " << smDS->ShapeToIndex( edge ) <<
961                         " linked to " << vNode );
962   }
963
964   // 2. face sets
965
966   set<const SMDS_MeshElement*> Elems1, Elems2;
967   for ( int is2 = 0; is2 < 2; ++is2 )
968   {
969     set<const SMDS_MeshElement*> & elems = is2 ? Elems2 : Elems1;
970     SMESHDS_SubMesh*                  sm = is2 ? SM2 : SM1;
971     SMESH_MesherHelper*           helper = is2 ? &helper2 : &helper1;
972     const TopoDS_Face &             face = is2 ? face2 : face1;
973     SMDS_ElemIteratorPtr eIt = sm->GetElements();
974
975     if ( !helper->IsSeamShape( is2 ? edge2 : edge1 ))
976     {
977       while ( eIt->more() ) elems.insert( eIt->next() );
978     }
979     else
980     {
981       // there is only seam edge in a face, i.e. it is a sphere.
982       // FindMatchingNodes() will not know which way to go from any edge.
983       // So we ignore all faces having nodes on edges or vertices except
984       // one of faces sharing current start nodes
985
986       // find a face to keep
987       const SMDS_MeshElement* faceToKeep = 0;
988       const SMDS_MeshNode* vNode = is2 ? vNode2 : vNode1;
989       const SMDS_MeshNode* eNode = is2 ? eNode2[0] : eNode1[0];
990       TIDSortedElemSet inSet, notInSet;
991
992       const SMDS_MeshElement* f1 =
993         SMESH_MeshEditor::FindFaceInSet( vNode, eNode, inSet, notInSet );
994       if ( !f1 ) RETURN_BAD_RESULT("The first face on seam not found");
995       notInSet.insert( f1 );
996
997       const SMDS_MeshElement* f2 =
998         SMESH_MeshEditor::FindFaceInSet( vNode, eNode, inSet, notInSet );
999       if ( !f2 ) RETURN_BAD_RESULT("The second face on seam not found");
1000
1001       // select a face with less UV of vNode
1002       const SMDS_MeshNode* notSeamNode[2] = {0, 0};
1003       for ( int iF = 0; iF < 2; ++iF ) {
1004         const SMDS_MeshElement* f = ( iF ? f2 : f1 );
1005         for ( int i = 0; !notSeamNode[ iF ] && i < f->NbNodes(); ++i ) {
1006           const SMDS_MeshNode* node = f->GetNode( i );
1007           if ( !helper->IsSeamShape( node->GetPosition()->GetShapeId() ))
1008             notSeamNode[ iF ] = node;
1009         }
1010       }
1011       gp_Pnt2d uv1 = helper->GetNodeUV( face, vNode, notSeamNode[0] );
1012       gp_Pnt2d uv2 = helper->GetNodeUV( face, vNode, notSeamNode[1] );
1013       if ( uv1.X() + uv1.Y() > uv2.X() + uv2.Y() )
1014         faceToKeep = f2;
1015       else
1016         faceToKeep = f1;
1017
1018       // fill elem set
1019       elems.insert( faceToKeep );
1020       while ( eIt->more() ) {
1021         const SMDS_MeshElement* f = eIt->next();
1022         int nbNodes = f->NbNodes();
1023         if ( f->IsQuadratic() )
1024           nbNodes /= 2;
1025         bool onBnd = false;
1026         for ( int i = 0; !onBnd && i < nbNodes; ++i ) {
1027           const SMDS_MeshNode* node = f->GetNode( i );
1028           onBnd = ( node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE);
1029         }
1030         if ( !onBnd )
1031           elems.insert( f );
1032       }
1033     } // case on a sphere
1034   } // loop on 2 faces
1035
1036   node1To2Map.clear();
1037   int res = SMESH_MeshEditor::FindMatchingNodes( Elems1, Elems2,
1038                                                  vNode1, vNode2,
1039                                                  eNode1[0], eNode2[0],
1040                                                  node1To2Map);
1041   if ( res != SMESH_MeshEditor::SEW_OK )
1042     RETURN_BAD_RESULT("FindMatchingNodes() result " << res );
1043
1044
1045   // On a sphere, add matching nodes on the edge
1046
1047   if ( helper1.IsSeamShape( edge1 ))
1048   {
1049     // sort nodes on edges by param on edge
1050     map< double, const SMDS_MeshNode* > u2nodesMaps[2];
1051     for ( int is2 = 0; is2 < 2; ++is2 )
1052     {
1053       TopoDS_Edge &     edge  = is2 ? edge2 : edge1;
1054       SMESHDS_Mesh *    smDS  = is2 ? meshDS2 : meshDS1;
1055       SMESHDS_SubMesh* edgeSM = smDS->MeshElements( edge );
1056       map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[ is2 ];
1057
1058       SMDS_NodeIteratorPtr nIt = edgeSM->GetNodes();
1059       while ( nIt->more() ) {
1060         const SMDS_MeshNode* node = nIt->next();
1061         const SMDS_EdgePosition* pos =
1062           static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
1063         pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
1064       }
1065       if ( pos2nodes.size() != edgeSM->NbNodes() )
1066         RETURN_BAD_RESULT("Equal params of nodes on edge "
1067                           << smDS->ShapeToIndex( edge ) << " of face " << is2 );
1068     }
1069     if ( u2nodesMaps[0].size() != u2nodesMaps[1].size() )
1070       RETURN_BAD_RESULT("Different nb of new nodes on edges or wrong params");
1071
1072     // compare edge orientation
1073     double u1 = helper1.GetNodeU( edge1, vNode1 );
1074     double u2 = helper2.GetNodeU( edge2, vNode2 );
1075     bool isFirst1 = ( u1 < u2nodesMaps[0].begin()->first );
1076     bool isFirst2 = ( u2 < u2nodesMaps[1].begin()->first );
1077     bool reverse ( isFirst1 != isFirst2 );
1078
1079     // associate matching nodes
1080     map< double, const SMDS_MeshNode* >::iterator u_Node1, u_Node2, end1;
1081     map< double, const SMDS_MeshNode* >::reverse_iterator uR_Node2;
1082     u_Node1 = u2nodesMaps[0].begin();
1083     u_Node2 = u2nodesMaps[1].begin();
1084     uR_Node2 = u2nodesMaps[1].rbegin();
1085     end1 = u2nodesMaps[0].end();
1086     for ( ; u_Node1 != end1; ++u_Node1 ) {
1087       const SMDS_MeshNode* n1 = u_Node1->second;
1088       const SMDS_MeshNode* n2 = ( reverse ? (uR_Node2++)->second : (u_Node2++)->second );
1089       node1To2Map.insert( make_pair( n1, n2 ));
1090     }
1091
1092     // associate matching nodes on the last vertices
1093     V2 = TopExp::LastVertex( TopoDS::Edge( edge2 ));
1094     if ( !assocMap.IsBound( V2 ))
1095       RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
1096     V1 = assocMap( V2 );
1097     vSM1 = meshDS1->MeshElements( V1 );
1098     vSM2 = meshDS2->MeshElements( V2 );
1099     if ( !vSM1 || !vSM2 || vSM1->NbNodes() != 1 || vSM2->NbNodes() != 1 )
1100       RETURN_BAD_RESULT("Bad node submesh");
1101     vNode1 = vSM1->GetNodes()->next();
1102     vNode2 = vSM2->GetNodes()->next();
1103     node1To2Map.insert( make_pair( vNode1, vNode2 ));
1104   }
1105   
1106   return true;
1107 }
1108
1109 //================================================================================
1110 /*!
1111  * \brief Check if the first and last vertices of an edge are the same
1112  * \param anEdge - the edge to check
1113  * \retval bool - true if same
1114  */
1115 //================================================================================
1116
1117 bool StdMeshers_ProjectionUtils::IsClosedEdge( const TopoDS_Edge& anEdge )
1118 {
1119   return TopExp::FirstVertex( anEdge ).IsSame( TopExp::LastVertex( anEdge ));
1120 }
1121
1122 //================================================================================
1123   /*!
1124    * \brief Return any subshape of a face belonging to the outer wire
1125     * \param face - the face
1126     * \param type - type of subshape to return
1127     * \retval TopoDS_Shape - the found subshape
1128    */
1129 //================================================================================
1130
1131 TopoDS_Shape StdMeshers_ProjectionUtils::OuterShape( const TopoDS_Face& face,
1132                                                      TopAbs_ShapeEnum   type)
1133 {
1134   TopExp_Explorer exp( BRepTools::OuterWire( face ), type );
1135   if ( exp.More() )
1136     return exp.Current();
1137   return TopoDS_Shape();
1138 }
1139
1140 //================================================================================
1141   /*!
1142    * \brief Check that submesh is computed and try to compute it if is not
1143     * \param sm - submesh to compute
1144     * \param iterationNb - int used to stop infinite recursive call
1145     * \retval bool - true if computed
1146    */
1147 //================================================================================
1148
1149 bool StdMeshers_ProjectionUtils::MakeComputed(SMESH_subMesh * sm, const int iterationNb)
1150 {
1151   if ( iterationNb > 10 )
1152     RETURN_BAD_RESULT("Infinite recursive projection");
1153   if ( !sm )
1154     RETURN_BAD_RESULT("NULL submesh");
1155   if ( sm->IsMeshComputed() )
1156     return true;
1157
1158   SMESH_Mesh* mesh = sm->GetFather();
1159   SMESH_Gen* gen   = mesh->GetGen();
1160   SMESH_Algo* algo = gen->GetAlgo( *mesh, sm->GetSubShape() );
1161   if ( !algo )
1162     RETURN_BAD_RESULT("No algo assigned to submesh " << sm->GetId());
1163
1164   string algoType = algo->GetName();
1165   if ( algoType.substr(0, 11) != "Projection_")
1166     return gen->Compute( *mesh, sm->GetSubShape() );
1167
1168   // try to compute source mesh
1169
1170   const list <const SMESHDS_Hypothesis *> & hyps =
1171     algo->GetUsedHypothesis( *mesh, sm->GetSubShape() );
1172
1173   TopoDS_Shape srcShape;
1174   SMESH_Mesh* srcMesh = 0;
1175   list <const SMESHDS_Hypothesis*>::const_iterator hIt = hyps.begin();
1176   for ( ; srcShape.IsNull() && hIt != hyps.end(); ++hIt ) {
1177     string hypName = (*hIt)->GetName();
1178     if ( hypName == "ProjectionSource1D" ) {
1179       const StdMeshers_ProjectionSource1D * hyp =
1180         static_cast<const StdMeshers_ProjectionSource1D*>( *hIt );
1181       srcShape = hyp->GetSourceEdge();
1182       srcMesh = hyp->GetSourceMesh();
1183     }
1184     else if ( hypName == "ProjectionSource2D" ) {
1185       const StdMeshers_ProjectionSource2D * hyp =
1186         static_cast<const StdMeshers_ProjectionSource2D*>( *hIt );
1187       srcShape = hyp->GetSourceFace();
1188       srcMesh = hyp->GetSourceMesh();
1189     }
1190     else if ( hypName == "ProjectionSource3D" ) {
1191       const StdMeshers_ProjectionSource3D * hyp =
1192         static_cast<const StdMeshers_ProjectionSource3D*>( *hIt );
1193       srcShape = hyp->GetSource3DShape();
1194       srcMesh = hyp->GetSourceMesh();
1195     }
1196   }
1197   if ( srcShape.IsNull() ) // no projection source defined
1198     return gen->Compute( *mesh, sm->GetSubShape() );
1199
1200   if ( srcShape.IsSame( sm->GetSubShape() ))
1201     RETURN_BAD_RESULT("Projection from self");
1202     
1203   if ( !srcMesh )
1204     srcMesh = mesh;
1205
1206   return MakeComputed( srcMesh->GetSubMesh( srcShape ), iterationNb + 1 );
1207 }
1208
1209 //================================================================================
1210   /*!
1211    * \brief Count nb of subshapes
1212     * \param shape - the shape
1213     * \param type - the type of subshapes to count
1214     * \retval int - the calculated number
1215    */
1216 //================================================================================
1217
1218 int StdMeshers_ProjectionUtils::Count(const TopoDS_Shape&    shape,
1219                                       const TopAbs_ShapeEnum type,
1220                                       const bool             ignoreSame)
1221 {
1222   if ( ignoreSame ) {
1223     TopTools_IndexedMapOfShape map;
1224     TopExp::MapShapes( shape, type, map );
1225     return map.Extent();
1226   }
1227   else {
1228     int nb = 0;
1229     for ( TopExp_Explorer exp( shape, type ); exp.More(); exp.Next() )
1230       ++nb;
1231     return nb;
1232   }
1233 }
1234
1235 namespace {
1236
1237   SMESH_subMeshEventListener* GetSrcSubMeshListener();
1238
1239   //================================================================================
1240   /*!
1241    * \brief Listener that resets an event listener on source submesh when 
1242    * "ProjectionSource*D" hypothesis is modified
1243    */
1244   //================================================================================
1245
1246   struct HypModifWaiter: SMESH_subMeshEventListener
1247   {
1248     HypModifWaiter():SMESH_subMeshEventListener(0){} // won't be deleted by submesh
1249
1250     void ProcessEvent(const int event, const int eventType, SMESH_subMesh* subMesh,
1251                       EventListenerData*, const SMESH_Hypothesis*)
1252     {
1253       if ( event     == SMESH_subMesh::MODIF_HYP &&
1254            eventType == SMESH_subMesh::ALGO_EVENT)
1255       {
1256         // delete current source listener
1257         subMesh->DeleteEventListener( GetSrcSubMeshListener() );
1258         // let algo set a new one
1259         SMESH_Gen* gen = subMesh->GetFather()->GetGen();
1260         if ( SMESH_Algo* algo = gen->GetAlgo( *subMesh->GetFather(),
1261                                               subMesh->GetSubShape() ))
1262           algo->SetEventListener( subMesh );
1263       }
1264     }
1265   };
1266   //================================================================================
1267   /*!
1268    * \brief return static HypModifWaiter
1269    */
1270   //================================================================================
1271
1272   SMESH_subMeshEventListener* GetHypModifWaiter() {
1273     static HypModifWaiter aHypModifWaiter;
1274     return &aHypModifWaiter;
1275   }
1276   //================================================================================
1277   /*!
1278    * \brief return static listener for source shape submeshes
1279    */
1280   //================================================================================
1281
1282   SMESH_subMeshEventListener* GetSrcSubMeshListener() {
1283     static SMESH_subMeshEventListener srcListener(0); // won't be deleted by submesh
1284     return &srcListener;
1285   }
1286 }
1287
1288 //================================================================================
1289 /*!
1290  * \brief Set event listeners to submesh with projection algo
1291  * \param subMesh - submesh with projection algo
1292  * \param srcShape - source shape
1293  * \param srcMesh - source mesh
1294  */
1295 //================================================================================
1296
1297 void StdMeshers_ProjectionUtils::SetEventListener(SMESH_subMesh* subMesh,
1298                                                   TopoDS_Shape   srcShape,
1299                                                   SMESH_Mesh*    srcMesh)
1300 {
1301   // Set listener that resets an event listener on source submesh when
1302   // "ProjectionSource*D" hypothesis is modified
1303   subMesh->SetEventListener( GetHypModifWaiter(),0,subMesh);
1304
1305   // Set an event listener to submesh of the source shape
1306   if ( !srcShape.IsNull() )
1307   {
1308     if ( !srcMesh )
1309       srcMesh = subMesh->GetFather();
1310
1311     SMESH_subMesh* srcShapeSM = srcMesh->GetSubMesh( srcShape );
1312
1313     if ( srcShapeSM != subMesh )
1314       subMesh->SetEventListener( GetSrcSubMeshListener(),
1315                                  SMESH_subMeshEventListenerData::MakeData( subMesh ),
1316                                  srcShapeSM );
1317   }
1318 }