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