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