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