Salome HOME
a21f5d7aa26b1986e6cbccc706a138ef5df5d70c
[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             FE1.push_back( make_pair( nextFace1, *eIt1 ));
760             FE2.push_back( make_pair( nextFace2, *eIt2 ));
761           }
762         }
763       }
764       InsertAssociation( theShape1, theShape2, theMap );
765       return true;
766     }
767       // ----------------------------------------------------------------------
768     case TopAbs_COMPOUND: { // GROUP
769       // ----------------------------------------------------------------------
770       // Maybe groups contain only one member
771       TopoDS_Iterator it1( theShape1 ), it2( theShape2 );
772       TopAbs_ShapeEnum memberType = it1.Value().ShapeType();
773       int nbMembers = SMESH_MesherHelper::Count( theShape1, memberType, true );
774       if ( nbMembers == 0 ) return true;
775       if ( nbMembers == 1 ) {
776         return FindSubShapeAssociation( it1.Value(), theMesh1, it2.Value(), theMesh2, theMap );
777       }
778       // Try to make shells of faces
779       //
780       BRep_Builder builder;
781       TopoDS_Shell shell1, shell2;
782       builder.MakeShell(shell1); builder.MakeShell(shell2);
783       if ( memberType == TopAbs_FACE ) {
784         // just add faces of groups to shells
785         for (; it1.More(); it1.Next(), it2.Next() )
786           builder.Add( shell1, it1.Value() ), builder.Add( shell2, it2.Value() );
787       }
788       else if ( memberType == TopAbs_EDGE ) {
789         // Try to add faces sharing more than one edge of a group or
790         // sharing all its vertices with the group
791         TopTools_IndexedMapOfShape groupVertices[2];
792         TopExp::MapShapes( theShape1, TopAbs_VERTEX, groupVertices[0]);
793         TopExp::MapShapes( theShape2, TopAbs_VERTEX, groupVertices[1]);
794         //
795         TopTools_MapOfShape groupEdges[2], addedFaces[2];
796         bool hasInitAssoc = (!theMap.IsEmpty()), initAssocOK = !hasInitAssoc;
797         for (; it1.More(); it1.Next(), it2.Next() ) {
798           groupEdges[0].Add( it1.Value() );
799           groupEdges[1].Add( it2.Value() );
800           if ( !initAssocOK ) {
801             // for shell association there must be an edge with both vertices bound
802             TopoDS_Vertex v1, v2;
803             TopExp::Vertices( TopoDS::Edge( it1.Value().Oriented(TopAbs_FORWARD)), v1, v2 );
804             initAssocOK = ( theMap.IsBound( v1 ) && theMap.IsBound( v2 ));
805           }
806         }
807         for (int is2ndGroup = 0; initAssocOK && is2ndGroup < 2; ++is2ndGroup) {
808           const TopoDS_Shape& group = is2ndGroup ? theShape2: theShape1;
809           SMESH_Mesh*         mesh  = is2ndGroup ? theMesh2 : theMesh1;
810           TopoDS_Shell&       shell = is2ndGroup ? shell2   : shell1;
811           for ( TopoDS_Iterator it( group ); it.More(); it.Next() ) {
812             const TopoDS_Edge& edge = TopoDS::Edge( it.Value() );
813             TopoDS_Face face;
814             for ( int iF = 0; iF < 2; ++iF ) { // loop on 2 faces sharing edge
815               face = GetNextFace(mesh->GetAncestorMap(), edge, face);
816               if ( !face.IsNull() ) {
817                 int nbGroupEdges = 0;
818                 for ( TopExp_Explorer f( face, TopAbs_EDGE ); f.More(); f.Next())
819                   if ( groupEdges[ is2ndGroup ].Contains( f.Current() ))
820                     if ( ++nbGroupEdges > 1 )
821                       break;
822                 bool add = (nbGroupEdges > 1 ||
823                             SMESH_MesherHelper::Count( face, TopAbs_EDGE, true ) == 1 );
824                 if ( !add ) {
825                   add = true;
826                   for ( TopExp_Explorer v( face, TopAbs_VERTEX ); add && v.More(); v.Next())
827                     add = groupVertices[ is2ndGroup ].Contains( v.Current() );
828                 }
829                 if ( add && addedFaces[ is2ndGroup ].Add( face ))
830                   builder.Add( shell, face );
831               }
832             }
833           }
834         }
835       } else {
836         RETURN_BAD_RESULT("Unexpected group type");
837       }
838       // Associate shells
839       //
840       int nbFaces1 = SMESH_MesherHelper:: Count( shell1, TopAbs_FACE, 0 );
841       int nbFaces2 = SMESH_MesherHelper:: Count( shell2, TopAbs_FACE, 0 );
842       if ( nbFaces1 != nbFaces2 )
843         RETURN_BAD_RESULT("Different nb of faces found for shells");
844       if ( nbFaces1 > 0 ) {
845         bool ok = false;
846         if ( nbFaces1 == 1 ) {
847           TopoDS_Shape F1 = TopoDS_Iterator( shell1 ).Value();
848           TopoDS_Shape F2 = TopoDS_Iterator( shell2 ).Value();
849           ok = FindSubShapeAssociation( F1, theMesh1, F2, theMesh2, theMap );
850         }
851         else {
852           ok = FindSubShapeAssociation(shell1, theMesh1, shell2, theMesh2, theMap );
853         }
854         // Check if all members are mapped 
855         if ( ok ) {
856           TopTools_MapOfShape boundMembers[2];
857           TopoDS_Iterator mIt;
858           for ( mIt.Initialize( theShape1 ); mIt.More(); mIt.Next())
859             if ( theMap.IsBound( mIt.Value() )) {
860               boundMembers[0].Add( mIt.Value() );
861               boundMembers[1].Add( theMap( mIt.Value() ));
862             }
863           if ( boundMembers[0].Extent() != nbMembers ) {
864             // make compounds of not bound members
865             TopoDS_Compound comp[2];
866             for ( int is2ndGroup = 0; is2ndGroup < 2; ++is2ndGroup ) {
867               builder.MakeCompound( comp[is2ndGroup] );
868               for ( mIt.Initialize( is2ndGroup ? theShape2:theShape1 ); mIt.More(); mIt.Next())
869                 if ( ! boundMembers[ is2ndGroup ].Contains( mIt.Value() ))
870                   builder.Add( comp[ is2ndGroup ], mIt.Value() );
871             }
872             // check if theMap contains initial association for the comp's
873             bool hasInitialAssoc = false;
874             if ( memberType == TopAbs_EDGE ) {
875               for ( TopExp_Explorer v( comp[0], TopAbs_VERTEX ); v.More(); v.Next())
876                 if ( theMap.IsBound( v.Current() )) {
877                   hasInitialAssoc = true;
878                   break;
879                 }
880             }
881             if ( hasInitialAssoc == bool( !theMap.IsEmpty() ))
882               ok = FindSubShapeAssociation( comp[0], theMesh1, comp[1], theMesh2, theMap );
883             else {
884               TShapeShapeMap tmpMap;
885               ok = FindSubShapeAssociation( comp[0], theMesh1, comp[1], theMesh2, tmpMap );
886               if ( ok ) {
887                 TopTools_DataMapIteratorOfDataMapOfShapeShape mapIt( tmpMap._map1to2 );
888                 for ( ; mapIt.More(); mapIt.Next() )
889                   theMap.Bind( mapIt.Key(), mapIt.Value());
890               }
891             }
892           }
893         }
894         return ok;
895       }
896       // Each edge of an edge group is shared by own faces
897       // ------------------------------------------------------------------
898       //
899       // map vertices to edges sharing them, avoid doubling edges in lists
900       TopTools_DataMapOfShapeListOfShape v2e[2];
901       for (int isFirst = 0; isFirst < 2; ++isFirst ) {
902         const TopoDS_Shape& group = isFirst ? theShape1 : theShape2;
903         TopTools_DataMapOfShapeListOfShape& veMap = v2e[ isFirst ? 0 : 1 ];
904         TopTools_MapOfShape addedEdges;
905         for ( TopExp_Explorer e( group, TopAbs_EDGE ); e.More(); e.Next() ) {
906           const TopoDS_Shape& edge = e.Current();
907           if ( addedEdges.Add( edge )) {
908             for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next()) {
909               const TopoDS_Shape& vertex = v.Current();
910               if ( !veMap.IsBound( vertex )) {
911                 TopTools_ListOfShape l;
912                 veMap.Bind( vertex, l );
913               }
914               veMap( vertex ).Append( edge );
915             }
916           }
917         }   
918       }
919       while ( !v2e[0].IsEmpty() )
920       {
921         // find a bound vertex
922         TopoDS_Vertex V[2];
923         TopTools_DataMapIteratorOfDataMapOfShapeListOfShape v2eIt( v2e[0] );
924         for ( ; v2eIt.More(); v2eIt.Next())
925           if ( theMap.IsBound( v2eIt.Key() )) {
926             V[0] = TopoDS::Vertex( v2eIt.Key() );
927             V[1] = TopoDS::Vertex( theMap( V[0] ));
928             break;
929           }
930         if ( V[0].IsNull() )
931           RETURN_BAD_RESULT("No more bound vertices");
932
933         while ( !V[0].IsNull() && v2e[0].IsBound( V[0] )) {
934           TopTools_ListOfShape& edges0 = v2e[0]( V[0] );
935           TopTools_ListOfShape& edges1 = v2e[1]( V[1] );
936           int nbE0 = edges0.Extent(), nbE1 = edges1.Extent();
937           if ( nbE0 != nbE1 )
938             RETURN_BAD_RESULT("Different nb of edges: "<< nbE0 << " != " << nbE1);
939
940           if ( nbE0 == 1 )
941           {
942             TopoDS_Edge e0 = TopoDS::Edge( edges0.First() );
943             TopoDS_Edge e1 = TopoDS::Edge( edges1.First() );
944             v2e[0].UnBind( V[0] );
945             v2e[1].UnBind( V[1] );
946             InsertAssociation( e0, e1, theMap );
947             MESSAGE("Assoc edge " << theMesh1->GetMeshDS()->ShapeToIndex( e0 )<<
948                     " to "        << theMesh2->GetMeshDS()->ShapeToIndex( e1 ));
949             V[0] = GetNextVertex( e0, V[0] );
950             V[1] = GetNextVertex( e1, V[1] );
951             if ( !V[0].IsNull() ) {
952               InsertAssociation( V[0], V[1], theMap );
953               MESSAGE("Assoc vertex " << theMesh1->GetMeshDS()->ShapeToIndex( V[0] )<<
954                       " to "          << theMesh2->GetMeshDS()->ShapeToIndex( V[1] ));
955             }
956           }
957           else if ( nbE0 == 2 )
958           {
959             // one of edges must have both ends bound
960             TopoDS_Vertex v0e0 = GetNextVertex( TopoDS::Edge( edges0.First() ), V[0] );
961             TopoDS_Vertex v1e0 = GetNextVertex( TopoDS::Edge( edges0.Last() ),  V[0] );
962             TopoDS_Vertex v0e1 = GetNextVertex( TopoDS::Edge( edges1.First() ), V[1] );
963             TopoDS_Vertex v1e1 = GetNextVertex( TopoDS::Edge( edges1.Last() ),  V[1] );
964             TopoDS_Shape e0b, e1b, e0n, e1n, v1b; // bound and not-bound
965             TopoDS_Vertex v0n, v1n;
966             if ( theMap.IsBound( v0e0 )) {
967               v0n = v1e0; e0b = edges0.First(); e0n = edges0.Last(); v1b = theMap( v0e0 );
968             } else if ( theMap.IsBound( v1e0 )) {
969               v0n = v0e0; e0n = edges0.First(); e0b = edges0.Last(); v1b = theMap( v1e0 );
970             } else {
971               RETURN_BAD_RESULT("None of vertices bound");
972             }
973             if ( v1b.IsSame( v1e1 )) {
974               v1n = v0e1; e1n = edges1.First(); e1b = edges1.Last();
975             } else {
976               v1n = v1e1; e1b = edges1.First(); e1n = edges1.Last();
977             }
978             InsertAssociation( e0b, e1b, theMap );
979             InsertAssociation( e0n, e1n, theMap );
980             InsertAssociation( v0n, v1n, theMap );
981             MESSAGE("Assoc edge " << theMesh1->GetMeshDS()->ShapeToIndex( e0b )<<
982                     " to "        << theMesh2->GetMeshDS()->ShapeToIndex( e1b ));
983             MESSAGE("Assoc edge " << theMesh1->GetMeshDS()->ShapeToIndex( e0n )<<
984                     " to "        << theMesh2->GetMeshDS()->ShapeToIndex( e1n ));
985             MESSAGE("Assoc vertex " << theMesh1->GetMeshDS()->ShapeToIndex( v0n )<<
986                     " to "          << theMesh2->GetMeshDS()->ShapeToIndex( v1n ));
987             v2e[0].UnBind( V[0] );
988             v2e[1].UnBind( V[1] );
989             V[0] = v0n;
990             V[1] = v1n;
991           }
992           else {
993             RETURN_BAD_RESULT("Not implemented");
994           }
995         }
996       } //while ( !v2e[0].IsEmpty() )
997       return true;
998     }
999
1000     default:
1001       RETURN_BAD_RESULT("Unexpected shape type");
1002
1003     } // end switch by shape type
1004   } // end case of available initial vertex association
1005
1006   //======================================================================
1007   // 4) NO INITIAL VERTEX ASSOCIATION
1008   //======================================================================
1009
1010   switch ( theShape1.ShapeType() ) {
1011
1012   case TopAbs_EDGE: {
1013     // ----------------------------------------------------------------------
1014     TopoDS_Edge edge1 = TopoDS::Edge( theShape1 );
1015     TopoDS_Edge edge2 = TopoDS::Edge( theShape2 );
1016     if ( isPropagationPossible( theMesh1, theMesh2 ))
1017     {
1018       TopoDS_Edge prpEdge = GetPropagationEdge( theMesh1, edge2, edge1 ).second;
1019       if ( !prpEdge.IsNull() )
1020       {
1021         TopoDS_Vertex VV1[2], VV2[2];
1022         TopExp::Vertices( edge1,   VV1[0], VV1[1], true );
1023         TopExp::Vertices( prpEdge, VV2[0], VV2[1], true );
1024         InsertAssociation( VV1[ 0 ], VV2[ 0 ], theMap );
1025         InsertAssociation( VV1[ 1 ], VV2[ 1 ], theMap );
1026         if ( VV1[0].IsSame( VV1[1] ) || // one of edges is closed
1027              VV2[0].IsSame( VV2[1] ) )
1028         {
1029           InsertAssociation( edge1, prpEdge, theMap ); // insert with a proper orientation
1030         }
1031         InsertAssociation( theShape1, theShape2, theMap );
1032         theMap.SetAssocType( TShapeShapeMap::PROPAGATION );
1033         return true; // done
1034       }
1035     }
1036     if ( SMESH_MesherHelper::IsClosedEdge( edge1 ) &&
1037          SMESH_MesherHelper::IsClosedEdge( edge2 ))
1038     {
1039       // TODO: find out a proper orientation (is it possible?)
1040       InsertAssociation( edge1, edge2, theMap ); // insert with a proper orientation
1041       InsertAssociation( TopExp::FirstVertex(edge1), TopExp::FirstVertex(edge2),
1042                          theMap );
1043       InsertAssociation( theShape1, theShape2, theMap );
1044       return true; // done
1045     }
1046     break; // try by vertex closeness
1047   }
1048
1049   case TopAbs_FACE: {
1050     // ----------------------------------------------------------------------
1051     if ( isPropagationPossible( theMesh1, theMesh2 )) // try by propagation in one mesh
1052     {
1053       TopoDS_Face face1 = TopoDS::Face(theShape1);
1054       TopoDS_Face face2 = TopoDS::Face(theShape2);
1055       if ( face1.Orientation() >= TopAbs_INTERNAL ) face1.Orientation( TopAbs_FORWARD );
1056       if ( face2.Orientation() >= TopAbs_INTERNAL ) face2.Orientation( TopAbs_FORWARD );
1057       TopoDS_Edge edge1, edge2;
1058       // get outer edge of theShape1
1059       TopoDS_Shape wire = OuterShape( face1, TopAbs_WIRE );
1060       //edge1 = TopoDS::Edge( OuterShape( face1, TopAbs_EDGE ));
1061       // use map to find the closest propagation edge
1062       map<int, pair< TopoDS_Edge, TopoDS_Edge > > propag_edges;
1063       for ( TopoDS_Iterator edgeIt( wire ); edgeIt.More(); edgeIt.Next() )
1064       {
1065         edge1 = TopoDS::Edge( edgeIt.Value() );
1066         // find out if any edge of face2 is a propagation edge of outer edge1
1067         for ( TopExp_Explorer exp( face2, TopAbs_EDGE ); exp.More(); exp.Next() ) {
1068           edge2 = TopoDS::Edge( exp.Current() );
1069           pair<int,TopoDS_Edge> step_edge = GetPropagationEdge( theMesh1, edge2, edge1 );
1070           if ( !step_edge.second.IsNull() ) { // propagation found
1071             propag_edges.insert( make_pair( step_edge.first,
1072                                             ( make_pair( edge1, step_edge.second ))));
1073             if ( step_edge.first == 1 ) break; // most close found
1074           }
1075         }
1076         if ( !propag_edges.empty() && propag_edges.begin()->first == 1 ) break;
1077       }
1078       if ( !propag_edges.empty() ) // propagation found
1079       {
1080         edge1 = propag_edges.begin()->second.first;
1081         edge2 = propag_edges.begin()->second.second;
1082         TopoDS_Vertex VV1[2], VV2[2];
1083         TopExp::Vertices( edge1, VV1[0], VV1[1], true );
1084         TopExp::Vertices( edge2, VV2[0], VV2[1], true );
1085         list< TopoDS_Edge > edges1, edges2;
1086         int nbE = FindFaceAssociation( face1, VV1, face2, VV2, edges1, edges2 );
1087         if ( !nbE ) RETURN_BAD_RESULT("FindFaceAssociation() failed");
1088         // take care of proper association of propagated edges
1089         bool same1 = edge1.IsSame( edges1.front() );
1090         bool same2 = edge2.IsSame( edges2.front() );
1091         if ( same1 != same2 )
1092         {
1093           reverseEdges(edges2, nbE);
1094           if ( nbE != 2 ) // 2 degen edges of 4 (issue 0021144)
1095             edges2.splice( edges2.end(), edges2, edges2.begin());
1096         }
1097         // store association
1098         list< TopoDS_Edge >::iterator eIt1 = edges1.begin();
1099         list< TopoDS_Edge >::iterator eIt2 = edges2.begin();
1100         for ( ; eIt1 != edges1.end(); ++eIt1, ++eIt2 )
1101         {
1102           InsertAssociation( *eIt1, *eIt2, theMap );
1103           VV1[0] = TopExp::FirstVertex( *eIt1, true );
1104           VV2[0] = TopExp::FirstVertex( *eIt2, true );
1105           InsertAssociation( VV1[0], VV2[0], theMap );
1106         }
1107         InsertAssociation( theShape1, theShape2, theMap );
1108         theMap.SetAssocType( TShapeShapeMap::PROPAGATION );
1109         return true;
1110       }
1111     }
1112     break; // try by vertex closeness
1113   }
1114   case TopAbs_COMPOUND: {
1115     // ----------------------------------------------------------------------
1116     if ( isPropagationPossible( theMesh1, theMesh2 )) {
1117
1118       // try to accosiate all using propagation
1119       if ( assocGroupsByPropagation( theShape1, theShape2, *theMesh1, theMap ))
1120         return true;
1121
1122       // find a boundary edge of theShape1
1123       TopoDS_Edge E = GetBoundaryEdge( theShape1, *theMesh1 );
1124       if ( E.IsNull() )
1125         break; // try by vertex closeness
1126
1127       // find association for vertices of edge E
1128       TopoDS_Vertex VV1[2], VV2[2];
1129       for(TopExp_Explorer eexp(E, TopAbs_VERTEX); eexp.More(); eexp.Next()) {
1130         TopoDS_Vertex V1 = TopoDS::Vertex( eexp.Current() );
1131         // look for an edge ending in E whose one vertex is in theShape1
1132         // and the other, in theShape2
1133         const TopTools_ListOfShape& Ancestors = theMesh1->GetAncestors(V1);
1134         TopTools_ListIteratorOfListOfShape ita(Ancestors);
1135         for(; ita.More(); ita.Next()) {
1136           if( ita.Value().ShapeType() != TopAbs_EDGE ) continue;
1137           TopoDS_Edge edge = TopoDS::Edge(ita.Value());
1138           bool FromShape1 = false;
1139           for(TopExp_Explorer expe(theShape1, TopAbs_EDGE); expe.More(); expe.Next() ) {
1140             if(edge.IsSame(expe.Current())) {
1141               FromShape1 = true;
1142               break;
1143             }
1144           }
1145           if(!FromShape1) {
1146             // is it an edge between theShape1 and theShape2?
1147             TopExp_Explorer expv(edge, TopAbs_VERTEX);
1148             TopoDS_Vertex V2 = TopoDS::Vertex( expv.Current() );
1149             if(V2.IsSame(V1)) {
1150               expv.Next();
1151               V2 = TopoDS::Vertex( expv.Current() );
1152             }
1153             bool FromShape2 = false;
1154             for ( expv.Init( theShape2, TopAbs_VERTEX ); expv.More(); expv.Next()) {
1155               if ( V2.IsSame( expv.Current() )) {
1156                 FromShape2 = true;
1157                 break;
1158               }
1159             }
1160             if ( FromShape2 ) {
1161               if ( VV1[0].IsNull() )
1162                 VV1[0] = V1, VV2[0] = V2;
1163               else
1164                 VV1[1] = V1, VV2[1] = V2;
1165               break; // from loop on ancestors of V1
1166             }
1167           }
1168         }
1169       }
1170       if ( !VV1[1].IsNull() ) {
1171         InsertAssociation( VV1[0], VV2[0], theMap );
1172         InsertAssociation( VV1[1], VV2[1], theMap );
1173         if ( FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap ))
1174         {
1175           theMap.SetAssocType( TShapeShapeMap::PROPAGATION );
1176           return true;
1177         }
1178       }
1179     }
1180     break; // try by vertex closeness
1181   }
1182   default:;
1183   }
1184
1185   // 4.b) Find association by closeness of vertices
1186   // ----------------------------------------------
1187
1188   TopTools_IndexedMapOfShape vMap1, vMap2;
1189   TopExp::MapShapes( theShape1, TopAbs_VERTEX, vMap1 );
1190   TopExp::MapShapes( theShape2, TopAbs_VERTEX, vMap2 );
1191   TopoDS_Vertex VV1[2], VV2[2];
1192
1193   if ( vMap1.Extent() != vMap2.Extent() )
1194   {
1195     if ( SMESH_MesherHelper:: Count( theShape1, TopAbs_EDGE, /*ignoreSame=*/false ) !=
1196          SMESH_MesherHelper:: Count( theShape2, TopAbs_EDGE, /*ignoreSame=*/false ))
1197       RETURN_BAD_RESULT("Different nb of vertices");
1198   }
1199
1200   if ( vMap1.Extent() == 1 || vMap2.Extent() == 1 ) {
1201     InsertAssociation( vMap1(1), vMap2(1), theMap );
1202     if ( theShape1.ShapeType() == TopAbs_EDGE ) {
1203       if ( vMap1.Extent() == 2 )
1204         InsertAssociation( vMap1(2), vMap2(1), theMap );
1205       else if ( vMap2.Extent() == 2 )
1206         InsertAssociation( vMap2(2), vMap1(1), theMap );
1207       InsertAssociation( theShape1, theShape2, theMap );
1208       return true;
1209     }
1210     return FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap);
1211   }
1212
1213   // Try to associate by common vertices of an edge
1214   for ( int i = 1; i <= vMap1.Extent(); ++i )
1215   {
1216     const TopoDS_Shape& v1 = vMap1(i);
1217     if ( vMap2.Contains( v1 ))
1218     {
1219       // find an egde sharing v1 and sharing at the same time another common vertex
1220       PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( v1, *theMesh1, TopAbs_EDGE);
1221       bool edgeFound = false;
1222       while ( edgeIt->more() && !edgeFound )
1223       {
1224         TopoDS_Edge edge = TopoDS::Edge( edgeIt->next()->Oriented(TopAbs_FORWARD));
1225         TopExp::Vertices(edge, VV1[0], VV1[1]);
1226         if ( !VV1[0].IsSame( VV1[1] ))
1227           edgeFound = ( vMap2.Contains( VV1[ v1.IsSame(VV1[0]) ? 1:0]));
1228       }
1229       if ( edgeFound )
1230       {
1231         InsertAssociation( VV1[0], VV1[0], theMap );
1232         InsertAssociation( VV1[1], VV1[1], theMap );
1233         if (FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap ))
1234         {
1235           theMap.SetAssocType( TShapeShapeMap::COMMON_VERTEX );
1236           return true;
1237         }
1238       }
1239     }
1240   }
1241
1242   // Find transformation to make the shapes be of similar size at same location
1243
1244   Bnd_Box box[2];
1245   for ( int i = 1; i <= vMap1.Extent(); ++i )
1246     box[ 0 ].Add( BRep_Tool::Pnt ( TopoDS::Vertex( vMap1( i ))));
1247   for ( int i = 1; i <= vMap2.Extent(); ++i )
1248     box[ 1 ].Add( BRep_Tool::Pnt ( TopoDS::Vertex( vMap2( i ))));
1249
1250   gp_Pnt gc[2]; // box center
1251   double x0,y0,z0, x1,y1,z1;
1252   box[0].Get( x0,y0,z0, x1,y1,z1 );
1253   gc[0] = 0.5 * ( gp_XYZ( x0,y0,z0 ) + gp_XYZ( x1,y1,z1 ));
1254   box[1].Get( x0,y0,z0, x1,y1,z1 );
1255   gc[1] = 0.5 * ( gp_XYZ( x0,y0,z0 ) + gp_XYZ( x1,y1,z1 ));
1256
1257   // 1 -> 2
1258   gp_Vec vec01( gc[0], gc[1] );
1259   double scale = sqrt( box[1].SquareExtent() / box[0].SquareExtent() );
1260
1261   // Find 2 closest vertices
1262
1263   // get 2 linked vertices of shape 1 not belonging to an inner wire of a face
1264   std::list< TopoDS_Edge > allBndEdges1;
1265   if ( !getOuterEdges( theShape1, *theMesh1, allBndEdges1 ))
1266   {
1267     if ( theShape1.ShapeType() != TopAbs_FACE )
1268       RETURN_BAD_RESULT("Edge not found");
1269     return assocFewEdgesFaces( TopoDS::Face( theShape1 ), theMesh1, 
1270                                TopoDS::Face( theShape2 ), theMesh2, theMap );
1271   }
1272   std::list< TopoDS_Edge >::iterator edge1 = allBndEdges1.begin();
1273   double minDist = std::numeric_limits<double>::max();
1274   for ( int nbChecked=0; edge1 != allBndEdges1.end() && nbChecked++ < 10; ++edge1 )
1275   {
1276     TopoDS_Vertex edge1VV[2];
1277     TopExp::Vertices( TopoDS::Edge( edge1->Oriented(TopAbs_FORWARD)), edge1VV[0], edge1VV[1]);
1278     if ( edge1VV[0].IsSame( edge1VV[1] ))
1279       continue;//RETURN_BAD_RESULT("Only closed edges");
1280
1281     // find vertices closest to 2 linked vertices of shape 1
1282     double dist2[2] = { 1e+100, 1e+100 };
1283     TopoDS_Vertex edge2VV[2];
1284     for ( int i1 = 0; i1 < 2; ++i1 )
1285     {
1286       gp_Pnt p1 = BRep_Tool::Pnt( edge1VV[ i1 ]);
1287       p1.Scale( gc[0], scale );
1288       p1.Translate( vec01 );
1289       if ( !i1 ) {
1290         // select a closest vertex among all ones in vMap2
1291         for ( int i2 = 1; i2 <= vMap2.Extent(); ++i2 )
1292         {
1293           TopoDS_Vertex V2 = TopoDS::Vertex( vMap2( i2 ));
1294           gp_Pnt        p2 = BRep_Tool::Pnt ( V2 );
1295           double        d2 = p1.SquareDistance( p2 );
1296           if ( d2 < dist2[ 0 ] && d2 < minDist ) {
1297             edge2VV[ 0 ] = V2;
1298             dist2  [ 0 ] = d2;
1299           }
1300         }
1301       }
1302       else if ( !edge2VV[0].IsNull() ) {
1303         // select a closest vertex among ends of edges meeting at edge2VV[0]
1304         PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( edge2VV[0],
1305                                                                      *theMesh2, TopAbs_EDGE);
1306         while ( const TopoDS_Shape* edge2 = edgeIt->next() )
1307           for ( TopoDS_Iterator itV2( *edge2 ); itV2.More(); itV2.Next() )
1308           {
1309             if ( itV2.Value().IsSame( edge2VV[ 0 ])) continue;
1310             if ( !vMap2.Contains( itV2.Value()    )) continue;
1311             TopoDS_Vertex V2 = TopoDS::Vertex( itV2.Value() );
1312             gp_Pnt        p2 = BRep_Tool::Pnt ( V2 );
1313             double        d2 = p1.SquareDistance( p2 );
1314             if ( d2 < dist2[1] && d2 < minDist ) {
1315               edge2VV[ 1 ] = V2;
1316               dist2  [ 1 ] = d2;
1317             }
1318           }
1319       }
1320     }
1321     if ( dist2[0] + dist2[1] < minDist ) {
1322       VV1[0] = edge1VV[0];
1323       VV1[1] = edge1VV[1];
1324       VV2[0] = edge2VV[0];
1325       VV2[1] = edge2VV[1];
1326       minDist = dist2[0] + dist2[1];
1327       if ( minDist < 1e-10 )
1328         break;
1329     }
1330   }
1331   theMap.SetAssocType( TShapeShapeMap::CLOSE_VERTEX );
1332
1333   InsertAssociation( VV1[ 0 ], VV2[ 0 ], theMap );
1334   InsertAssociation( VV1[ 1 ], VV2[ 1 ], theMap );
1335   MESSAGE("Initial assoc VERT " << theMesh1->GetMeshDS()->ShapeToIndex( VV1[ 0 ] )<<
1336           " to "                << theMesh2->GetMeshDS()->ShapeToIndex( VV2[ 0 ] )<<
1337           "\nand         VERT " << theMesh1->GetMeshDS()->ShapeToIndex( VV1[ 1 ] )<<
1338           " to "                << theMesh2->GetMeshDS()->ShapeToIndex( VV2[ 1 ] ));
1339   if ( theShape1.ShapeType() == TopAbs_EDGE ) {
1340     InsertAssociation( theShape1, theShape2, theMap );
1341     return true;
1342   }
1343
1344   return FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap );
1345 }
1346
1347 //================================================================================
1348 /*
1349  * Find association of edges of faces
1350  *  \param face1 - face 1
1351  *  \param VV1 - vertices of face 1
1352  *  \param face2 - face 2
1353  *  \param VV2 - vertices of face 2 associated with ones of face 1
1354  *  \param edges1 - out list of edges of face 1
1355  *  \param edges2 - out list of edges of face 2
1356  *  \param isClosenessAssoc - is association starting by VERTEX closeness
1357  *  \retval int - nb of edges in an outer wire in a success case, else zero
1358  */
1359 //================================================================================
1360
1361 int StdMeshers_ProjectionUtils::FindFaceAssociation(const TopoDS_Face&    face1,
1362                                                     TopoDS_Vertex         VV1[2],
1363                                                     const TopoDS_Face&    face2,
1364                                                     TopoDS_Vertex         VV2[2],
1365                                                     list< TopoDS_Edge > & edges1,
1366                                                     list< TopoDS_Edge > & edges2,
1367                                                     const bool            isClosenessAssoc)
1368 {
1369   bool OK = false;
1370   list< int > nbEInW1, nbEInW2;
1371   list< TopoDS_Edge >::iterator edgeIt;
1372   int i_ok_wire_algo = -1;
1373   for ( int outer_wire_algo = 0; outer_wire_algo < 2 && !OK; ++outer_wire_algo )
1374   {
1375     edges1.clear();
1376     edges2.clear();
1377
1378     if ( SMESH_Block::GetOrderedEdges( face1, edges1, nbEInW1, VV1[0], outer_wire_algo) !=
1379          SMESH_Block::GetOrderedEdges( face2, edges2, nbEInW2, VV2[0], outer_wire_algo) )
1380       CONT_BAD_RESULT("Different number of wires in faces ");
1381
1382     if ( nbEInW1 != nbEInW2 && outer_wire_algo == 0 &&
1383          ( std::accumulate( nbEInW1.begin(), nbEInW1.end(), 0) !=
1384            std::accumulate( nbEInW2.begin(), nbEInW2.end(), 0)))
1385       RETURN_BAD_RESULT("Different number of edges in faces");
1386
1387     if ( nbEInW1.front() != nbEInW2.front() )
1388       CONT_BAD_RESULT("Different number of edges in the outer wire: " <<
1389                       nbEInW1.front() << " != " << nbEInW2.front());
1390
1391     i_ok_wire_algo = outer_wire_algo;
1392
1393     // Define if we need to reverse one of wires to make edges in lists match each other
1394
1395     bool reverse = false;
1396     const bool severalWires = ( nbEInW1.size() > 1 );
1397
1398     if ( !VV1[1].IsSame( TopExp::LastVertex( edges1.front(), true )))
1399     {
1400       reverse = true;
1401       // check if the second vertex belongs to the first or last edge in the wire
1402       edgeIt = --edges1.end(); // pointer to the last edge in the outer wire
1403       if ( severalWires ) {
1404         edgeIt = edges1.begin();
1405         std::advance( edgeIt, nbEInW1.front()-1 );
1406       }
1407       if ( TopExp::FirstVertex( *edgeIt ).IsSame( TopExp::LastVertex( *edgeIt )) &&
1408            SMESH_Algo::isDegenerated( *edgeIt )) {
1409         --edgeIt; // skip a degenerated edge (www.salome-platform.org/forum/forum_11/173031193)
1410       }
1411       if ( !VV1[1].IsSame( TopExp::FirstVertex( *edgeIt, true ))) {
1412         CONT_BAD_RESULT("GetOrderedEdges() failed");
1413       }
1414     }
1415     if ( !VV2[1].IsSame( TopExp::LastVertex( edges2.front(), true )))
1416     {
1417       reverse = !reverse;
1418       // check if the second vertex belongs to the first or last edge in the wire
1419       edgeIt = --edges2.end(); // pointer to the last edge in the outer wire
1420       if ( severalWires ) {
1421         edgeIt = edges2.begin();
1422         std::advance( edgeIt, nbEInW2.front()-1 );
1423       }
1424       if ( TopExp::FirstVertex( *edgeIt ).IsSame( TopExp::LastVertex( *edgeIt )) &&
1425            SMESH_Algo::isDegenerated( *edgeIt )) {
1426         --edgeIt;  // skip a degenerated edge
1427       }
1428       if ( !VV2[1].IsSame( TopExp::FirstVertex( *edgeIt, true ))) {
1429         CONT_BAD_RESULT("GetOrderedEdges() failed");
1430       }
1431     }
1432     if ( reverse )
1433     {
1434       reverseEdges( edges2 , nbEInW2.front());
1435
1436       if ( SMESH_Algo::isDegenerated( edges2.front() ))
1437       {
1438         // move a degenerated edge to the back of the outer wire
1439         edgeIt = edges2.end();
1440         if ( severalWires ) {
1441           edgeIt = edges2.begin();
1442           std::advance( edgeIt, nbEInW2.front() );
1443         }
1444         edges2.splice( edgeIt, edges2, edges2.begin() );
1445       }
1446       if (( VV1[1].IsSame( TopExp::LastVertex( edges1.front(), true ))) !=
1447           ( VV2[1].IsSame( TopExp::LastVertex( edges2.front(), true ))))
1448         CONT_BAD_RESULT("GetOrderedEdges() failed");
1449     }
1450     OK = true;
1451
1452   } // loop algos getting an outer wire
1453
1454   if ( OK && nbEInW1.front() > 4 ) // care of a case where faces are closed (23032)
1455   {
1456     // check if the first edges are seam ones
1457     list< TopoDS_Edge >::iterator revSeam1, revSeam2;
1458     revSeam1 = std::find( ++edges1.begin(), edges1.end(), edges1.front().Reversed());
1459     revSeam2 = edges2.end();
1460     if ( revSeam1 != edges1.end() )
1461       revSeam2 = std::find( ++edges2.begin(), edges2.end(), edges2.front().Reversed());
1462     if ( revSeam2 != edges2.end() ) // two seams detected
1463     {
1464       bool reverse =
1465         std::distance( edges1.begin(), revSeam1 ) != std::distance( edges2.begin(), revSeam2 );
1466       if ( !reverse && isClosenessAssoc )
1467       {
1468         // compare orientations of a non-seam edges using 3D closeness;
1469         // look for a non-seam edges
1470         list< TopoDS_Edge >::iterator edge1 = ++edges1.begin();
1471         list< TopoDS_Edge >::iterator edge2 = ++edges2.begin();
1472         for ( ; edge1 != edges1.end(); ++edge1, ++edge2 )
1473         {
1474           if (( edge1 == revSeam1 ) ||
1475               ( SMESH_Algo::isDegenerated( *edge1 )) ||
1476               ( std::find( ++edges1.begin(), edges1.end(), edge1->Reversed()) != edges1.end() ))
1477             continue;
1478           gp_Pnt p1 = BRep_Tool::Pnt( VV1[0] );
1479           gp_Pnt p2 = BRep_Tool::Pnt( VV2[0] );
1480           gp_Vec vec2to1( p2, p1 );
1481
1482           gp_Pnt pp1[2], pp2[2];
1483           const double r = 0.2345;
1484           double f,l;
1485           Handle(Geom_Curve) C = BRep_Tool::Curve( *edge1, f,l );
1486           pp1[0] = C->Value( f * r + l * ( 1. - r ));
1487           pp1[1] = C->Value( l * r + f * ( 1. - r ));
1488           if ( edge1->Orientation() == TopAbs_REVERSED )
1489             std::swap( pp1[0], pp1[1] );
1490           C = BRep_Tool::Curve( *edge2, f,l );
1491           if ( C.IsNull() ) return 0;
1492           pp2[0] = C->Value( f * r + l * ( 1. - r )).Translated( vec2to1 );
1493           pp2[1] = C->Value( l * r + f * ( 1. - r )).Translated( vec2to1 );
1494           if ( edge2->Orientation() == TopAbs_REVERSED )
1495             std::swap( pp2[0], pp2[1] );
1496
1497           double dist00 = pp1[0].SquareDistance( pp2[0] );
1498           double dist01 = pp1[0].SquareDistance( pp2[1] );
1499           reverse = ( dist00 > dist01 );
1500           break;
1501         }
1502       }
1503       if ( reverse ) // make a seam counterpart be the first
1504       {
1505         list< TopoDS_Edge >::iterator outWireEnd = edges2.begin();
1506         std::advance( outWireEnd, nbEInW2.front() );
1507         edges2.splice( outWireEnd, edges2, edges2.begin(), ++revSeam2 );
1508         reverseEdges( edges2 , nbEInW2.front());
1509       }
1510     }
1511   }
1512   
1513   // Try to orient all (if !OK) or only internal wires (issue 0020996) by UV similarity
1514
1515   if (( !OK || nbEInW1.size() > 1 ) && i_ok_wire_algo > -1 )
1516   {
1517     // Check that Vec(VV1[0],VV1[1]) in 2D on face1 is the same
1518     // as Vec(VV2[0],VV2[1]) on face2
1519     double vTol = BRep_Tool::Tolerance( VV1[0] );
1520     BRepAdaptor_Surface surface1( face1, true );
1521     BRepAdaptor_Surface surface2( face2, true );
1522     // TODO: use TrsfFinder2D to superpose the faces
1523     gp_Pnt2d v0f1UV( surface1.FirstUParameter(), surface1.FirstVParameter() );
1524     gp_Pnt2d v0f2UV( surface2.FirstUParameter(), surface2.FirstVParameter() );
1525     gp_Pnt2d v1f1UV( surface1.LastUParameter(),  surface1.LastVParameter() );
1526     gp_Pnt2d v1f2UV( surface2.LastUParameter(),  surface2.LastVParameter() );
1527     double vTolUV =
1528       surface1.UResolution( vTol ) + surface1.VResolution( vTol ); // let's be tolerant
1529     // VV1[0] = TopExp::FirstVertex( edges1.front(), true ); // ori is important if face is closed
1530     // VV1[1] = TopExp::LastVertex ( edges1.front(), true );
1531     // VV2[0] = TopExp::FirstVertex( edges2.front(), true );
1532     // VV2[1] = TopExp::LastVertex ( edges2.front(), true );
1533     // gp_Pnt2d v0f1UV = BRep_Tool::Parameters( VV1[0], face1 );
1534     // gp_Pnt2d v0f2UV = BRep_Tool::Parameters( VV2[0], face2 );
1535     // gp_Pnt2d v1f1UV = BRep_Tool::Parameters( VV1[1], face1 );
1536     // gp_Pnt2d v1f2UV = BRep_Tool::Parameters( VV2[1], face2 );
1537     gp_Vec2d v01f1Vec( v0f1UV, v1f1UV );
1538     gp_Vec2d v01f2Vec( v0f2UV, v1f2UV );
1539     if ( Abs( v01f1Vec.X()-v01f2Vec.X()) < vTolUV &&
1540          Abs( v01f1Vec.Y()-v01f2Vec.Y()) < vTolUV )
1541     {
1542       if ( !OK /*i_ok_wire_algo != 1*/ )
1543       {
1544         edges1.clear();
1545         edges2.clear();
1546         SMESH_Block::GetOrderedEdges( face1, edges1, nbEInW1, VV1[0], i_ok_wire_algo);
1547         SMESH_Block::GetOrderedEdges( face2, edges2, nbEInW2, VV2[0], i_ok_wire_algo);
1548       }
1549       gp_XY dUV = v0f2UV.XY() - v0f1UV.XY(); // UV shift between 2 faces
1550       //
1551       // skip edges of the outer wire (if the outer wire is OK)
1552       list< int >::iterator nbE2, nbE1 = nbEInW1.begin();
1553       list< TopoDS_Edge >::iterator edge2Beg, edge1Beg = edges1.begin();
1554       if ( OK ) std::advance( edge1Beg, *nbE1++ );
1555       list< TopoDS_Edge >::iterator edge2End, edge1End;
1556       //
1557       // find corresponding wires of face2
1558       for ( int iW1 = OK; nbE1 != nbEInW1.end(); ++nbE1, ++iW1 ) // loop on wires of face1
1559       {
1560         // reach an end of edges of a current wire1
1561         edge1End = edge1Beg;
1562         std::advance( edge1End, *nbE1 );
1563         // UV on face1 to find on face2
1564         TopoDS_Vertex v01 = SMESH_MesherHelper::IthVertex(0,*edge1Beg);
1565         TopoDS_Vertex v11 = SMESH_MesherHelper::IthVertex(1,*edge1Beg);
1566         v0f1UV = BRep_Tool::Parameters( v01, face1 );
1567         v1f1UV = BRep_Tool::Parameters( v11, face1 );
1568         v0f1UV.ChangeCoord() += dUV;
1569         v1f1UV.ChangeCoord() += dUV;
1570         //
1571         // look through wires of face2
1572         edge2Beg = edges2.begin();
1573         nbE2     = nbEInW2.begin();
1574         if ( OK ) std::advance( edge2Beg, *nbE2++ );
1575         for ( int iW2 = OK; nbE2 != nbEInW2.end(); ++nbE2, ++iW2 ) // loop on wires of face2
1576         {
1577           // reach an end of edges of a current wire2
1578           edge2End = edge2Beg;
1579           std::advance( edge2End, *nbE2 );
1580           if ( *nbE1 == *nbE2 && iW2 >= iW1 )
1581           {
1582             // rotate edge2 untill coincidence with edge1 in 2D
1583             int i = *nbE2;
1584             bool sameUV = false;
1585             while ( !( sameUV = sameVertexUV( *edge2Beg, face2, 0, v0f1UV, vTolUV )) && --i > 0 )
1586               // move edge2Beg to place before edge2End
1587               edges2.splice( edge2End, edges2, edge2Beg++ );
1588
1589             if ( sameUV )
1590             {
1591               if ( iW1 == 0 ) OK = true; // OK is for the first wire
1592
1593               // reverse edges2 if needed
1594               if ( SMESH_MesherHelper::IsClosedEdge( *edge1Beg ))
1595               {
1596                 double f,l;
1597                 Handle(Geom2d_Curve) c1 = BRep_Tool::CurveOnSurface( *edge1Beg, face1,f,l );
1598                 if (  edge1Beg->Orientation() == TopAbs_REVERSED )
1599                   std::swap( f,l );
1600                 gp_Pnt2d uv1 = dUV + c1->Value( f * 0.8 + l * 0.2 ).XY();
1601
1602                 Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( *edge2Beg, face2,f,l );
1603                 if (  edge2Beg->Orientation() == TopAbs_REVERSED )
1604                   std::swap( f,l );
1605                 gp_Pnt2d uv2 = c2->Value( f * 0.8 + l * 0.2 );
1606                 gp_Pnt2d uv3 = c2->Value( l * 0.8 + f * 0.2 );
1607
1608                 if ( uv1.SquareDistance( uv2 ) > uv1.SquareDistance( uv3 ))
1609                   edge2Beg->Reverse();
1610               }
1611               else
1612               {
1613                 if ( !sameVertexUV( *edge2Beg, face2, 1, v1f1UV, vTolUV ))
1614                   reverseEdges( edges2 , *nbE2, std::distance( edges2.begin(),edge2Beg ));
1615               }
1616
1617               // put wire2 at a right place within edges2
1618               if ( iW1 != iW2 ) {
1619                 list< TopoDS_Edge >::iterator place2 = edges2.begin();
1620                 std::advance( place2, std::distance( edges1.begin(), edge1Beg ));
1621                 edges2.splice( place2, edges2, edge2Beg, edge2End );
1622                 // move nbE2 as well
1623                 list< int >::iterator placeNbE2 = nbEInW2.begin();
1624                 std::advance( placeNbE2, iW1 );
1625                 nbEInW2.splice( placeNbE2, nbEInW2, nbE2 );
1626               }
1627               break;
1628             }
1629           }
1630           // prepare to the next wire loop
1631           edge2Beg = edge2End;
1632         }
1633         edge1Beg = edge1End;
1634       }
1635     }
1636   }
1637
1638   const int nbEdges = nbEInW1.front();
1639   if ( OK && nbEdges == 2 )
1640   {
1641     // if wires include 2 edges, it's impossible to associate them using
1642     // topological information only. Try to use length of edges for association.
1643     double l1[2], l2[2];
1644     edgeIt = edges1.begin();
1645     l1[0] = SMESH_Algo::EdgeLength( *edgeIt++ );
1646     l1[1] = SMESH_Algo::EdgeLength( *edgeIt++ );
1647     if ( Abs( l1[0] - l1[1] ) > 0.1 * Max( l1[0], l1[1] ) )
1648     {
1649       edgeIt = edges2.begin();
1650       l2[0] = SMESH_Algo::EdgeLength( *edgeIt++ );
1651       l2[1] = SMESH_Algo::EdgeLength( *edgeIt++ );
1652       if (( l1[0] < l1[1] ) != ( l2[0] < l2[1] ))
1653       {
1654         reverseEdges( edges2, nbEdges );
1655       }
1656     }
1657   }
1658
1659   return OK ? nbEInW1.front() : 0;
1660 }
1661
1662 //=======================================================================
1663 //function : InitVertexAssociation
1664 //purpose  : 
1665 //=======================================================================
1666
1667 void StdMeshers_ProjectionUtils::InitVertexAssociation( const SMESH_Hypothesis* theHyp,
1668                                                         TShapeShapeMap &        theAssociationMap)
1669 {
1670   string hypName = theHyp->GetName();
1671   if ( hypName == "ProjectionSource1D" ) {
1672     const StdMeshers_ProjectionSource1D * hyp =
1673       static_cast<const StdMeshers_ProjectionSource1D*>( theHyp );
1674     if ( hyp->HasVertexAssociation() )
1675       InsertAssociation( hyp->GetTargetVertex(),hyp->GetSourceVertex(),theAssociationMap );
1676   }
1677   else if ( hypName == "ProjectionSource2D" ) {
1678     const StdMeshers_ProjectionSource2D * hyp =
1679       static_cast<const StdMeshers_ProjectionSource2D*>( theHyp );
1680     if ( hyp->HasVertexAssociation() ) {
1681       InsertAssociation( hyp->GetTargetVertex(1),hyp->GetSourceVertex(1),theAssociationMap);
1682       InsertAssociation( hyp->GetTargetVertex(2),hyp->GetSourceVertex(2),theAssociationMap);
1683     }
1684   }
1685   else if ( hypName == "ProjectionSource3D" ) {
1686     const StdMeshers_ProjectionSource3D * hyp =
1687       static_cast<const StdMeshers_ProjectionSource3D*>( theHyp );
1688     if ( hyp->HasVertexAssociation() ) {
1689       InsertAssociation( hyp->GetTargetVertex(1),hyp->GetSourceVertex(1),theAssociationMap);
1690       InsertAssociation( hyp->GetTargetVertex(2),hyp->GetSourceVertex(2),theAssociationMap);
1691     }
1692   }
1693 }
1694
1695 //=======================================================================
1696 /*
1697  * Inserts association theShape1 <-> theShape2 to TShapeShapeMap
1698  *  \param theShape1 - target shape
1699  *  \param theShape2 - source shape
1700  *  \param theAssociationMap - association map 
1701  *  \retval bool - true if there was no association for these shapes before
1702  */
1703 //=======================================================================
1704
1705 bool StdMeshers_ProjectionUtils::InsertAssociation( const TopoDS_Shape& theShape1, // tgt
1706                                                     const TopoDS_Shape& theShape2, // src
1707                                                     TShapeShapeMap &    theAssociationMap)
1708 {
1709   if ( !theShape1.IsNull() && !theShape2.IsNull() ) {
1710     SHOW_SHAPE(theShape1,"Assoc ");
1711     SHOW_SHAPE(theShape2," to ");
1712     bool isNew = ( theAssociationMap.Bind( theShape1, theShape2 ));
1713     return isNew;
1714   }
1715   else {
1716     throw SALOME_Exception("StdMeshers_ProjectionUtils: attempt to associate NULL shape");
1717   }
1718   return false;
1719 }
1720
1721 //=======================================================================
1722 /*
1723  * Finds an edge by its vertices in a main shape of the mesh
1724  *  \param aMesh - the mesh
1725  *  \param V1 - vertex 1
1726  *  \param V2 - vertex 2
1727  *  \retval TopoDS_Edge - found edge
1728  */
1729 //=======================================================================
1730
1731 TopoDS_Edge StdMeshers_ProjectionUtils::GetEdgeByVertices( SMESH_Mesh*          theMesh,
1732                                                            const TopoDS_Vertex& theV1,
1733                                                            const TopoDS_Vertex& theV2)
1734 {
1735   if ( theMesh && !theV1.IsNull() && !theV2.IsNull() )
1736   {
1737     TopTools_ListIteratorOfListOfShape ancestorIt( theMesh->GetAncestors( theV1 ));
1738     for ( ; ancestorIt.More(); ancestorIt.Next() )
1739       if ( ancestorIt.Value().ShapeType() == TopAbs_EDGE )
1740         for ( TopExp_Explorer expV ( ancestorIt.Value(), TopAbs_VERTEX );
1741               expV.More();
1742               expV.Next() )
1743           if ( theV2.IsSame( expV.Current() ))
1744             return TopoDS::Edge( ancestorIt.Value() );
1745   }
1746   return TopoDS_Edge();
1747 }
1748
1749 //================================================================================
1750 /*
1751  * Return another face sharing an edge
1752  *  \param edgeToFaces - data map of descendants to ancestors
1753  *  \param edge - edge
1754  *  \param face - face
1755  *  \retval TopoDS_Face - found face
1756  */
1757 //================================================================================
1758
1759 TopoDS_Face StdMeshers_ProjectionUtils::GetNextFace( const TAncestorMap& edgeToFaces,
1760                                                      const TopoDS_Edge&  edge,
1761                                                      const TopoDS_Face&  face)
1762 {
1763 //   if ( !edge.IsNull() && !face.IsNull() && edgeToFaces.Contains( edge ))
1764   if ( !edge.IsNull() && edgeToFaces.Contains( edge )) // PAL16202
1765   {
1766     TopTools_ListIteratorOfListOfShape ancestorIt( edgeToFaces.FindFromKey( edge ));
1767     for ( ; ancestorIt.More(); ancestorIt.Next() )
1768       if ( ancestorIt.Value().ShapeType() == TopAbs_FACE &&
1769            !face.IsSame( ancestorIt.Value() ))
1770         return TopoDS::Face( ancestorIt.Value() );
1771   }
1772   return TopoDS_Face();
1773 }
1774
1775 //================================================================================
1776 /*
1777  * Return other vertex of an edge
1778  */
1779 //================================================================================
1780
1781 TopoDS_Vertex StdMeshers_ProjectionUtils::GetNextVertex(const TopoDS_Edge&   edge,
1782                                                         const TopoDS_Vertex& vertex)
1783 {
1784   TopoDS_Vertex vF,vL;
1785   TopExp::Vertices(edge,vF,vL);
1786   if ( vF.IsSame( vL ))
1787     return TopoDS_Vertex();
1788   return vertex.IsSame( vF ) ? vL : vF; 
1789 }
1790
1791 //================================================================================
1792 /*
1793  * Return a propagation edge
1794  *  \param aMesh - mesh
1795  *  \param anEdge - edge to find by propagation
1796  *  \param fromEdge - start edge for propagation
1797  *  \param chain - return, if !NULL, a propagation chain passed till
1798  *         anEdge; if anEdge.IsNull() then a full propagation chain is returned;
1799  *         fromEdge is the 1st in the chain
1800  *  \retval pair<int,TopoDS_Edge> - propagation step and found edge
1801  */
1802 //================================================================================
1803
1804 pair<int,TopoDS_Edge>
1805 StdMeshers_ProjectionUtils::GetPropagationEdge( SMESH_Mesh*                 aMesh,
1806                                                 const TopoDS_Edge&          anEdge,
1807                                                 const TopoDS_Edge&          fromEdge,
1808                                                 TopTools_IndexedMapOfShape* chain)
1809 {
1810   TopTools_IndexedMapOfShape locChain;
1811   TopTools_IndexedMapOfShape& aChain = chain ? *chain : locChain;
1812   int step = 0;
1813
1814   //TopTools_IndexedMapOfShape checkedWires;
1815   BRepTools_WireExplorer aWE;
1816   TopoDS_Shape fourEdges[4];
1817
1818   // List of edges, added to chain on the previous cycle pass
1819   TopTools_ListOfShape listPrevEdges;
1820   listPrevEdges.Append( fromEdge );
1821   aChain.Add( fromEdge );
1822
1823   // Collect all edges pass by pass
1824   while (listPrevEdges.Extent() > 0)
1825   {
1826     step++;
1827     // List of edges, added to chain on this cycle pass
1828     TopTools_ListOfShape listCurEdges;
1829
1830     // Find the next portion of edges
1831     TopTools_ListIteratorOfListOfShape itE (listPrevEdges);
1832     for (; itE.More(); itE.Next())
1833     {
1834       const TopoDS_Shape& anE = itE.Value();
1835
1836       // Iterate on faces, having edge <anE>
1837       TopTools_ListIteratorOfListOfShape itA (aMesh->GetAncestors(anE));
1838       for (; itA.More(); itA.Next())
1839       {
1840         const TopoDS_Shape& aW = itA.Value();
1841
1842         // There are objects of different type among the ancestors of edge
1843         if ( aW.ShapeType() == TopAbs_WIRE /*&& checkedWires.Add( aW )*/)
1844         {
1845           Standard_Integer nb = 0, found = -1;
1846           for ( aWE.Init( TopoDS::Wire( aW )); aWE.More(); aWE.Next() ) {
1847             if (nb+1 > 4) {
1848               found = -1;
1849               break;
1850             }
1851             fourEdges[ nb ] = aWE.Current();
1852             if ( aWE.Current().IsSame( anE )) found = nb;
1853             nb++;
1854           }
1855           if (nb == 4 && found >= 0) {
1856             // Quadrangle face found, get an opposite edge
1857             TopoDS_Shape& anOppE = fourEdges[( found + 2 ) % 4 ];
1858
1859             // add anOppE to aChain if ...
1860             int prevChainSize = aChain.Extent();
1861             if ( aChain.Add(anOppE) > prevChainSize ) { // ... anOppE is not in aChain
1862               // Add found edge to the chain oriented so that to
1863               // have it co-directed with a forward MainEdge
1864               TopAbs_Orientation ori = anE.Orientation();
1865               if ( anOppE.Orientation() == fourEdges[found].Orientation() )
1866                 ori = TopAbs::Reverse( ori );
1867               anOppE.Orientation( ori );
1868               if ( anOppE.IsSame( anEdge ))
1869                 return make_pair( step, TopoDS::Edge( anOppE ));
1870               listCurEdges.Append(anOppE);
1871             }
1872           } // if (nb == 4 && found >= 0)
1873         } // if (aF.ShapeType() == TopAbs_WIRE)
1874       } // loop on ancestors of anE
1875     } // loop on listPrevEdges
1876
1877     listPrevEdges = listCurEdges;
1878   } // while (listPrevEdges.Extent() > 0)
1879
1880   return make_pair( INT_MAX, TopoDS_Edge());
1881 }
1882
1883 //================================================================================
1884 /*
1885  * Find corresponding nodes on two faces
1886  *  \param face1 - the first face
1887  *  \param mesh1 - mesh containing elements on the first face
1888  *  \param face2 - the second face
1889  *  \param mesh2 - mesh containing elements on the second face
1890  *  \param assocMap - map associating sub-shapes of the faces
1891  *  \param node1To2Map - map containing found matching nodes
1892  *  \retval bool - is a success
1893  */
1894 //================================================================================
1895
1896 bool StdMeshers_ProjectionUtils::
1897 FindMatchingNodesOnFaces( const TopoDS_Face&     face1,
1898                           SMESH_Mesh*            mesh1,
1899                           const TopoDS_Face&     face2,
1900                           SMESH_Mesh*            mesh2,
1901                           const TShapeShapeMap & assocMap,
1902                           TNodeNodeMap &         node1To2Map)
1903 {
1904   SMESHDS_Mesh* meshDS1 = mesh1->GetMeshDS();
1905   SMESHDS_Mesh* meshDS2 = mesh2->GetMeshDS();
1906
1907   SMESH_MesherHelper helper1( *mesh1 );
1908   SMESH_MesherHelper helper2( *mesh2 );
1909
1910   // Get corresponding submeshes and roughly check match of meshes
1911
1912   SMESHDS_SubMesh * SM2 = meshDS2->MeshElements( face2 );
1913   SMESHDS_SubMesh * SM1 = meshDS1->MeshElements( face1 );
1914   if ( !SM2 || !SM1 )
1915     RETURN_BAD_RESULT("Empty submeshes");
1916   if ( SM2->NbNodes()    != SM1->NbNodes() ||
1917        SM2->NbElements() != SM1->NbElements() )
1918     RETURN_BAD_RESULT("Different meshes on corresponding faces "
1919                       << meshDS1->ShapeToIndex( face1 ) << " and "
1920                       << meshDS2->ShapeToIndex( face2 ));
1921   if ( SM2->NbElements() == 0 )
1922     RETURN_BAD_RESULT("Empty submeshes");
1923
1924   helper1.SetSubShape( face1 );
1925   helper2.SetSubShape( face2 );
1926   if ( helper1.HasSeam() != helper2.HasSeam() )
1927     RETURN_BAD_RESULT("Different faces' geometry");
1928
1929   // Data to call SMESH_MeshEditor::FindMatchingNodes():
1930
1931   // 1. Nodes of corresponding links:
1932
1933   // get 2 matching edges, try to find not seam ones
1934   TopoDS_Edge edge1, edge2, seam1, seam2, anyEdge1, anyEdge2;
1935   TopExp_Explorer eE( OuterShape( face2, TopAbs_WIRE ), TopAbs_EDGE );
1936   do {
1937     // edge 2
1938     TopoDS_Edge e2 = TopoDS::Edge( eE.Current() );
1939     eE.Next();
1940     // edge 1
1941     if ( !assocMap.IsBound( e2, /*is2nd=*/true ))
1942       continue;
1943       //RETURN_BAD_RESULT("Association not found for edge " << meshDS2->ShapeToIndex( e2 ));
1944     TopoDS_Edge e1 = TopoDS::Edge( assocMap( e2, /*is2nd=*/true ));
1945     if ( !helper1.IsSubShape( e1, face1 ))
1946       RETURN_BAD_RESULT("Wrong association, edge " << meshDS1->ShapeToIndex( e1 ) <<
1947                         " isn't a sub-shape of face " << meshDS1->ShapeToIndex( face1 ));
1948     // check that there are nodes on edges
1949     SMESHDS_SubMesh * eSM1 = meshDS1->MeshElements( e1 );
1950     SMESHDS_SubMesh * eSM2 = meshDS2->MeshElements( e2 );
1951     bool nodesOnEdges = ( eSM1 && eSM2 && eSM1->NbNodes() && eSM2->NbNodes() );
1952     // check that the nodes on edges belong to faces
1953     // (as NETGEN ignores nodes on the degenerated geom edge)
1954     bool nodesOfFaces = false;
1955     if ( nodesOnEdges ) {
1956       const SMDS_MeshNode* n1 = eSM1->GetNodes()->next();
1957       const SMDS_MeshNode* n2 = eSM2->GetNodes()->next();
1958       nodesOfFaces = ( n1->GetInverseElementIterator(SMDSAbs_Face)->more() &&
1959                        n2->GetInverseElementIterator(SMDSAbs_Face)->more() );
1960     }
1961     if ( nodesOfFaces )
1962     {
1963       if ( helper2.IsRealSeam( e2 )) {
1964         seam1 = e1; seam2 = e2;
1965       }
1966       else {
1967         edge1 = e1; edge2 = e2;
1968       }
1969     }
1970     else {
1971       anyEdge1 = e1; anyEdge2 = e2;
1972     }
1973   } while ( edge2.IsNull() && eE.More() );
1974   //
1975   if ( edge2.IsNull() ) {
1976     edge1 = seam1; edge2 = seam2;
1977   }
1978   bool hasNodesOnEdge = (! edge2.IsNull() );
1979   if ( !hasNodesOnEdge ) {
1980     // 0020338 - nb segments == 1
1981     edge1 = anyEdge1; edge2 = anyEdge2;
1982   }
1983
1984   // get 2 matching vertices
1985   TopoDS_Vertex V2 = TopExp::FirstVertex( TopoDS::Edge( edge2 ));
1986   if ( !assocMap.IsBound( V2, /*is2nd=*/true ))
1987   {
1988     V2 = TopExp::LastVertex( TopoDS::Edge( edge2 ));
1989     if ( !assocMap.IsBound( V2, /*is2nd=*/true ))
1990       RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
1991   }
1992   TopoDS_Vertex V1 = TopoDS::Vertex( assocMap( V2, /*is2nd=*/true ));
1993
1994   // nodes on vertices
1995   const SMDS_MeshNode* vNode1 = SMESH_Algo::VertexNode( V1, meshDS1 );
1996   const SMDS_MeshNode* vNode2 = SMESH_Algo::VertexNode( V2, meshDS2 );
1997   if ( !vNode1 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS1->ShapeToIndex( V1 ));
1998   if ( !vNode2 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS2->ShapeToIndex( V2 ));
1999
2000   // nodes on edges linked with nodes on vertices
2001   const SMDS_MeshNode* nullNode = 0;
2002   vector< const SMDS_MeshNode*> eNode1( 2, nullNode );
2003   vector< const SMDS_MeshNode*> eNode2( 2, nullNode );
2004   if ( hasNodesOnEdge )
2005   {
2006     int nbNodeToGet = 1;
2007     if ( helper1.IsClosedEdge( edge1 ) || helper2.IsClosedEdge( edge2 ) )
2008       nbNodeToGet = 2;
2009     for ( int is2 = 0; is2 < 2; ++is2 )
2010     {
2011       TopoDS_Edge &     edge  = is2 ? edge2 : edge1;
2012       SMESHDS_Mesh *    smDS  = is2 ? meshDS2 : meshDS1;
2013       SMESHDS_SubMesh* edgeSM = smDS->MeshElements( edge );
2014       // nodes linked with ones on vertices
2015       const SMDS_MeshNode*           vNode = is2 ? vNode2 : vNode1;
2016       vector< const SMDS_MeshNode*>& eNode = is2 ? eNode2 : eNode1;
2017       int nbGotNode = 0;
2018       SMDS_ElemIteratorPtr vElem = vNode->GetInverseElementIterator(SMDSAbs_Edge);
2019       while ( vElem->more() && nbGotNode != nbNodeToGet ) {
2020         const SMDS_MeshElement* elem = vElem->next();
2021         if ( edgeSM->Contains( elem ))
2022           eNode[ nbGotNode++ ] = 
2023             ( elem->GetNode(0) == vNode ) ? elem->GetNode(1) : elem->GetNode(0);
2024       }
2025       if ( nbGotNode > 1 ) // sort found nodes by param on edge
2026       {
2027         SMESH_MesherHelper* helper = is2 ? &helper2 : &helper1;
2028         double u0 = helper->GetNodeU( edge, eNode[ 0 ]);
2029         double u1 = helper->GetNodeU( edge, eNode[ 1 ]);
2030         if ( u0 > u1 ) std::swap( eNode[ 0 ], eNode[ 1 ]);
2031       }
2032       if ( nbGotNode == 0 )
2033         RETURN_BAD_RESULT("Found no nodes on edge " << smDS->ShapeToIndex( edge ) <<
2034                           " linked to " << vNode );
2035     }
2036   }
2037   else // 0020338 - nb segments == 1
2038   {
2039     // get 2 other matching vertices
2040     V2 = TopExp::LastVertex( TopoDS::Edge( edge2 ));
2041     if ( !assocMap.IsBound( V2, /*is2nd=*/true ))
2042       RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
2043     V1 = TopoDS::Vertex( assocMap( V2, /*is2nd=*/true ));
2044
2045     // nodes on vertices
2046     eNode1[0] = SMESH_Algo::VertexNode( V1, meshDS1 );
2047     eNode2[0] = SMESH_Algo::VertexNode( V2, meshDS2 );
2048     if ( !eNode1[0] ) RETURN_BAD_RESULT("No node on vertex #" << meshDS1->ShapeToIndex( V1 ));
2049     if ( !eNode2[0] ) RETURN_BAD_RESULT("No node on vertex #" << meshDS2->ShapeToIndex( V2 ));
2050   }
2051
2052   // 2. face sets
2053
2054   int assocRes;
2055   for ( int iAttempt = 0; iAttempt < 2; ++iAttempt )
2056   {
2057     set<const SMDS_MeshElement*> Elems1, Elems2;
2058     for ( int is2 = 0; is2 < 2; ++is2 )
2059     {
2060       set<const SMDS_MeshElement*> & elems = is2 ? Elems2 : Elems1;
2061       SMESHDS_SubMesh*                  sm = is2 ? SM2 : SM1;
2062       SMESH_MesherHelper*           helper = is2 ? &helper2 : &helper1;
2063       const TopoDS_Face &             face = is2 ? face2 : face1;
2064       SMDS_ElemIteratorPtr eIt = sm->GetElements();
2065
2066       if ( !helper->IsRealSeam( is2 ? edge2 : edge1 ))
2067       {
2068         while ( eIt->more() ) elems.insert( elems.end(), eIt->next() );
2069       }
2070       else
2071       {
2072         // the only suitable edge is seam, i.e. it is a sphere.
2073         // FindMatchingNodes() will not know which way to go from any edge.
2074         // So we ignore all faces having nodes on edges or vertices except
2075         // one of faces sharing current start nodes
2076
2077         // find a face to keep
2078         const SMDS_MeshElement* faceToKeep = 0;
2079         const SMDS_MeshNode* vNode = is2 ? vNode2 : vNode1;
2080         const SMDS_MeshNode* eNode = is2 ? eNode2[0] : eNode1[0];
2081         TIDSortedElemSet inSet, notInSet;
2082
2083         const SMDS_MeshElement* f1 =
2084           SMESH_MeshAlgos::FindFaceInSet( vNode, eNode, inSet, notInSet );
2085         if ( !f1 ) RETURN_BAD_RESULT("The first face on seam not found");
2086         notInSet.insert( f1 );
2087
2088         const SMDS_MeshElement* f2 =
2089           SMESH_MeshAlgos::FindFaceInSet( vNode, eNode, inSet, notInSet );
2090         if ( !f2 ) RETURN_BAD_RESULT("The second face on seam not found");
2091
2092         // select a face with less UV of vNode
2093         const SMDS_MeshNode* notSeamNode[2] = {0, 0};
2094         for ( int iF = 0; iF < 2; ++iF ) {
2095           const SMDS_MeshElement* f = ( iF ? f2 : f1 );
2096           for ( int i = 0; !notSeamNode[ iF ] && i < f->NbNodes(); ++i ) {
2097             const SMDS_MeshNode* node = f->GetNode( i );
2098             if ( !helper->IsSeamShape( node->getshapeId() ))
2099               notSeamNode[ iF ] = node;
2100           }
2101         }
2102         gp_Pnt2d uv1 = helper->GetNodeUV( face, vNode, notSeamNode[0] );
2103         gp_Pnt2d uv2 = helper->GetNodeUV( face, vNode, notSeamNode[1] );
2104         if ( uv1.X() + uv1.Y() > uv2.X() + uv2.Y() )
2105           faceToKeep = f2;
2106         else
2107           faceToKeep = f1;
2108
2109         // fill elem set
2110         elems.insert( faceToKeep );
2111         while ( eIt->more() ) {
2112           const SMDS_MeshElement* f = eIt->next();
2113           int nbNodes = f->NbNodes();
2114           if ( f->IsQuadratic() )
2115             nbNodes /= 2;
2116           bool onBnd = false;
2117           for ( int i = 0; !onBnd && i < nbNodes; ++i ) {
2118             const SMDS_MeshNode* node = f->GetNode( i );
2119             onBnd = ( node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE);
2120           }
2121           if ( !onBnd )
2122             elems.insert( f );
2123         }
2124         // add also faces adjacent to faceToKeep
2125         int nbNodes = faceToKeep->NbNodes();
2126         if ( faceToKeep->IsQuadratic() ) nbNodes /= 2;
2127         notInSet.insert( f1 );
2128         notInSet.insert( f2 );
2129         for ( int i = 0; i < nbNodes; ++i ) {
2130           const SMDS_MeshNode* n1 = faceToKeep->GetNode( i );
2131           const SMDS_MeshNode* n2 = faceToKeep->GetNode(( i+1 ) % nbNodes );
2132           f1 = SMESH_MeshAlgos::FindFaceInSet( n1, n2, inSet, notInSet );
2133           if ( f1 )
2134             elems.insert( f1 );
2135         }
2136       } // case on a sphere
2137     } // loop on 2 faces
2138
2139     node1To2Map.clear();
2140     assocRes = SMESH_MeshEditor::FindMatchingNodes( Elems1, Elems2,
2141                                                     vNode1, vNode2,
2142                                                     eNode1[0], eNode2[0],
2143                                                     node1To2Map);
2144     if (( assocRes != SMESH_MeshEditor::SEW_OK ) &&
2145         ( eNode1[1] || eNode2[1] )) // there is another node to try (on a closed EDGE)
2146     {
2147       node1To2Map.clear();
2148       if ( eNode1[1] ) std::swap( eNode1[0], eNode1[1] );
2149       else             std::swap( eNode2[0], eNode2[1] );
2150       continue; // one more attempt
2151     }
2152
2153     break;
2154   }
2155   if ( assocRes != SMESH_MeshEditor::SEW_OK )
2156     RETURN_BAD_RESULT("FindMatchingNodes() result " << assocRes );
2157
2158   // On a sphere, add matching nodes on the edge
2159
2160   if ( helper1.IsRealSeam( edge1 ))
2161   {
2162     // sort nodes on edges by param on edge
2163     map< double, const SMDS_MeshNode* > u2nodesMaps[2];
2164     for ( int is2 = 0; is2 < 2; ++is2 )
2165     {
2166       TopoDS_Edge &     edge  = is2 ? edge2 : edge1;
2167       SMESHDS_Mesh *    smDS  = is2 ? meshDS2 : meshDS1;
2168       SMESHDS_SubMesh* edgeSM = smDS->MeshElements( edge );
2169       map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[ is2 ];
2170
2171       SMDS_NodeIteratorPtr nIt = edgeSM->GetNodes();
2172       while ( nIt->more() ) {
2173         const SMDS_MeshNode* node = nIt->next();
2174         const SMDS_EdgePosition* pos =
2175           static_cast<const SMDS_EdgePosition*>(node->GetPosition());
2176         pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
2177       }
2178       if ( pos2nodes.size() != edgeSM->NbNodes() )
2179         RETURN_BAD_RESULT("Equal params of nodes on edge "
2180                           << smDS->ShapeToIndex( edge ) << " of face " << is2 );
2181     }
2182     if ( u2nodesMaps[0].size() != u2nodesMaps[1].size() )
2183       RETURN_BAD_RESULT("Different nb of new nodes on edges or wrong params");
2184
2185     // compare edge orientation
2186     double u1 = helper1.GetNodeU( edge1, vNode1 );
2187     double u2 = helper2.GetNodeU( edge2, vNode2 );
2188     bool isFirst1 = ( u1 < u2nodesMaps[0].begin()->first );
2189     bool isFirst2 = ( u2 < u2nodesMaps[1].begin()->first );
2190     bool reverse ( isFirst1 != isFirst2 );
2191
2192     // associate matching nodes
2193     map< double, const SMDS_MeshNode* >::iterator u_Node1, u_Node2, end1;
2194     map< double, const SMDS_MeshNode* >::reverse_iterator uR_Node2;
2195     u_Node1 = u2nodesMaps[0].begin();
2196     u_Node2 = u2nodesMaps[1].begin();
2197     uR_Node2 = u2nodesMaps[1].rbegin();
2198     end1 = u2nodesMaps[0].end();
2199     for ( ; u_Node1 != end1; ++u_Node1 ) {
2200       const SMDS_MeshNode* n1 = u_Node1->second;
2201       const SMDS_MeshNode* n2 = ( reverse ? (uR_Node2++)->second : (u_Node2++)->second );
2202       node1To2Map.insert( make_pair( n1, n2 ));
2203     }
2204
2205     // associate matching nodes on the last vertices
2206     V2 = TopExp::LastVertex( TopoDS::Edge( edge2 ));
2207     if ( !assocMap.IsBound( V2, /*is2nd=*/true ))
2208       RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
2209     V1 = TopoDS::Vertex( assocMap( V2, /*is2nd=*/true ));
2210     vNode1 = SMESH_Algo::VertexNode( V1, meshDS1 );
2211     vNode2 = SMESH_Algo::VertexNode( V2, meshDS2 );
2212     if ( !vNode1 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS1->ShapeToIndex( V1 ));
2213     if ( !vNode2 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS2->ShapeToIndex( V2 ));
2214     node1To2Map.insert( make_pair( vNode1, vNode2 ));
2215   }
2216
2217   // don't know why this condition is usually true :(
2218   //   if ( node1To2Map.size() * quadFactor < SM1->NbNodes() )
2219   //     MESSAGE("FindMatchingNodes() found too few node pairs starting from nodes ("
2220   //             << vNode1->GetID() << " - " << eNode1[0]->GetID() << ") ("
2221   //             << vNode2->GetID() << " - " << eNode2[0]->GetID() << "):"
2222   //             << node1To2Map.size() * quadFactor << " < " << SM1->NbNodes());
2223
2224   return true;
2225 }
2226
2227 //================================================================================
2228 /*
2229  * Return any sub-shape of a face belonging to the outer wire
2230  *  \param face - the face
2231  *  \param type - type of sub-shape to return
2232  *  \retval TopoDS_Shape - the found sub-shape
2233  */
2234 //================================================================================
2235
2236 TopoDS_Shape StdMeshers_ProjectionUtils::OuterShape( const TopoDS_Face& face,
2237                                                      TopAbs_ShapeEnum   type)
2238 {
2239   TopExp_Explorer exp( BRepTools::OuterWire( face ), type );
2240   if ( exp.More() )
2241     return exp.Current();
2242   return TopoDS_Shape();
2243 }
2244
2245 //================================================================================
2246 /*
2247  * Check that sub-mesh is computed and try to compute it if is not
2248  *  \param sm - sub-mesh to compute
2249  *  \param iterationNb - int used to stop infinite recursive call
2250  *  \retval bool - true if computed
2251  */
2252 //================================================================================
2253
2254 bool StdMeshers_ProjectionUtils::MakeComputed(SMESH_subMesh * sm, const int iterationNb)
2255 {
2256   if ( iterationNb > 10 )
2257     RETURN_BAD_RESULT("Infinite recursive projection");
2258   if ( !sm )
2259     RETURN_BAD_RESULT("NULL submesh");
2260   if ( sm->IsMeshComputed() )
2261     return true;
2262
2263   SMESH_Mesh*   mesh = sm->GetFather();
2264   SMESH_Gen*     gen = mesh->GetGen();
2265   SMESH_Algo*   algo = sm->GetAlgo();
2266   TopoDS_Shape shape = sm->GetSubShape();
2267   if ( !algo )
2268   {
2269     if ( shape.ShapeType() != TopAbs_COMPOUND )
2270     {
2271       // No algo assigned to a non-compound sub-mesh.
2272       // Try to find an all-dimensional algo of an upper dimension
2273       int dim = gen->GetShapeDim( shape );
2274       for ( ++dim; ( dim <= 3 && !algo ); ++dim )
2275       {
2276         SMESH_HypoFilter hypoFilter( SMESH_HypoFilter::IsAlgo() );
2277         hypoFilter.And( SMESH_HypoFilter::HasDim( dim ));
2278         list <const SMESHDS_Hypothesis * > hyps;
2279         list< TopoDS_Shape >               assignedTo;
2280         int nbAlgos =
2281           mesh->GetHypotheses( shape, hypoFilter, hyps, true, &assignedTo );
2282         if ( nbAlgos > 1 ) // concurrent algos
2283         {
2284           vector<SMESH_subMesh*> smList; // where an algo is assigned
2285           list< TopoDS_Shape >::iterator shapeIt = assignedTo.begin();
2286           for ( ; shapeIt != assignedTo.end(); ++shapeIt )
2287             smList.push_back( mesh->GetSubMesh( *shapeIt ));
2288
2289           mesh->SortByMeshOrder( smList );
2290           algo  = smList.front()->GetAlgo();
2291           shape = smList.front()->GetSubShape();
2292         }
2293         else if ( nbAlgos == 1 )
2294         {
2295           algo = (SMESH_Algo*) hyps.front();
2296           shape = assignedTo.front();
2297         }
2298       }
2299       if ( !algo )
2300         return false;
2301     }
2302     else
2303     {
2304       // group
2305       bool computed = true;
2306       for ( TopoDS_Iterator grMember( shape ); grMember.More(); grMember.Next())
2307         if ( SMESH_subMesh* grSub = mesh->GetSubMesh( grMember.Value() ))
2308           if ( !MakeComputed( grSub, iterationNb + 1 ))
2309             computed = false;
2310       return computed;
2311     }
2312   }
2313
2314   string algoType = algo->GetName();
2315   if ( algoType.substr(0, 11) != "Projection_")
2316     return gen->Compute( *mesh, shape, /*shapeOnly=*/true );
2317
2318   // try to compute source mesh
2319
2320   const list <const SMESHDS_Hypothesis *> & hyps =
2321     algo->GetUsedHypothesis( *mesh, shape );
2322
2323   TopoDS_Shape srcShape;
2324   SMESH_Mesh* srcMesh = 0;
2325   list <const SMESHDS_Hypothesis*>::const_iterator hIt = hyps.begin();
2326   for ( ; srcShape.IsNull() && hIt != hyps.end(); ++hIt ) {
2327     string hypName = (*hIt)->GetName();
2328     if ( hypName == "ProjectionSource1D" ) {
2329       const StdMeshers_ProjectionSource1D * hyp =
2330         static_cast<const StdMeshers_ProjectionSource1D*>( *hIt );
2331       srcShape = hyp->GetSourceEdge();
2332       srcMesh = hyp->GetSourceMesh();
2333     }
2334     else if ( hypName == "ProjectionSource2D" ) {
2335       const StdMeshers_ProjectionSource2D * hyp =
2336         static_cast<const StdMeshers_ProjectionSource2D*>( *hIt );
2337       srcShape = hyp->GetSourceFace();
2338       srcMesh = hyp->GetSourceMesh();
2339     }
2340     else if ( hypName == "ProjectionSource3D" ) {
2341       const StdMeshers_ProjectionSource3D * hyp =
2342         static_cast<const StdMeshers_ProjectionSource3D*>( *hIt );
2343       srcShape = hyp->GetSource3DShape();
2344       srcMesh = hyp->GetSourceMesh();
2345     }
2346   }
2347   if ( srcShape.IsNull() ) // no projection source defined
2348     return gen->Compute( *mesh, shape, /*shapeOnly=*/true );
2349
2350   if ( srcShape.IsSame( shape ))
2351     RETURN_BAD_RESULT("Projection from self");
2352     
2353   if ( !srcMesh )
2354     srcMesh = mesh;
2355
2356   if ( MakeComputed( srcMesh->GetSubMesh( srcShape ), iterationNb + 1 ) &&
2357        gen->Compute( *mesh, shape, /*shapeOnly=*/true ))
2358     return sm->IsMeshComputed();
2359
2360   return false;
2361 }
2362
2363
2364 //================================================================================
2365 /*
2366  * Returns an error message to show in case if MakeComputed( sm ) fails.
2367  */
2368 //================================================================================
2369
2370 std::string StdMeshers_ProjectionUtils::SourceNotComputedError( SMESH_subMesh * sm,
2371                                                                 SMESH_Algo*     projAlgo )
2372 {
2373   const char usualMessage [] = "Source mesh not computed";
2374   if ( !projAlgo )
2375     return usualMessage;
2376   if ( !sm || sm->GetAlgoState() != SMESH_subMesh::NO_ALGO )
2377     return usualMessage; // algo is OK, anything else is KO.
2378
2379   // Try to find a type of all-dimentional algorithm that would compute the
2380   // given sub-mesh if it could be launched before projection
2381   const TopoDS_Shape shape = sm->GetSubShape();
2382   const int       shapeDim = SMESH_Gen::GetShapeDim( shape );
2383
2384   for ( int dimIncrement = 1; shapeDim + dimIncrement < 4; ++dimIncrement )
2385   {
2386     SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
2387     filter.And( filter.HasDim( shapeDim + dimIncrement ));
2388
2389     SMESH_Algo* algo = (SMESH_Algo*) sm->GetFather()->GetHypothesis( shape, filter, true );
2390     if ( algo && !algo->NeedDiscreteBoundary() )
2391       return SMESH_Comment("\"")
2392         << algo->GetFeatures()._label << "\""
2393         << " can't be used to compute the source mesh for \""
2394         << projAlgo->GetFeatures()._label << "\" in this case";
2395   }
2396   return usualMessage;
2397 }
2398
2399 //================================================================================
2400 /*
2401  * Return a boundary EDGE (or all boundary EDGEs) of edgeContainer
2402  */
2403 //================================================================================
2404
2405 TopoDS_Edge
2406 StdMeshers_ProjectionUtils::GetBoundaryEdge(const TopoDS_Shape&       edgeContainer,
2407                                             const SMESH_Mesh&         mesh,
2408                                             std::list< TopoDS_Edge >* allBndEdges)
2409 {
2410   TopTools_IndexedMapOfShape facesOfEdgeContainer, facesNearEdge;
2411   TopExp::MapShapes( edgeContainer, TopAbs_FACE, facesOfEdgeContainer );
2412
2413   if ( !facesOfEdgeContainer.IsEmpty() ) 
2414     for ( TopExp_Explorer exp(edgeContainer, TopAbs_EDGE); exp.More(); exp.Next() )
2415     {
2416       const TopoDS_Edge& edge = TopoDS::Edge( exp.Current() );
2417       facesNearEdge.Clear();
2418       PShapeIteratorPtr faceIt = SMESH_MesherHelper::GetAncestors( edge, mesh, TopAbs_FACE );
2419       while ( const TopoDS_Shape* face = faceIt->next() )
2420         if ( facesOfEdgeContainer.Contains( *face ))
2421           if ( facesNearEdge.Add( *face ) && facesNearEdge.Extent() > 1 )
2422             break;
2423       if ( facesNearEdge.Extent() == 1 ) {
2424         if ( allBndEdges )
2425           allBndEdges->push_back( edge );
2426         else
2427           return edge;
2428       }
2429     }
2430
2431   return TopoDS_Edge();
2432 }
2433
2434
2435 namespace { // Definition of event listeners
2436
2437   SMESH_subMeshEventListener* getSrcSubMeshListener();
2438
2439   //================================================================================
2440   /*!
2441    * \brief Listener that resets an event listener on source submesh when 
2442    * "ProjectionSource*D" hypothesis is modified
2443    */
2444   //================================================================================
2445
2446   struct HypModifWaiter: SMESH_subMeshEventListener
2447   {
2448     HypModifWaiter():SMESH_subMeshEventListener(false,// won't be deleted by submesh
2449                                                 "StdMeshers_ProjectionUtils::HypModifWaiter") {}
2450     void ProcessEvent(const int event, const int eventType, SMESH_subMesh* subMesh,
2451                       EventListenerData*, const SMESH_Hypothesis*)
2452     {
2453       if ( event     == SMESH_subMesh::MODIF_HYP &&
2454            eventType == SMESH_subMesh::ALGO_EVENT)
2455       {
2456         // delete current source listener
2457         subMesh->DeleteEventListener( getSrcSubMeshListener() );
2458         // let algo set a new one
2459         if ( SMESH_Algo* algo = subMesh->GetAlgo() )
2460           algo->SetEventListener( subMesh );
2461       }
2462     }
2463   };
2464   //================================================================================
2465   /*!
2466    * \brief return static HypModifWaiter
2467    */
2468   //================================================================================
2469
2470   SMESH_subMeshEventListener* getHypModifWaiter() {
2471     static HypModifWaiter aHypModifWaiter;
2472     return &aHypModifWaiter;
2473   }
2474   //================================================================================
2475   /*!
2476    * \brief return static listener for source shape submeshes
2477    */
2478   //================================================================================
2479
2480   SMESH_subMeshEventListener* getSrcSubMeshListener() {
2481     static SMESH_subMeshEventListener srcListener(false, // won't be deleted by submesh
2482                                                   "StdMeshers_ProjectionUtils::SrcSubMeshListener");
2483     return &srcListener;
2484   }
2485 }
2486
2487 //================================================================================
2488 /*
2489  * Set event listeners to submesh with projection algo
2490  *  \param subMesh - submesh with projection algo
2491  *  \param srcShape - source shape
2492  *  \param srcMesh - source mesh
2493  */
2494 //================================================================================
2495
2496 void StdMeshers_ProjectionUtils::SetEventListener(SMESH_subMesh* subMesh,
2497                                                   TopoDS_Shape   srcShape,
2498                                                   SMESH_Mesh*    srcMesh)
2499 {
2500   // Set the listener that resets an event listener on source submesh when
2501   // "ProjectionSource*D" hypothesis is modified since source shape can be changed
2502   subMesh->SetEventListener( getHypModifWaiter(),0,subMesh);
2503
2504   // Set an event listener to submesh of the source shape
2505   if ( !srcShape.IsNull() )
2506   {
2507     if ( !srcMesh )
2508       srcMesh = subMesh->GetFather();
2509
2510     SMESH_subMesh* srcShapeSM = srcMesh->GetSubMesh( srcShape );
2511
2512     if ( srcShapeSM != subMesh ) {
2513       if ( srcShapeSM->GetSubMeshDS() &&
2514            srcShapeSM->GetSubMeshDS()->IsComplexSubmesh() )
2515       {  // source shape is a group
2516         TopExp_Explorer it(srcShapeSM->GetSubShape(), // explore the group into sub-shapes...
2517                            subMesh->GetSubShape().ShapeType()); // ...of target shape type
2518         for (; it.More(); it.Next())
2519         {
2520           SMESH_subMesh* srcSM = srcMesh->GetSubMesh( it.Current() );
2521           if ( srcSM != subMesh )
2522           {
2523             SMESH_subMeshEventListenerData* data =
2524               srcSM->GetEventListenerData(getSrcSubMeshListener());
2525             if ( data )
2526               data->mySubMeshes.push_back( subMesh );
2527             else
2528               data = SMESH_subMeshEventListenerData::MakeData( subMesh );
2529             subMesh->SetEventListener ( getSrcSubMeshListener(), data, srcSM );
2530           }
2531         }
2532       }
2533       else
2534       {
2535         if ( SMESH_subMeshEventListenerData* data =
2536              srcShapeSM->GetEventListenerData( getSrcSubMeshListener() ))
2537         {
2538           bool alreadyIn =
2539             (std::find( data->mySubMeshes.begin(),
2540                         data->mySubMeshes.end(), subMesh ) != data->mySubMeshes.end() );
2541           if ( !alreadyIn )
2542             data->mySubMeshes.push_back( subMesh );
2543         }
2544         else
2545         {
2546           subMesh->SetEventListener( getSrcSubMeshListener(),
2547                                      SMESH_subMeshEventListenerData::MakeData( subMesh ),
2548                                      srcShapeSM );
2549         }
2550       }
2551     }
2552   }
2553 }
2554
2555 namespace StdMeshers_ProjectionUtils
2556 {
2557
2558   //================================================================================
2559   /*!
2560    * \brief Computes transformation beween two sets of 2D points using
2561    *        a least square approximation
2562    *
2563    * See "Surface Mesh Projection For Hexahedral Mesh Generation By Sweeping"
2564    * by X.Roca, J.Sarrate, A.Huerta. (2.2)
2565    */
2566   //================================================================================
2567
2568   bool TrsfFinder2D::Solve( const vector< gp_XY >& srcPnts,
2569                             const vector< gp_XY >& tgtPnts )
2570   {
2571     // find gravity centers
2572     gp_XY srcGC( 0,0 ), tgtGC( 0,0 );
2573     for ( size_t i = 0; i < srcPnts.size(); ++i )
2574     {
2575       srcGC += srcPnts[i];
2576       tgtGC += tgtPnts[i];
2577     }
2578     srcGC /= srcPnts.size();
2579     tgtGC /= tgtPnts.size();
2580
2581     // find trsf
2582
2583     math_Matrix mat (1,4,1,4, 0.);
2584     math_Vector vec (1,4, 0.);
2585
2586     // cout << "m1 = smesh.Mesh('src')" << endl
2587     //      << "m2 = smesh.Mesh('tgt')" << endl;
2588     double xx = 0, xy = 0, yy = 0;
2589     for ( size_t i = 0; i < srcPnts.size(); ++i )
2590     {
2591       gp_XY srcUV = srcPnts[i] - srcGC;
2592       gp_XY tgtUV = tgtPnts[i] - tgtGC;
2593       xx += srcUV.X() * srcUV.X();
2594       yy += srcUV.Y() * srcUV.Y();
2595       xy += srcUV.X() * srcUV.Y();
2596       vec( 1 ) += srcUV.X() * tgtUV.X();
2597       vec( 2 ) += srcUV.Y() * tgtUV.X();
2598       vec( 3 ) += srcUV.X() * tgtUV.Y();
2599       vec( 4 ) += srcUV.Y() * tgtUV.Y();
2600       // cout << "m1.AddNode( " << srcUV.X() << ", " << srcUV.Y() << ", 0 )" << endl
2601       //      << "m2.AddNode( " << tgtUV.X() << ", " << tgtUV.Y() << ", 0 )" << endl;
2602     }
2603     mat( 1,1 ) = mat( 3,3 ) = xx;
2604     mat( 2,2 ) = mat( 4,4 ) = yy;
2605     mat( 1,2 ) = mat( 2,1 ) = mat( 3,4 ) = mat( 4,3 ) = xy;
2606
2607     math_Gauss solver( mat );
2608     if ( !solver.IsDone() )
2609       return false;
2610     solver.Solve( vec );
2611     if ( vec.Norm2() < gp::Resolution() )
2612       return false;
2613     // cout << vec( 1 ) << "\t " << vec( 2 ) << endl
2614     //      << vec( 3 ) << "\t " << vec( 4 ) << endl;
2615
2616     _trsf.SetTranslation( tgtGC );
2617     _srcOrig = srcGC;
2618
2619     gp_Mat2d& M = const_cast< gp_Mat2d& >( _trsf.HVectorialPart());
2620     M( 1,1 ) = vec( 1 );
2621     M( 2,1 ) = vec( 2 );
2622     M( 1,2 ) = vec( 3 );
2623     M( 2,2 ) = vec( 4 );
2624
2625     return true;
2626   }
2627
2628   //================================================================================
2629   /*!
2630    * \brief Transforms a 2D points using a found transformation
2631    */
2632   //================================================================================
2633
2634   gp_XY TrsfFinder2D::Transform( const gp_Pnt2d& srcUV ) const
2635   {
2636     gp_XY uv = srcUV.XY() - _srcOrig ;
2637     _trsf.Transforms( uv );
2638     return uv;
2639   }
2640
2641   //================================================================================
2642   /*!
2643    * \brief Computes transformation beween two sets of 3D points using
2644    *        a least square approximation
2645    *
2646    * See "Surface Mesh Projection For Hexahedral Mesh Generation By Sweeping"
2647    * by X.Roca, J.Sarrate, A.Huerta. (2.4)
2648    */
2649   //================================================================================
2650
2651   bool TrsfFinder3D::Solve( const vector< gp_XYZ > & srcPnts,
2652                             const vector< gp_XYZ > & tgtPnts )
2653   {
2654     // find gravity center
2655     gp_XYZ srcGC( 0,0,0 ), tgtGC( 0,0,0 );
2656     for ( size_t i = 0; i < srcPnts.size(); ++i )
2657     {
2658       srcGC += srcPnts[i];
2659       tgtGC += tgtPnts[i];
2660     }
2661     srcGC /= srcPnts.size();
2662     tgtGC /= tgtPnts.size();
2663
2664     gp_XYZ srcOrig = 2 * srcGC - tgtGC;
2665     gp_XYZ tgtOrig = srcGC;
2666
2667     // find trsf
2668
2669     math_Matrix mat (1,9,1,9, 0.);
2670     math_Vector vec (1,9, 0.);
2671
2672     double xx = 0, yy = 0, zz = 0;
2673     double xy = 0, xz = 0, yz = 0;
2674     for ( size_t i = 0; i < srcPnts.size(); ++i )
2675     {
2676       gp_XYZ src = srcPnts[i] - srcOrig;
2677       gp_XYZ tgt = tgtPnts[i] - tgtOrig;
2678       xx += src.X() * src.X();
2679       yy += src.Y() * src.Y();
2680       zz += src.Z() * src.Z();
2681       xy += src.X() * src.Y();
2682       xz += src.X() * src.Z();
2683       yz += src.Y() * src.Z();
2684       vec( 1 ) += src.X() * tgt.X();
2685       vec( 2 ) += src.Y() * tgt.X();
2686       vec( 3 ) += src.Z() * tgt.X();
2687       vec( 4 ) += src.X() * tgt.Y();
2688       vec( 5 ) += src.Y() * tgt.Y();
2689       vec( 6 ) += src.Z() * tgt.Y();
2690       vec( 7 ) += src.X() * tgt.Z();
2691       vec( 8 ) += src.Y() * tgt.Z();
2692       vec( 9 ) += src.Z() * tgt.Z();
2693     }
2694     mat( 1,1 ) = mat( 4,4 ) = mat( 7,7 ) = xx;
2695     mat( 2,2 ) = mat( 5,5 ) = mat( 8,8 ) = yy;
2696     mat( 3,3 ) = mat( 6,6 ) = mat( 9,9 ) = zz;
2697     mat( 1,2 ) = mat( 2,1 ) = mat( 4,5 ) = mat( 5,4 ) = mat( 7,8 ) = mat( 8,7 ) = xy;
2698     mat( 1,3 ) = mat( 3,1 ) = mat( 4,6 ) = mat( 6,4 ) = mat( 7,9 ) = mat( 9,7 ) = xz;
2699     mat( 2,3 ) = mat( 3,2 ) = mat( 5,6 ) = mat( 6,5 ) = mat( 8,9 ) = mat( 9,8 ) = yz;
2700
2701     math_Gauss solver( mat );
2702     if ( !solver.IsDone() )
2703       return false;
2704     solver.Solve( vec );
2705     if ( vec.Norm2() < gp::Resolution() )
2706       return false;
2707     // cout << endl
2708     //      << vec( 1 ) << "\t " << vec( 2 ) << "\t " << vec( 3 ) << endl
2709     //      << vec( 4 ) << "\t " << vec( 5 ) << "\t " << vec( 6 ) << endl
2710     //      << vec( 7 ) << "\t " << vec( 8 ) << "\t " << vec( 9 ) << endl;
2711
2712     _srcOrig = srcOrig;
2713     _trsf.SetTranslation( tgtOrig );
2714
2715     gp_Mat& M = const_cast< gp_Mat& >( _trsf.HVectorialPart() );
2716     M.SetRows( gp_XYZ( vec( 1 ), vec( 2 ), vec( 3 )),
2717                gp_XYZ( vec( 4 ), vec( 5 ), vec( 6 )),
2718                gp_XYZ( vec( 7 ), vec( 8 ), vec( 9 )));
2719     return true;
2720   }
2721
2722   //================================================================================
2723   /*!
2724    * \brief Transforms a 3D point using a found transformation
2725    */
2726   //================================================================================
2727
2728   gp_XYZ TrsfFinder3D::Transform( const gp_Pnt& srcP ) const
2729   {
2730     gp_XYZ p = srcP.XYZ() - _srcOrig;
2731     _trsf.Transforms( p );
2732     return p;
2733   }
2734
2735   //================================================================================
2736   /*!
2737    * \brief Transforms a 3D vector using a found transformation
2738    */
2739   //================================================================================
2740
2741   gp_XYZ TrsfFinder3D::TransformVec( const gp_Vec& v ) const
2742   {
2743     return v.XYZ().Multiplied( _trsf.HVectorialPart() );
2744   }
2745   //================================================================================
2746   /*!
2747    * \brief Inversion
2748    */
2749   //================================================================================
2750
2751   bool TrsfFinder3D::Invert()
2752   {
2753     if (( _trsf.Form() == gp_Translation ) &&
2754         ( _srcOrig.X() != 0 || _srcOrig.Y() != 0 || _srcOrig.Z() != 0 ))
2755     {
2756       // seems to be defined via Solve()
2757       gp_XYZ newSrcOrig = _trsf.TranslationPart();
2758       gp_Mat& M = const_cast< gp_Mat& >( _trsf.HVectorialPart() );
2759       const double D = M.Determinant();
2760       if ( D < 1e-3 * ( newSrcOrig - _srcOrig ).Modulus() )
2761       {
2762 #ifdef _DEBUG_
2763         cerr << "TrsfFinder3D::Invert()"
2764              << "D " << M.Determinant() << " IsSingular " << M.IsSingular() << endl;
2765 #endif
2766         return false;
2767       }
2768       gp_Mat Minv = M.Inverted();
2769       _trsf.SetTranslation( _srcOrig );
2770       _srcOrig = newSrcOrig;
2771       M = Minv;
2772     }
2773     else
2774     {
2775       _trsf.Invert();
2776     }
2777     return true;
2778   }
2779 }