Salome HOME
25f2399cdc8ab2d9991677a3cfa93be26f68f9ee
[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, try to find not seam ones
902   TopoDS_Edge edge1, edge2, seam1, seam2;
903   TopExp_Explorer eE( OuterShape( face2, TopAbs_WIRE ), TopAbs_EDGE );
904   do {
905     // edge 2
906     TopoDS_Edge e2 = TopoDS::Edge( eE.Current() );
907     eE.Next();
908     // edge 1
909     if ( !assocMap.IsBound( e2 ))
910       RETURN_BAD_RESULT("Association not found for edge " << meshDS2->ShapeToIndex( e2 ));
911     TopoDS_Edge e1 = TopoDS::Edge( assocMap( e2 ));
912     if ( !IsSubShape( e1, face1 ))
913       RETURN_BAD_RESULT("Wrong association, edge " << meshDS1->ShapeToIndex( e1 ) <<
914                         " isn't a subshape of face " << meshDS1->ShapeToIndex( face1 ));
915     // check that there are nodes on edges
916     SMESHDS_SubMesh * eSM1 = meshDS1->MeshElements( e1 );
917     SMESHDS_SubMesh * eSM2 = meshDS2->MeshElements( e2 );
918     if ( eSM1 && eSM2 && eSM1->NbNodes() > 0 && eSM2->NbNodes() > 0 )
919     {
920       if ( BRep_Tool::IsClosed( e2, face2 )) {
921         seam1 = e1; seam2 = e2;
922       }
923       else {
924         edge1 = e1; edge2 = e2;
925       }
926     }
927   } while ( edge2.IsNull() && eE.More() );
928   //
929   if ( edge2.IsNull() ) {
930     edge1 = seam1; edge2 = seam2;
931   }
932   if ( edge2.IsNull() ) RETURN_BAD_RESULT("No matching edges with nodes found");
933
934   // get 2 matching vertices
935   TopoDS_Vertex V2 = TopExp::FirstVertex( TopoDS::Edge( edge2 ));
936   if ( !assocMap.IsBound( V2 ))
937     RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
938   TopoDS_Vertex V1 = TopoDS::Vertex( assocMap( V2 ));
939
940   // nodes on vertices
941   const SMDS_MeshNode* vNode1 = SMESH_Algo::VertexNode( V1, meshDS1 );
942   const SMDS_MeshNode* vNode2 = SMESH_Algo::VertexNode( V2, meshDS2 );
943   if ( !vNode1 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS1->ShapeToIndex( V1 ));
944   if ( !vNode2 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS2->ShapeToIndex( V2 ));
945
946   // nodes on edges linked with nodes on vertices
947   const SMDS_MeshNode* nullNode = 0;
948   vector< const SMDS_MeshNode*> eNode1( 2, nullNode );
949   vector< const SMDS_MeshNode*> eNode2( 2, nullNode );
950   int nbNodeToGet = 1;
951   if ( IsClosedEdge( edge1 ) || IsClosedEdge( edge2 ) )
952     nbNodeToGet = 2;
953   for ( int is2 = 0; is2 < 2; ++is2 )
954   {
955     TopoDS_Edge &     edge  = is2 ? edge2 : edge1;
956     SMESHDS_Mesh *    smDS  = is2 ? meshDS2 : meshDS1;
957     SMESHDS_SubMesh* edgeSM = smDS->MeshElements( edge );
958     // nodes linked with ones on vertices
959     const SMDS_MeshNode*           vNode = is2 ? vNode2 : vNode1;
960     vector< const SMDS_MeshNode*>& eNode = is2 ? eNode2 : eNode1;
961     int nbGotNode = 0;
962     SMDS_ElemIteratorPtr vElem = vNode->GetInverseElementIterator();
963     while ( vElem->more() && nbGotNode != nbNodeToGet ) {
964       const SMDS_MeshElement* elem = vElem->next();
965       if ( elem->GetType() == SMDSAbs_Edge && edgeSM->Contains( elem ))
966         eNode[ nbGotNode++ ] = 
967           ( elem->GetNode(0) == vNode ) ? elem->GetNode(1) : elem->GetNode(0);
968     }
969     if ( nbGotNode > 1 ) // sort found nodes by param on edge
970     {
971       SMESH_MesherHelper* helper = is2 ? &helper2 : &helper1;
972       double u0 = helper->GetNodeU( edge, eNode[ 0 ]);
973       double u1 = helper->GetNodeU( edge, eNode[ 1 ]);
974       if ( u0 > u1 ) std::swap( eNode[ 0 ], eNode[ 1 ]);
975     }
976     if ( nbGotNode == 0 )
977       RETURN_BAD_RESULT("Found no nodes on edge " << smDS->ShapeToIndex( edge ) <<
978                         " linked to " << vNode );
979   }
980
981   // 2. face sets
982
983   set<const SMDS_MeshElement*> Elems1, Elems2;
984   for ( int is2 = 0; is2 < 2; ++is2 )
985   {
986     set<const SMDS_MeshElement*> & elems = is2 ? Elems2 : Elems1;
987     SMESHDS_SubMesh*                  sm = is2 ? SM2 : SM1;
988     SMESH_MesherHelper*           helper = is2 ? &helper2 : &helper1;
989     const TopoDS_Face &             face = is2 ? face2 : face1;
990     SMDS_ElemIteratorPtr eIt = sm->GetElements();
991
992     if ( !helper->IsSeamShape( is2 ? edge2 : edge1 ))
993     {
994       while ( eIt->more() ) elems.insert( eIt->next() );
995     }
996     else
997     {
998       // there is only seam edge in a face, i.e. it is a sphere.
999       // FindMatchingNodes() will not know which way to go from any edge.
1000       // So we ignore all faces having nodes on edges or vertices except
1001       // one of faces sharing current start nodes
1002
1003       // find a face to keep
1004       const SMDS_MeshElement* faceToKeep = 0;
1005       const SMDS_MeshNode* vNode = is2 ? vNode2 : vNode1;
1006       const SMDS_MeshNode* eNode = is2 ? eNode2[0] : eNode1[0];
1007       TIDSortedElemSet inSet, notInSet;
1008
1009       const SMDS_MeshElement* f1 =
1010         SMESH_MeshEditor::FindFaceInSet( vNode, eNode, inSet, notInSet );
1011       if ( !f1 ) RETURN_BAD_RESULT("The first face on seam not found");
1012       notInSet.insert( f1 );
1013
1014       const SMDS_MeshElement* f2 =
1015         SMESH_MeshEditor::FindFaceInSet( vNode, eNode, inSet, notInSet );
1016       if ( !f2 ) RETURN_BAD_RESULT("The second face on seam not found");
1017
1018       // select a face with less UV of vNode
1019       const SMDS_MeshNode* notSeamNode[2] = {0, 0};
1020       for ( int iF = 0; iF < 2; ++iF ) {
1021         const SMDS_MeshElement* f = ( iF ? f2 : f1 );
1022         for ( int i = 0; !notSeamNode[ iF ] && i < f->NbNodes(); ++i ) {
1023           const SMDS_MeshNode* node = f->GetNode( i );
1024           if ( !helper->IsSeamShape( node->GetPosition()->GetShapeId() ))
1025             notSeamNode[ iF ] = node;
1026         }
1027       }
1028       gp_Pnt2d uv1 = helper->GetNodeUV( face, vNode, notSeamNode[0] );
1029       gp_Pnt2d uv2 = helper->GetNodeUV( face, vNode, notSeamNode[1] );
1030       if ( uv1.X() + uv1.Y() > uv2.X() + uv2.Y() )
1031         faceToKeep = f2;
1032       else
1033         faceToKeep = f1;
1034
1035       // fill elem set
1036       elems.insert( faceToKeep );
1037       while ( eIt->more() ) {
1038         const SMDS_MeshElement* f = eIt->next();
1039         int nbNodes = f->NbNodes();
1040         if ( f->IsQuadratic() )
1041           nbNodes /= 2;
1042         bool onBnd = false;
1043         for ( int i = 0; !onBnd && i < nbNodes; ++i ) {
1044           const SMDS_MeshNode* node = f->GetNode( i );
1045           onBnd = ( node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE);
1046         }
1047         if ( !onBnd )
1048           elems.insert( f );
1049       }
1050       // add also faces adjacent to faceToKeep
1051       int nbNodes = faceToKeep->NbNodes();
1052       if ( faceToKeep->IsQuadratic() ) nbNodes /= 2;
1053       notInSet.insert( f1 );
1054       notInSet.insert( f2 );
1055       for ( int i = 0; i < nbNodes; ++i ) {
1056         const SMDS_MeshNode* n1 = faceToKeep->GetNode( i );
1057         const SMDS_MeshNode* n2 = faceToKeep->GetNode( i+1 );
1058         f1 = SMESH_MeshEditor::FindFaceInSet( n1, n2, inSet, notInSet );
1059         if ( f1 )
1060           elems.insert( f1 );
1061       }
1062     } // case on a sphere
1063   } // loop on 2 faces
1064
1065   node1To2Map.clear();
1066   int res = SMESH_MeshEditor::FindMatchingNodes( Elems1, Elems2,
1067                                                  vNode1, vNode2,
1068                                                  eNode1[0], eNode2[0],
1069                                                  node1To2Map);
1070   if ( res != SMESH_MeshEditor::SEW_OK )
1071     RETURN_BAD_RESULT("FindMatchingNodes() result " << res );
1072
1073
1074   // On a sphere, add matching nodes on the edge
1075
1076   if ( helper1.IsSeamShape( edge1 ))
1077   {
1078     // sort nodes on edges by param on edge
1079     map< double, const SMDS_MeshNode* > u2nodesMaps[2];
1080     for ( int is2 = 0; is2 < 2; ++is2 )
1081     {
1082       TopoDS_Edge &     edge  = is2 ? edge2 : edge1;
1083       SMESHDS_Mesh *    smDS  = is2 ? meshDS2 : meshDS1;
1084       SMESHDS_SubMesh* edgeSM = smDS->MeshElements( edge );
1085       map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[ is2 ];
1086
1087       SMDS_NodeIteratorPtr nIt = edgeSM->GetNodes();
1088       while ( nIt->more() ) {
1089         const SMDS_MeshNode* node = nIt->next();
1090         const SMDS_EdgePosition* pos =
1091           static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
1092         pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
1093       }
1094       if ( pos2nodes.size() != edgeSM->NbNodes() )
1095         RETURN_BAD_RESULT("Equal params of nodes on edge "
1096                           << smDS->ShapeToIndex( edge ) << " of face " << is2 );
1097     }
1098     if ( u2nodesMaps[0].size() != u2nodesMaps[1].size() )
1099       RETURN_BAD_RESULT("Different nb of new nodes on edges or wrong params");
1100
1101     // compare edge orientation
1102     double u1 = helper1.GetNodeU( edge1, vNode1 );
1103     double u2 = helper2.GetNodeU( edge2, vNode2 );
1104     bool isFirst1 = ( u1 < u2nodesMaps[0].begin()->first );
1105     bool isFirst2 = ( u2 < u2nodesMaps[1].begin()->first );
1106     bool reverse ( isFirst1 != isFirst2 );
1107
1108     // associate matching nodes
1109     map< double, const SMDS_MeshNode* >::iterator u_Node1, u_Node2, end1;
1110     map< double, const SMDS_MeshNode* >::reverse_iterator uR_Node2;
1111     u_Node1 = u2nodesMaps[0].begin();
1112     u_Node2 = u2nodesMaps[1].begin();
1113     uR_Node2 = u2nodesMaps[1].rbegin();
1114     end1 = u2nodesMaps[0].end();
1115     for ( ; u_Node1 != end1; ++u_Node1 ) {
1116       const SMDS_MeshNode* n1 = u_Node1->second;
1117       const SMDS_MeshNode* n2 = ( reverse ? (uR_Node2++)->second : (u_Node2++)->second );
1118       node1To2Map.insert( make_pair( n1, n2 ));
1119     }
1120
1121     // associate matching nodes on the last vertices
1122     V2 = TopExp::LastVertex( TopoDS::Edge( edge2 ));
1123     if ( !assocMap.IsBound( V2 ))
1124       RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
1125     V1 = TopoDS::Vertex( assocMap( V2 ));
1126     vNode1 = SMESH_Algo::VertexNode( V1, meshDS1 );
1127     vNode2 = SMESH_Algo::VertexNode( V2, meshDS2 );
1128     if ( !vNode1 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS1->ShapeToIndex( V1 ));
1129     if ( !vNode2 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS2->ShapeToIndex( V2 ));
1130     node1To2Map.insert( make_pair( vNode1, vNode2 ));
1131   }
1132   
1133   return true;
1134 }
1135
1136 //================================================================================
1137 /*!
1138  * \brief Check if the first and last vertices of an edge are the same
1139  * \param anEdge - the edge to check
1140  * \retval bool - true if same
1141  */
1142 //================================================================================
1143
1144 bool StdMeshers_ProjectionUtils::IsClosedEdge( const TopoDS_Edge& anEdge )
1145 {
1146   return TopExp::FirstVertex( anEdge ).IsSame( TopExp::LastVertex( anEdge ));
1147 }
1148
1149 //================================================================================
1150   /*!
1151    * \brief Return any subshape of a face belonging to the outer wire
1152     * \param face - the face
1153     * \param type - type of subshape to return
1154     * \retval TopoDS_Shape - the found subshape
1155    */
1156 //================================================================================
1157
1158 TopoDS_Shape StdMeshers_ProjectionUtils::OuterShape( const TopoDS_Face& face,
1159                                                      TopAbs_ShapeEnum   type)
1160 {
1161   TopExp_Explorer exp( BRepTools::OuterWire( face ), type );
1162   if ( exp.More() )
1163     return exp.Current();
1164   return TopoDS_Shape();
1165 }
1166
1167 //================================================================================
1168   /*!
1169    * \brief Check that submesh is computed and try to compute it if is not
1170     * \param sm - submesh to compute
1171     * \param iterationNb - int used to stop infinite recursive call
1172     * \retval bool - true if computed
1173    */
1174 //================================================================================
1175
1176 bool StdMeshers_ProjectionUtils::MakeComputed(SMESH_subMesh * sm, const int iterationNb)
1177 {
1178   if ( iterationNb > 10 )
1179     RETURN_BAD_RESULT("Infinite recursive projection");
1180   if ( !sm )
1181     RETURN_BAD_RESULT("NULL submesh");
1182   if ( sm->IsMeshComputed() )
1183     return true;
1184
1185   SMESH_Mesh* mesh = sm->GetFather();
1186   SMESH_Gen* gen   = mesh->GetGen();
1187   SMESH_Algo* algo = gen->GetAlgo( *mesh, sm->GetSubShape() );
1188   if ( !algo )
1189     RETURN_BAD_RESULT("No algo assigned to submesh " << sm->GetId());
1190
1191   string algoType = algo->GetName();
1192   if ( algoType.substr(0, 11) != "Projection_")
1193     return gen->Compute( *mesh, sm->GetSubShape() );
1194
1195   // try to compute source mesh
1196
1197   const list <const SMESHDS_Hypothesis *> & hyps =
1198     algo->GetUsedHypothesis( *mesh, sm->GetSubShape() );
1199
1200   TopoDS_Shape srcShape;
1201   SMESH_Mesh* srcMesh = 0;
1202   list <const SMESHDS_Hypothesis*>::const_iterator hIt = hyps.begin();
1203   for ( ; srcShape.IsNull() && hIt != hyps.end(); ++hIt ) {
1204     string hypName = (*hIt)->GetName();
1205     if ( hypName == "ProjectionSource1D" ) {
1206       const StdMeshers_ProjectionSource1D * hyp =
1207         static_cast<const StdMeshers_ProjectionSource1D*>( *hIt );
1208       srcShape = hyp->GetSourceEdge();
1209       srcMesh = hyp->GetSourceMesh();
1210     }
1211     else if ( hypName == "ProjectionSource2D" ) {
1212       const StdMeshers_ProjectionSource2D * hyp =
1213         static_cast<const StdMeshers_ProjectionSource2D*>( *hIt );
1214       srcShape = hyp->GetSourceFace();
1215       srcMesh = hyp->GetSourceMesh();
1216     }
1217     else if ( hypName == "ProjectionSource3D" ) {
1218       const StdMeshers_ProjectionSource3D * hyp =
1219         static_cast<const StdMeshers_ProjectionSource3D*>( *hIt );
1220       srcShape = hyp->GetSource3DShape();
1221       srcMesh = hyp->GetSourceMesh();
1222     }
1223   }
1224   if ( srcShape.IsNull() ) // no projection source defined
1225     return gen->Compute( *mesh, sm->GetSubShape() );
1226
1227   if ( srcShape.IsSame( sm->GetSubShape() ))
1228     RETURN_BAD_RESULT("Projection from self");
1229     
1230   if ( !srcMesh )
1231     srcMesh = mesh;
1232
1233   return MakeComputed( srcMesh->GetSubMesh( srcShape ), iterationNb + 1 );
1234 }
1235
1236 //================================================================================
1237   /*!
1238    * \brief Count nb of subshapes
1239     * \param shape - the shape
1240     * \param type - the type of subshapes to count
1241     * \retval int - the calculated number
1242    */
1243 //================================================================================
1244
1245 int StdMeshers_ProjectionUtils::Count(const TopoDS_Shape&    shape,
1246                                       const TopAbs_ShapeEnum type,
1247                                       const bool             ignoreSame)
1248 {
1249   if ( ignoreSame ) {
1250     TopTools_IndexedMapOfShape map;
1251     TopExp::MapShapes( shape, type, map );
1252     return map.Extent();
1253   }
1254   else {
1255     int nb = 0;
1256     for ( TopExp_Explorer exp( shape, type ); exp.More(); exp.Next() )
1257       ++nb;
1258     return nb;
1259   }
1260 }
1261
1262 namespace {
1263
1264   SMESH_subMeshEventListener* GetSrcSubMeshListener();
1265
1266   //================================================================================
1267   /*!
1268    * \brief Listener that resets an event listener on source submesh when 
1269    * "ProjectionSource*D" hypothesis is modified
1270    */
1271   //================================================================================
1272
1273   struct HypModifWaiter: SMESH_subMeshEventListener
1274   {
1275     HypModifWaiter():SMESH_subMeshEventListener(0){} // won't be deleted by submesh
1276
1277     void ProcessEvent(const int event, const int eventType, SMESH_subMesh* subMesh,
1278                       EventListenerData*, const SMESH_Hypothesis*)
1279     {
1280       if ( event     == SMESH_subMesh::MODIF_HYP &&
1281            eventType == SMESH_subMesh::ALGO_EVENT)
1282       {
1283         // delete current source listener
1284         subMesh->DeleteEventListener( GetSrcSubMeshListener() );
1285         // let algo set a new one
1286         SMESH_Gen* gen = subMesh->GetFather()->GetGen();
1287         if ( SMESH_Algo* algo = gen->GetAlgo( *subMesh->GetFather(),
1288                                               subMesh->GetSubShape() ))
1289           algo->SetEventListener( subMesh );
1290       }
1291     }
1292   };
1293   //================================================================================
1294   /*!
1295    * \brief return static HypModifWaiter
1296    */
1297   //================================================================================
1298
1299   SMESH_subMeshEventListener* GetHypModifWaiter() {
1300     static HypModifWaiter aHypModifWaiter;
1301     return &aHypModifWaiter;
1302   }
1303   //================================================================================
1304   /*!
1305    * \brief return static listener for source shape submeshes
1306    */
1307   //================================================================================
1308
1309   SMESH_subMeshEventListener* GetSrcSubMeshListener() {
1310     static SMESH_subMeshEventListener srcListener(0); // won't be deleted by submesh
1311     return &srcListener;
1312   }
1313 }
1314
1315 //================================================================================
1316 /*!
1317  * \brief Set event listeners to submesh with projection algo
1318  * \param subMesh - submesh with projection algo
1319  * \param srcShape - source shape
1320  * \param srcMesh - source mesh
1321  */
1322 //================================================================================
1323
1324 void StdMeshers_ProjectionUtils::SetEventListener(SMESH_subMesh* subMesh,
1325                                                   TopoDS_Shape   srcShape,
1326                                                   SMESH_Mesh*    srcMesh)
1327 {
1328   // Set listener that resets an event listener on source submesh when
1329   // "ProjectionSource*D" hypothesis is modified
1330   subMesh->SetEventListener( GetHypModifWaiter(),0,subMesh);
1331
1332   // Set an event listener to submesh of the source shape
1333   if ( !srcShape.IsNull() )
1334   {
1335     if ( !srcMesh )
1336       srcMesh = subMesh->GetFather();
1337
1338     SMESH_subMesh* srcShapeSM = srcMesh->GetSubMesh( srcShape );
1339
1340     if ( srcShapeSM != subMesh )
1341       subMesh->SetEventListener( GetSrcSubMeshListener(),
1342                                  SMESH_subMeshEventListenerData::MakeData( subMesh ),
1343                                  srcShapeSM );
1344   }
1345 }