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