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