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