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