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