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