Salome HOME
23422: EDF 14312 - Strange behavior of Viscous Layer Surface offset + smooth
[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           reverseEdges(edges2, nbE);
1106           if ( nbE != 2 ) // 2 degen edges of 4 (issue 0021144)
1107             edges2.splice( edges2.end(), edges2, edges2.begin());
1108         }
1109         // store association
1110         list< TopoDS_Edge >::iterator eIt1 = edges1.begin();
1111         list< TopoDS_Edge >::iterator eIt2 = edges2.begin();
1112         for ( ; eIt1 != edges1.end(); ++eIt1, ++eIt2 )
1113         {
1114           InsertAssociation( *eIt1, *eIt2, theMap );
1115           VV1[0] = SMESH_MesherHelper::IthVertex( 0, *eIt1, true );
1116           VV2[0] = SMESH_MesherHelper::IthVertex( 0, *eIt2, true );
1117           InsertAssociation( VV1[0], VV2[0], theMap );
1118         }
1119         InsertAssociation( theShape1, theShape2, theMap );
1120         theMap.SetAssocType( TShapeShapeMap::PROPAGATION );
1121         return true;
1122       }
1123     }
1124     break; // try by vertex closeness
1125   }
1126   case TopAbs_COMPOUND: {
1127     // ----------------------------------------------------------------------
1128     if ( isPropagationPossible( theMesh1, theMesh2 )) {
1129
1130       // try to accosiate all using propagation
1131       if ( assocGroupsByPropagation( theShape1, theShape2, *theMesh1, theMap ))
1132         return true;
1133
1134       // find a boundary edge of theShape1
1135       TopoDS_Edge E = GetBoundaryEdge( theShape1, *theMesh1 );
1136       if ( E.IsNull() )
1137         break; // try by vertex closeness
1138
1139       // find association for vertices of edge E
1140       TopoDS_Vertex VV1[2], VV2[2];
1141       for(TopExp_Explorer eexp(E, TopAbs_VERTEX); eexp.More(); eexp.Next()) {
1142         TopoDS_Vertex V1 = TopoDS::Vertex( eexp.Current() );
1143         // look for an edge ending in E whose one vertex is in theShape1
1144         // and the other, in theShape2
1145         const TopTools_ListOfShape& Ancestors = theMesh1->GetAncestors(V1);
1146         TopTools_ListIteratorOfListOfShape ita(Ancestors);
1147         for(; ita.More(); ita.Next()) {
1148           if( ita.Value().ShapeType() != TopAbs_EDGE ) continue;
1149           TopoDS_Edge edge = TopoDS::Edge(ita.Value());
1150           bool FromShape1 = false;
1151           for(TopExp_Explorer expe(theShape1, TopAbs_EDGE); expe.More(); expe.Next() ) {
1152             if(edge.IsSame(expe.Current())) {
1153               FromShape1 = true;
1154               break;
1155             }
1156           }
1157           if(!FromShape1) {
1158             // is it an edge between theShape1 and theShape2?
1159             TopExp_Explorer expv(edge, TopAbs_VERTEX);
1160             TopoDS_Vertex V2 = TopoDS::Vertex( expv.Current() );
1161             if(V2.IsSame(V1)) {
1162               expv.Next();
1163               V2 = TopoDS::Vertex( expv.Current() );
1164             }
1165             bool FromShape2 = false;
1166             for ( expv.Init( theShape2, TopAbs_VERTEX ); expv.More(); expv.Next()) {
1167               if ( V2.IsSame( expv.Current() )) {
1168                 FromShape2 = true;
1169                 break;
1170               }
1171             }
1172             if ( FromShape2 ) {
1173               if ( VV1[0].IsNull() )
1174                 VV1[0] = V1, VV2[0] = V2;
1175               else
1176                 VV1[1] = V1, VV2[1] = V2;
1177               break; // from loop on ancestors of V1
1178             }
1179           }
1180         }
1181       }
1182       if ( !VV1[1].IsNull() ) {
1183         InsertAssociation( VV1[0], VV2[0], theMap );
1184         InsertAssociation( VV1[1], VV2[1], theMap );
1185         TShapeShapeMap::EAssocType asType = theMap._assocType;
1186         theMap.SetAssocType( TShapeShapeMap::PROPAGATION );
1187         if ( FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap ))
1188           return true;
1189         theMap._assocType = asType;
1190       }
1191     }
1192     break; // try by vertex closeness
1193   }
1194   default:;
1195   }
1196
1197   // 4.b) Find association by closeness of vertices
1198   // ----------------------------------------------
1199
1200   TopTools_IndexedMapOfShape vMap1, vMap2;
1201   TopExp::MapShapes( theShape1, TopAbs_VERTEX, vMap1 );
1202   TopExp::MapShapes( theShape2, TopAbs_VERTEX, vMap2 );
1203   TopoDS_Vertex VV1[2], VV2[2];
1204
1205   if ( vMap1.Extent() != vMap2.Extent() )
1206   {
1207     if ( SMESH_MesherHelper:: Count( theShape1, TopAbs_EDGE, /*ignoreSame=*/false ) !=
1208          SMESH_MesherHelper:: Count( theShape2, TopAbs_EDGE, /*ignoreSame=*/false ))
1209       RETURN_BAD_RESULT("Different nb of vertices");
1210   }
1211
1212   if ( vMap1.Extent() == 1 || vMap2.Extent() == 1 ) {
1213     InsertAssociation( vMap1(1), vMap2(1), theMap );
1214     if ( theShape1.ShapeType() == TopAbs_EDGE ) {
1215       if ( vMap1.Extent() == 2 )
1216         InsertAssociation( vMap1(2), vMap2(1), theMap );
1217       else if ( vMap2.Extent() == 2 )
1218         InsertAssociation( vMap2(2), vMap1(1), theMap );
1219       InsertAssociation( theShape1, theShape2, theMap );
1220       return true;
1221     }
1222     return FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap);
1223   }
1224
1225   // Try to associate by common vertices of an edge
1226   for ( int i = 1; i <= vMap1.Extent(); ++i )
1227   {
1228     const TopoDS_Shape& v1 = vMap1(i);
1229     if ( vMap2.Contains( v1 ))
1230     {
1231       // find an egde sharing v1 and sharing at the same time another common vertex
1232       PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( v1, *theMesh1, TopAbs_EDGE);
1233       bool edgeFound = false;
1234       while ( edgeIt->more() && !edgeFound )
1235       {
1236         TopoDS_Edge edge = TopoDS::Edge( edgeIt->next()->Oriented(TopAbs_FORWARD));
1237         TopExp::Vertices(edge, VV1[0], VV1[1]);
1238         if ( !VV1[0].IsSame( VV1[1] ))
1239           edgeFound = ( vMap2.Contains( VV1[ v1.IsSame(VV1[0]) ? 1:0]));
1240       }
1241       if ( edgeFound )
1242       {
1243         InsertAssociation( VV1[0], VV1[0], theMap );
1244         InsertAssociation( VV1[1], VV1[1], theMap );
1245         TShapeShapeMap::EAssocType asType = theMap._assocType;
1246         theMap.SetAssocType( TShapeShapeMap::COMMON_VERTEX );
1247         if ( FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap ))
1248           return true;
1249         theMap._assocType = asType;
1250       }
1251     }
1252   }
1253
1254   // Find transformation to make the shapes be of similar size at same location
1255
1256   Bnd_Box box[2];
1257   for ( int i = 1; i <= vMap1.Extent(); ++i )
1258     box[ 0 ].Add( BRep_Tool::Pnt ( TopoDS::Vertex( vMap1( i ))));
1259   for ( int i = 1; i <= vMap2.Extent(); ++i )
1260     box[ 1 ].Add( BRep_Tool::Pnt ( TopoDS::Vertex( vMap2( i ))));
1261
1262   gp_Pnt gc[2]; // box center
1263   double x0,y0,z0, x1,y1,z1;
1264   box[0].Get( x0,y0,z0, x1,y1,z1 );
1265   gc[0] = 0.5 * ( gp_XYZ( x0,y0,z0 ) + gp_XYZ( x1,y1,z1 ));
1266   box[1].Get( x0,y0,z0, x1,y1,z1 );
1267   gc[1] = 0.5 * ( gp_XYZ( x0,y0,z0 ) + gp_XYZ( x1,y1,z1 ));
1268
1269   // 1 -> 2
1270   gp_Vec vec01( gc[0], gc[1] );
1271   double scale = sqrt( box[1].SquareExtent() / box[0].SquareExtent() );
1272
1273   // Find 2 closest vertices
1274
1275   // get 2 linked vertices of shape 1 not belonging to an inner wire of a face
1276   std::list< TopoDS_Edge > allBndEdges1;
1277   if ( !getOuterEdges( theShape1, *theMesh1, allBndEdges1 ))
1278   {
1279     if ( theShape1.ShapeType() != TopAbs_FACE )
1280       RETURN_BAD_RESULT("Edge not found");
1281     return assocFewEdgesFaces( TopoDS::Face( theShape1 ), theMesh1, 
1282                                TopoDS::Face( theShape2 ), theMesh2, theMap );
1283   }
1284   std::list< TopoDS_Edge >::iterator edge1 = allBndEdges1.begin();
1285   double minDist = std::numeric_limits<double>::max();
1286   for ( int nbChecked=0; edge1 != allBndEdges1.end() && nbChecked++ < 10; ++edge1 )
1287   {
1288     TopoDS_Vertex edge1VV[2];
1289     TopExp::Vertices( TopoDS::Edge( edge1->Oriented(TopAbs_FORWARD)), edge1VV[0], edge1VV[1]);
1290     if ( edge1VV[0].IsSame( edge1VV[1] ))
1291       continue;//RETURN_BAD_RESULT("Only closed edges");
1292
1293     // find vertices closest to 2 linked vertices of shape 1
1294     double dist2[2] = { 1e+100, 1e+100 };
1295     TopoDS_Vertex edge2VV[2];
1296     for ( int i1 = 0; i1 < 2; ++i1 )
1297     {
1298       gp_Pnt p1 = BRep_Tool::Pnt( edge1VV[ i1 ]);
1299       p1.Scale( gc[0], scale );
1300       p1.Translate( vec01 );
1301       if ( !i1 ) {
1302         // select a closest vertex among all ones in vMap2
1303         for ( int i2 = 1; i2 <= vMap2.Extent(); ++i2 )
1304         {
1305           TopoDS_Vertex V2 = TopoDS::Vertex( vMap2( i2 ));
1306           gp_Pnt        p2 = BRep_Tool::Pnt ( V2 );
1307           double        d2 = p1.SquareDistance( p2 );
1308           if ( d2 < dist2[ 0 ] && d2 < minDist ) {
1309             edge2VV[ 0 ] = V2;
1310             dist2  [ 0 ] = d2;
1311           }
1312         }
1313       }
1314       else if ( !edge2VV[0].IsNull() ) {
1315         // select a closest vertex among ends of edges meeting at edge2VV[0]
1316         PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( edge2VV[0],
1317                                                                      *theMesh2, TopAbs_EDGE);
1318         while ( const TopoDS_Shape* edge2 = edgeIt->next() )
1319           for ( TopoDS_Iterator itV2( *edge2 ); itV2.More(); itV2.Next() )
1320           {
1321             if ( itV2.Value().IsSame( edge2VV[ 0 ])) continue;
1322             if ( !vMap2.Contains( itV2.Value()    )) continue;
1323             TopoDS_Vertex V2 = TopoDS::Vertex( itV2.Value() );
1324             gp_Pnt        p2 = BRep_Tool::Pnt ( V2 );
1325             double        d2 = p1.SquareDistance( p2 );
1326             if ( d2 < dist2[1] && d2 < minDist ) {
1327               edge2VV[ 1 ] = V2;
1328               dist2  [ 1 ] = d2;
1329             }
1330           }
1331       }
1332     }
1333     if ( dist2[0] + dist2[1] < minDist ) {
1334       VV1[0] = edge1VV[0];
1335       VV1[1] = edge1VV[1];
1336       VV2[0] = edge2VV[0];
1337       VV2[1] = edge2VV[1];
1338       minDist = dist2[0] + dist2[1];
1339       if ( minDist < 1e-10 )
1340         break;
1341     }
1342   }
1343   theMap.SetAssocType( TShapeShapeMap::CLOSE_VERTEX );
1344
1345   InsertAssociation( VV1[ 0 ], VV2[ 0 ], theMap );
1346   InsertAssociation( VV1[ 1 ], VV2[ 1 ], theMap );
1347   // MESSAGE("Initial assoc VERT " << theMesh1->GetMeshDS()->ShapeToIndex( VV1[ 0 ] )<<
1348   //         " to "                << theMesh2->GetMeshDS()->ShapeToIndex( VV2[ 0 ] )<<
1349   //         "\nand         VERT " << theMesh1->GetMeshDS()->ShapeToIndex( VV1[ 1 ] )<<
1350   //         " to "                << theMesh2->GetMeshDS()->ShapeToIndex( VV2[ 1 ] ));
1351   if ( theShape1.ShapeType() == TopAbs_EDGE ) {
1352     InsertAssociation( theShape1, theShape2, theMap );
1353     return true;
1354   }
1355
1356   return FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap );
1357 }
1358
1359 //================================================================================
1360 /*
1361  * Find association of edges of faces
1362  *  \param face1 - face 1
1363  *  \param VV1 - vertices of face 1
1364  *  \param face2 - face 2
1365  *  \param VV2 - vertices of face 2 associated with ones of face 1
1366  *  \param edges1 - out list of edges of face 1
1367  *  \param edges2 - out list of edges of face 2
1368  *  \param isClosenessAssoc - is association starting by VERTEX closeness
1369  *  \retval int - nb of edges in an outer wire in a success case, else zero
1370  */
1371 //================================================================================
1372
1373 int StdMeshers_ProjectionUtils::FindFaceAssociation(const TopoDS_Face&    face1,
1374                                                     TopoDS_Vertex         VV1[2],
1375                                                     const TopoDS_Face&    face2,
1376                                                     TopoDS_Vertex         VV2[2],
1377                                                     list< TopoDS_Edge > & edges1,
1378                                                     list< TopoDS_Edge > & edges2,
1379                                                     const bool            isClosenessAssoc)
1380 {
1381   bool OK = false;
1382   list< int > nbEInW1, nbEInW2;
1383   list< TopoDS_Edge >::iterator edgeIt;
1384   int i_ok_wire_algo = -1;
1385   for ( int outer_wire_algo = 0; outer_wire_algo < 2 && !OK; ++outer_wire_algo )
1386   {
1387     edges1.clear();
1388     edges2.clear();
1389
1390     if ( SMESH_Block::GetOrderedEdges( face1, edges1, nbEInW1, VV1[0], outer_wire_algo) !=
1391          SMESH_Block::GetOrderedEdges( face2, edges2, nbEInW2, VV2[0], outer_wire_algo) )
1392       CONT_BAD_RESULT("Different number of wires in faces ");
1393
1394     if ( nbEInW1 != nbEInW2 && outer_wire_algo == 0 &&
1395          ( std::accumulate( nbEInW1.begin(), nbEInW1.end(), 0) !=
1396            std::accumulate( nbEInW2.begin(), nbEInW2.end(), 0)))
1397       RETURN_BAD_RESULT("Different number of edges in faces");
1398
1399     if ( nbEInW1.front() != nbEInW2.front() )
1400       CONT_BAD_RESULT("Different number of edges in the outer wire: " <<
1401                       nbEInW1.front() << " != " << nbEInW2.front());
1402
1403     i_ok_wire_algo = outer_wire_algo;
1404
1405     // Define if we need to reverse one of wires to make edges in lists match each other
1406
1407     bool reverse = false;
1408     const bool severalWires = ( nbEInW1.size() > 1 );
1409
1410     if ( !VV1[1].IsSame( TopExp::LastVertex( edges1.front(), true )))
1411     {
1412       reverse = true;
1413       // check if the second vertex belongs to the first or last edge in the wire
1414       edgeIt = --edges1.end(); // pointer to the last edge in the outer wire
1415       if ( severalWires ) {
1416         edgeIt = edges1.begin();
1417         std::advance( edgeIt, nbEInW1.front()-1 );
1418       }
1419       if ( TopExp::FirstVertex( *edgeIt ).IsSame( TopExp::LastVertex( *edgeIt )) &&
1420            SMESH_Algo::isDegenerated( *edgeIt )) {
1421         --edgeIt; // skip a degenerated edge (test 3D_mesh_Projection_00/A3)
1422       }
1423       if ( !VV1[1].IsSame( TopExp::FirstVertex( *edgeIt, true ))) {
1424         CONT_BAD_RESULT("GetOrderedEdges() failed");
1425       }
1426     }
1427     if ( !VV2[1].IsSame( TopExp::LastVertex( edges2.front(), true )))
1428     {
1429       reverse = !reverse;
1430       // check if the second vertex belongs to the first or last edge in the wire
1431       edgeIt = --edges2.end(); // pointer to the last edge in the outer wire
1432       if ( severalWires ) {
1433         edgeIt = edges2.begin();
1434         std::advance( edgeIt, nbEInW2.front()-1 );
1435       }
1436       if ( TopExp::FirstVertex( *edgeIt ).IsSame( TopExp::LastVertex( *edgeIt )) &&
1437            SMESH_Algo::isDegenerated( *edgeIt )) {
1438         --edgeIt;  // skip a degenerated edge
1439       }
1440       if ( !VV2[1].IsSame( TopExp::FirstVertex( *edgeIt, true ))) {
1441         CONT_BAD_RESULT("GetOrderedEdges() failed");
1442       }
1443     }
1444     if ( reverse )
1445     {
1446       reverseEdges( edges2 , nbEInW2.front());
1447
1448       if ( SMESH_Algo::isDegenerated( edges2.front() ))
1449       {
1450         // move a degenerated edge to the back of the outer wire
1451         edgeIt = edges2.end();
1452         if ( severalWires ) {
1453           edgeIt = edges2.begin();
1454           std::advance( edgeIt, nbEInW2.front() );
1455         }
1456         edges2.splice( edgeIt, edges2, edges2.begin() );
1457       }
1458       if (( VV1[1].IsSame( TopExp::LastVertex( edges1.front(), true ))) !=
1459           ( VV2[1].IsSame( TopExp::LastVertex( edges2.front(), true ))))
1460         CONT_BAD_RESULT("GetOrderedEdges() failed");
1461     }
1462     OK = true;
1463
1464   } // loop algos getting an outer wire
1465
1466   if ( OK && nbEInW1.front() > 4 ) // care of a case where faces are closed (23032)
1467   {
1468     // check if the first edges are seam ones
1469     list< TopoDS_Edge >::iterator revSeam1, revSeam2;
1470     revSeam1 = std::find( ++edges1.begin(), edges1.end(), edges1.front().Reversed());
1471     revSeam2 = edges2.end();
1472     if ( revSeam1 != edges1.end() )
1473       revSeam2 = std::find( ++edges2.begin(), edges2.end(), edges2.front().Reversed());
1474     if ( revSeam2 != edges2.end() ) // two seams detected
1475     {
1476       bool reverse =
1477         std::distance( edges1.begin(), revSeam1 ) != std::distance( edges2.begin(), revSeam2 );
1478       if ( !reverse && isClosenessAssoc )
1479       {
1480         // compare orientations of a non-seam edges using 3D closeness;
1481         // look for a non-seam edges
1482         list< TopoDS_Edge >::iterator edge1 = ++edges1.begin();
1483         list< TopoDS_Edge >::iterator edge2 = ++edges2.begin();
1484         for ( ; edge1 != edges1.end(); ++edge1, ++edge2 )
1485         {
1486           if (( edge1 == revSeam1 ) ||
1487               ( SMESH_Algo::isDegenerated( *edge1 )) ||
1488               ( std::find( ++edges1.begin(), edges1.end(), edge1->Reversed()) != edges1.end() ))
1489             continue;
1490           gp_Pnt p1 = BRep_Tool::Pnt( VV1[0] );
1491           gp_Pnt p2 = BRep_Tool::Pnt( VV2[0] );
1492           gp_Vec vec2to1( p2, p1 );
1493
1494           gp_Pnt pp1[2], pp2[2];
1495           const double r = 0.2345;
1496           double f,l;
1497           Handle(Geom_Curve) C = BRep_Tool::Curve( *edge1, f,l );
1498           pp1[0] = C->Value( f * r + l * ( 1. - r ));
1499           pp1[1] = C->Value( l * r + f * ( 1. - r ));
1500           if ( edge1->Orientation() == TopAbs_REVERSED )
1501             std::swap( pp1[0], pp1[1] );
1502           C = BRep_Tool::Curve( *edge2, f,l );
1503           if ( C.IsNull() ) return 0;
1504           pp2[0] = C->Value( f * r + l * ( 1. - r )).Translated( vec2to1 );
1505           pp2[1] = C->Value( l * r + f * ( 1. - r )).Translated( vec2to1 );
1506           if ( edge2->Orientation() == TopAbs_REVERSED )
1507             std::swap( pp2[0], pp2[1] );
1508
1509           double dist00 = pp1[0].SquareDistance( pp2[0] );
1510           double dist01 = pp1[0].SquareDistance( pp2[1] );
1511           reverse = ( dist00 > dist01 );
1512           break;
1513         }
1514       }
1515       if ( reverse ) // make a seam counterpart be the first
1516       {
1517         list< TopoDS_Edge >::iterator outWireEnd = edges2.begin();
1518         std::advance( outWireEnd, nbEInW2.front() );
1519         edges2.splice( outWireEnd, edges2, edges2.begin(), ++revSeam2 );
1520         reverseEdges( edges2 , nbEInW2.front());
1521       }
1522     }
1523   }
1524   
1525   // Try to orient all (if !OK) or only internal wires (issue 0020996) by UV similarity
1526
1527   if (( !OK || nbEInW1.size() > 1 ) && i_ok_wire_algo > -1 )
1528   {
1529     // Check that Vec(VV1[0],VV1[1]) in 2D on face1 is the same
1530     // as Vec(VV2[0],VV2[1]) on face2
1531     double vTol = BRep_Tool::Tolerance( VV1[0] );
1532     BRepAdaptor_Surface surface1( face1, true );
1533     BRepAdaptor_Surface surface2( face2, true );
1534     // TODO: use TrsfFinder2D to superpose the faces
1535     gp_Pnt2d v0f1UV( surface1.FirstUParameter(), surface1.FirstVParameter() );
1536     gp_Pnt2d v0f2UV( surface2.FirstUParameter(), surface2.FirstVParameter() );
1537     gp_Pnt2d v1f1UV( surface1.LastUParameter(),  surface1.LastVParameter() );
1538     gp_Pnt2d v1f2UV( surface2.LastUParameter(),  surface2.LastVParameter() );
1539     double vTolUV =
1540       surface1.UResolution( vTol ) + surface1.VResolution( vTol ); // let's be tolerant
1541     // VV1[0] = TopExp::FirstVertex( edges1.front(), true ); // ori is important if face is closed
1542     // VV1[1] = TopExp::LastVertex ( edges1.front(), true );
1543     // VV2[0] = TopExp::FirstVertex( edges2.front(), true );
1544     // VV2[1] = TopExp::LastVertex ( edges2.front(), true );
1545     // gp_Pnt2d v0f1UV = BRep_Tool::Parameters( VV1[0], face1 );
1546     // gp_Pnt2d v0f2UV = BRep_Tool::Parameters( VV2[0], face2 );
1547     // gp_Pnt2d v1f1UV = BRep_Tool::Parameters( VV1[1], face1 );
1548     // gp_Pnt2d v1f2UV = BRep_Tool::Parameters( VV2[1], face2 );
1549     gp_Vec2d v01f1Vec( v0f1UV, v1f1UV );
1550     gp_Vec2d v01f2Vec( v0f2UV, v1f2UV );
1551     if ( Abs( v01f1Vec.X()-v01f2Vec.X()) < vTolUV &&
1552          Abs( v01f1Vec.Y()-v01f2Vec.Y()) < vTolUV )
1553     {
1554       if ( !OK /*i_ok_wire_algo != 1*/ )
1555       {
1556         edges1.clear();
1557         edges2.clear();
1558         SMESH_Block::GetOrderedEdges( face1, edges1, nbEInW1, VV1[0], i_ok_wire_algo);
1559         SMESH_Block::GetOrderedEdges( face2, edges2, nbEInW2, VV2[0], i_ok_wire_algo);
1560       }
1561       gp_XY dUV = v0f2UV.XY() - v0f1UV.XY(); // UV shift between 2 faces
1562       //
1563       // skip edges of the outer wire (if the outer wire is OK)
1564       list< int >::iterator nbE2, nbE1 = nbEInW1.begin();
1565       list< TopoDS_Edge >::iterator edge2Beg, edge1Beg = edges1.begin();
1566       if ( OK ) std::advance( edge1Beg, *nbE1++ );
1567       list< TopoDS_Edge >::iterator edge2End, edge1End;
1568       //
1569       // find corresponding wires of face2
1570       for ( int iW1 = OK; nbE1 != nbEInW1.end(); ++nbE1, ++iW1 ) // loop on wires of face1
1571       {
1572         // reach an end of edges of a current wire1
1573         edge1End = edge1Beg;
1574         std::advance( edge1End, *nbE1 );
1575         // UV on face1 to find on face2
1576         TopoDS_Vertex v01 = SMESH_MesherHelper::IthVertex(0,*edge1Beg);
1577         TopoDS_Vertex v11 = SMESH_MesherHelper::IthVertex(1,*edge1Beg);
1578         v0f1UV = BRep_Tool::Parameters( v01, face1 );
1579         v1f1UV = BRep_Tool::Parameters( v11, face1 );
1580         v0f1UV.ChangeCoord() += dUV;
1581         v1f1UV.ChangeCoord() += dUV;
1582         //
1583         // look through wires of face2
1584         edge2Beg = edges2.begin();
1585         nbE2     = nbEInW2.begin();
1586         if ( OK ) std::advance( edge2Beg, *nbE2++ );
1587         for ( int iW2 = OK; nbE2 != nbEInW2.end(); ++nbE2, ++iW2 ) // loop on wires of face2
1588         {
1589           // reach an end of edges of a current wire2
1590           edge2End = edge2Beg;
1591           std::advance( edge2End, *nbE2 );
1592           if ( *nbE1 == *nbE2 && iW2 >= iW1 )
1593           {
1594             // rotate edge2 until coincides with edge1 in 2D
1595             int i = *nbE2;
1596             bool sameUV = false;
1597             while ( !( sameUV = sameVertexUV( *edge2Beg, face2, 0, v0f1UV, vTolUV )) && --i > 0 )
1598               // move edge2Beg to place before edge2End
1599               edges2.splice( edge2End, edges2, edge2Beg++ );
1600
1601             if ( sameUV )
1602             {
1603               if ( iW1 == 0 ) OK = true; // OK is for the first wire
1604
1605               // reverse edges2 if needed
1606               if ( SMESH_MesherHelper::IsClosedEdge( *edge1Beg ))
1607               {
1608                 // Commented (so far?) as it's not checked if orientation must be same or reversed
1609                 // double f,l;
1610                 // Handle(Geom2d_Curve) c1 = BRep_Tool::CurveOnSurface( *edge1Beg, face1,f,l );
1611                 // if (  edge1Beg->Orientation() == TopAbs_REVERSED )
1612                 //   std::swap( f,l );
1613                 // gp_Pnt2d uv1 = dUV + c1->Value( f * 0.8 + l * 0.2 ).XY();
1614
1615                 // Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( *edge2Beg, face2,f,l );
1616                 // if (  edge2Beg->Orientation() == TopAbs_REVERSED )
1617                 //   std::swap( f,l );
1618                 // gp_Pnt2d uv2 = c2->Value( f * 0.8 + l * 0.2 );
1619                 // gp_Pnt2d uv3 = c2->Value( l * 0.8 + f * 0.2 );
1620
1621                 // if ( uv1.SquareDistance( uv2 ) > uv1.SquareDistance( uv3 ))
1622                 //   edge2Beg->Reverse();
1623               }
1624               else
1625               {
1626                 if ( !sameVertexUV( *edge2Beg, face2, 1, v1f1UV, vTolUV ))
1627                   reverseEdges( edges2 , *nbE2, std::distance( edges2.begin(),edge2Beg ));
1628               }
1629
1630               // put wire2 at a right place within edges2
1631               if ( iW1 != iW2 ) {
1632                 list< TopoDS_Edge >::iterator place2 = edges2.begin();
1633                 std::advance( place2, std::distance( edges1.begin(), edge1Beg ));
1634                 edges2.splice( place2, edges2, edge2Beg, edge2End );
1635                 // move nbE2 as well
1636                 list< int >::iterator placeNbE2 = nbEInW2.begin();
1637                 std::advance( placeNbE2, iW1 );
1638                 nbEInW2.splice( placeNbE2, nbEInW2, nbE2 );
1639               }
1640               break;
1641             }
1642           }
1643           // prepare for the next wire loop
1644           edge2Beg = edge2End;
1645         }
1646         edge1Beg = edge1End;
1647       }
1648     }
1649   }
1650
1651   const int nbEdges = nbEInW1.front();
1652   if ( OK && nbEdges == 2 )
1653   {
1654     // if wires include 2 edges, it's impossible to associate them using
1655     // topological information only. Try to use length of edges for association.
1656     double l1[2], l2[2];
1657     edgeIt = edges1.begin();
1658     l1[0] = SMESH_Algo::EdgeLength( *edgeIt++ );
1659     l1[1] = SMESH_Algo::EdgeLength( *edgeIt++ );
1660     if ( Abs( l1[0] - l1[1] ) > 0.1 * Max( l1[0], l1[1] ) )
1661     {
1662       edgeIt = edges2.begin();
1663       l2[0] = SMESH_Algo::EdgeLength( *edgeIt++ );
1664       l2[1] = SMESH_Algo::EdgeLength( *edgeIt++ );
1665       if (( l1[0] < l1[1] ) != ( l2[0] < l2[1] ))
1666       {
1667         reverseEdges( edges2, nbEdges );
1668       }
1669     }
1670   }
1671
1672   return OK ? nbEInW1.front() : 0;
1673 }
1674
1675 //=======================================================================
1676 //function : InitVertexAssociation
1677 //purpose  : 
1678 //=======================================================================
1679
1680 void StdMeshers_ProjectionUtils::InitVertexAssociation( const SMESH_Hypothesis* theHyp,
1681                                                         TShapeShapeMap &        theAssociationMap)
1682 {
1683   string hypName = theHyp->GetName();
1684   if ( hypName == "ProjectionSource1D" ) {
1685     const StdMeshers_ProjectionSource1D * hyp =
1686       static_cast<const StdMeshers_ProjectionSource1D*>( theHyp );
1687     if ( hyp->HasVertexAssociation() )
1688       InsertAssociation( hyp->GetTargetVertex(),hyp->GetSourceVertex(),theAssociationMap );
1689   }
1690   else if ( hypName == "ProjectionSource2D" ) {
1691     const StdMeshers_ProjectionSource2D * hyp =
1692       static_cast<const StdMeshers_ProjectionSource2D*>( theHyp );
1693     if ( hyp->HasVertexAssociation() ) {
1694       InsertAssociation( hyp->GetTargetVertex(1),hyp->GetSourceVertex(1),theAssociationMap);
1695       InsertAssociation( hyp->GetTargetVertex(2),hyp->GetSourceVertex(2),theAssociationMap);
1696     }
1697   }
1698   else if ( hypName == "ProjectionSource3D" ) {
1699     const StdMeshers_ProjectionSource3D * hyp =
1700       static_cast<const StdMeshers_ProjectionSource3D*>( theHyp );
1701     if ( hyp->HasVertexAssociation() ) {
1702       InsertAssociation( hyp->GetTargetVertex(1),hyp->GetSourceVertex(1),theAssociationMap);
1703       InsertAssociation( hyp->GetTargetVertex(2),hyp->GetSourceVertex(2),theAssociationMap);
1704     }
1705   }
1706 }
1707
1708 //=======================================================================
1709 /*
1710  * Inserts association theShape1 <-> theShape2 to TShapeShapeMap
1711  *  \param theShape1 - target shape
1712  *  \param theShape2 - source shape
1713  *  \param theAssociationMap - association map 
1714  *  \retval bool - true if there was no association for these shapes before
1715  */
1716 //=======================================================================
1717
1718 bool StdMeshers_ProjectionUtils::InsertAssociation( const TopoDS_Shape& theShape1, // tgt
1719                                                     const TopoDS_Shape& theShape2, // src
1720                                                     TShapeShapeMap &    theAssociationMap)
1721 {
1722   if ( !theShape1.IsNull() && !theShape2.IsNull() ) {
1723     SHOW_SHAPE(theShape1,"Assoc ");
1724     SHOW_SHAPE(theShape2," to ");
1725     bool isNew = ( theAssociationMap.Bind( theShape1, theShape2 ));
1726     return isNew;
1727   }
1728   else {
1729     throw SALOME_Exception("StdMeshers_ProjectionUtils: attempt to associate NULL shape");
1730   }
1731   return false;
1732 }
1733
1734 //=======================================================================
1735 /*
1736  * Finds an edge by its vertices in a main shape of the mesh
1737  *  \param aMesh - the mesh
1738  *  \param V1 - vertex 1
1739  *  \param V2 - vertex 2
1740  *  \retval TopoDS_Edge - found edge
1741  */
1742 //=======================================================================
1743
1744 TopoDS_Edge StdMeshers_ProjectionUtils::GetEdgeByVertices( SMESH_Mesh*          theMesh,
1745                                                            const TopoDS_Vertex& theV1,
1746                                                            const TopoDS_Vertex& theV2)
1747 {
1748   if ( theMesh && !theV1.IsNull() && !theV2.IsNull() )
1749   {
1750     TopTools_ListIteratorOfListOfShape ancestorIt( theMesh->GetAncestors( theV1 ));
1751     for ( ; ancestorIt.More(); ancestorIt.Next() )
1752       if ( ancestorIt.Value().ShapeType() == TopAbs_EDGE )
1753         for ( TopExp_Explorer expV ( ancestorIt.Value(), TopAbs_VERTEX );
1754               expV.More();
1755               expV.Next() )
1756           if ( theV2.IsSame( expV.Current() ))
1757             return TopoDS::Edge( ancestorIt.Value() );
1758   }
1759   return TopoDS_Edge();
1760 }
1761
1762 //================================================================================
1763 /*
1764  * Return another face sharing an edge
1765  *  \param edgeToFaces - data map of descendants to ancestors
1766  *  \param edge - edge
1767  *  \param face - face
1768  *  \retval TopoDS_Face - found face
1769  */
1770 //================================================================================
1771
1772 TopoDS_Face StdMeshers_ProjectionUtils::GetNextFace( const TAncestorMap& edgeToFaces,
1773                                                      const TopoDS_Edge&  edge,
1774                                                      const TopoDS_Face&  face)
1775 {
1776 //   if ( !edge.IsNull() && !face.IsNull() && edgeToFaces.Contains( edge ))
1777   if ( !edge.IsNull() && edgeToFaces.Contains( edge )) // PAL16202
1778   {
1779     TopTools_ListIteratorOfListOfShape ancestorIt( edgeToFaces.FindFromKey( edge ));
1780     for ( ; ancestorIt.More(); ancestorIt.Next() )
1781       if ( ancestorIt.Value().ShapeType() == TopAbs_FACE &&
1782            !face.IsSame( ancestorIt.Value() ))
1783         return TopoDS::Face( ancestorIt.Value() );
1784   }
1785   return TopoDS_Face();
1786 }
1787
1788 //================================================================================
1789 /*
1790  * Return other vertex of an edge
1791  */
1792 //================================================================================
1793
1794 TopoDS_Vertex StdMeshers_ProjectionUtils::GetNextVertex(const TopoDS_Edge&   edge,
1795                                                         const TopoDS_Vertex& vertex)
1796 {
1797   TopoDS_Vertex vF,vL;
1798   TopExp::Vertices(edge,vF,vL);
1799   if ( vF.IsSame( vL ))
1800     return TopoDS_Vertex();
1801   return vertex.IsSame( vF ) ? vL : vF; 
1802 }
1803
1804 //================================================================================
1805 /*
1806  * Return a propagation edge
1807  *  \param aMesh - mesh
1808  *  \param anEdge - edge to find by propagation
1809  *  \param fromEdge - start edge for propagation
1810  *  \param chain - return, if !NULL, a propagation chain passed till
1811  *         anEdge; if anEdge.IsNull() then a full propagation chain is returned;
1812  *         fromEdge is the 1st in the chain
1813  *  \retval pair<int,TopoDS_Edge> - propagation step and found edge
1814  */
1815 //================================================================================
1816
1817 pair<int,TopoDS_Edge>
1818 StdMeshers_ProjectionUtils::GetPropagationEdge( SMESH_Mesh*                 aMesh,
1819                                                 const TopoDS_Edge&          anEdge,
1820                                                 const TopoDS_Edge&          fromEdge,
1821                                                 TopTools_IndexedMapOfShape* chain)
1822 {
1823   TopTools_IndexedMapOfShape locChain;
1824   TopTools_IndexedMapOfShape& aChain = chain ? *chain : locChain;
1825   int step = 0;
1826
1827   //TopTools_IndexedMapOfShape checkedWires;
1828   BRepTools_WireExplorer aWE;
1829   TopoDS_Shape fourEdges[4];
1830
1831   // List of edges, added to chain on the previous cycle pass
1832   TopTools_ListOfShape listPrevEdges;
1833   listPrevEdges.Append( fromEdge );
1834   aChain.Add( fromEdge );
1835
1836   // Collect all edges pass by pass
1837   while (listPrevEdges.Extent() > 0)
1838   {
1839     step++;
1840     // List of edges, added to chain on this cycle pass
1841     TopTools_ListOfShape listCurEdges;
1842
1843     // Find the next portion of edges
1844     TopTools_ListIteratorOfListOfShape itE (listPrevEdges);
1845     for (; itE.More(); itE.Next())
1846     {
1847       const TopoDS_Shape& anE = itE.Value();
1848
1849       // Iterate on faces, having edge <anE>
1850       TopTools_ListIteratorOfListOfShape itA (aMesh->GetAncestors(anE));
1851       for (; itA.More(); itA.Next())
1852       {
1853         const TopoDS_Shape& aW = itA.Value();
1854
1855         // There are objects of different type among the ancestors of edge
1856         if ( aW.ShapeType() == TopAbs_WIRE /*&& checkedWires.Add( aW )*/)
1857         {
1858           Standard_Integer nb = 0, found = -1;
1859           for ( aWE.Init( TopoDS::Wire( aW )); aWE.More(); aWE.Next() ) {
1860             if (nb+1 > 4) {
1861               found = -1;
1862               break;
1863             }
1864             fourEdges[ nb ] = aWE.Current();
1865             if ( aWE.Current().IsSame( anE )) found = nb;
1866             nb++;
1867           }
1868           if (nb == 4 && found >= 0) {
1869             // Quadrangle face found, get an opposite edge
1870             TopoDS_Shape& anOppE = fourEdges[( found + 2 ) % 4 ];
1871
1872             // add anOppE to aChain if ...
1873             int prevChainSize = aChain.Extent();
1874             if ( aChain.Add(anOppE) > prevChainSize ) { // ... anOppE is not in aChain
1875               // Add found edge to the chain oriented so that to
1876               // have it co-directed with a fromEdge
1877               TopAbs_Orientation ori = anE.Orientation();
1878               if ( anOppE.Orientation() == fourEdges[found].Orientation() )
1879                 ori = TopAbs::Reverse( ori );
1880               anOppE.Orientation( ori );
1881               if ( anOppE.IsSame( anEdge ))
1882                 return make_pair( step, TopoDS::Edge( anOppE ));
1883               listCurEdges.Append(anOppE);
1884             }
1885           } // if (nb == 4 && found >= 0)
1886         } // if (aF.ShapeType() == TopAbs_WIRE)
1887       } // loop on ancestors of anE
1888     } // loop on listPrevEdges
1889
1890     listPrevEdges = listCurEdges;
1891   } // while (listPrevEdges.Extent() > 0)
1892
1893   return make_pair( INT_MAX, TopoDS_Edge());
1894 }
1895
1896 //================================================================================
1897 /*
1898  * Find corresponding nodes on two faces
1899  *  \param face1 - the first face
1900  *  \param mesh1 - mesh containing elements on the first face
1901  *  \param face2 - the second face
1902  *  \param mesh2 - mesh containing elements on the second face
1903  *  \param assocMap - map associating sub-shapes of the faces
1904  *  \param node1To2Map - map containing found matching nodes
1905  *  \retval bool - is a success
1906  */
1907 //================================================================================
1908
1909 bool StdMeshers_ProjectionUtils::
1910 FindMatchingNodesOnFaces( const TopoDS_Face&     face1,
1911                           SMESH_Mesh*            mesh1,
1912                           const TopoDS_Face&     face2,
1913                           SMESH_Mesh*            mesh2,
1914                           const TShapeShapeMap & assocMap,
1915                           TNodeNodeMap &         node1To2Map)
1916 {
1917   SMESHDS_Mesh* meshDS1 = mesh1->GetMeshDS();
1918   SMESHDS_Mesh* meshDS2 = mesh2->GetMeshDS();
1919
1920   SMESH_MesherHelper helper1( *mesh1 );
1921   SMESH_MesherHelper helper2( *mesh2 );
1922
1923   // Get corresponding submeshes and roughly check match of meshes
1924
1925   SMESHDS_SubMesh * SM2 = meshDS2->MeshElements( face2 );
1926   SMESHDS_SubMesh * SM1 = meshDS1->MeshElements( face1 );
1927   if ( !SM2 || !SM1 )
1928     RETURN_BAD_RESULT("Empty submeshes");
1929   if ( SM2->NbNodes()    != SM1->NbNodes() ||
1930        SM2->NbElements() != SM1->NbElements() )
1931     RETURN_BAD_RESULT("Different meshes on corresponding faces "
1932                       << meshDS1->ShapeToIndex( face1 ) << " and "
1933                       << meshDS2->ShapeToIndex( face2 ));
1934   if ( SM2->NbElements() == 0 )
1935     RETURN_BAD_RESULT("Empty submeshes");
1936
1937   helper1.SetSubShape( face1 );
1938   helper2.SetSubShape( face2 );
1939   if ( helper1.HasRealSeam() != helper2.HasRealSeam() )
1940     RETURN_BAD_RESULT("Different faces' geometry");
1941
1942   // Data to call SMESH_MeshEditor::FindMatchingNodes():
1943
1944   // 1. Nodes of corresponding links:
1945
1946   // get 2 matching edges, try to find not seam ones
1947   TopoDS_Edge edge1, edge2, seam1, seam2, anyEdge1, anyEdge2;
1948   TopExp_Explorer eE( OuterShape( face2, TopAbs_WIRE ), TopAbs_EDGE );
1949   do {
1950     // edge 2
1951     TopoDS_Edge e2 = TopoDS::Edge( eE.Current() );
1952     eE.Next();
1953     // edge 1
1954     if ( !assocMap.IsBound( e2, /*is2nd=*/true ))
1955       continue;
1956       //RETURN_BAD_RESULT("Association not found for edge " << meshDS2->ShapeToIndex( e2 ));
1957     TopoDS_Edge e1 = TopoDS::Edge( assocMap( e2, /*is2nd=*/true ));
1958     if ( !helper1.IsSubShape( e1, face1 ))
1959       RETURN_BAD_RESULT("Wrong association, edge " << meshDS1->ShapeToIndex( e1 ) <<
1960                         " isn't a sub-shape of face " << meshDS1->ShapeToIndex( face1 ));
1961     // check that there are nodes on edges
1962     SMESHDS_SubMesh * eSM1 = meshDS1->MeshElements( e1 );
1963     SMESHDS_SubMesh * eSM2 = meshDS2->MeshElements( e2 );
1964     bool nodesOnEdges = ( eSM1 && eSM2 && eSM1->NbNodes() && eSM2->NbNodes() );
1965     // check that the nodes on edges belong to faces
1966     // (as NETGEN ignores nodes on the degenerated geom edge)
1967     bool nodesOfFaces = false;
1968     if ( nodesOnEdges ) {
1969       const SMDS_MeshNode* n1 = eSM1->GetNodes()->next();
1970       const SMDS_MeshNode* n2 = eSM2->GetNodes()->next();
1971       nodesOfFaces = ( n1->GetInverseElementIterator(SMDSAbs_Face)->more() &&
1972                        n2->GetInverseElementIterator(SMDSAbs_Face)->more() );
1973     }
1974     if ( nodesOfFaces )
1975     {
1976       if ( helper2.IsRealSeam( e2 )) {
1977         seam1 = e1; seam2 = e2;
1978       }
1979       else {
1980         edge1 = e1; edge2 = e2;
1981       }
1982     }
1983     else {
1984       anyEdge1 = e1; anyEdge2 = e2;
1985     }
1986   } while ( edge2.IsNull() && eE.More() );
1987   //
1988   if ( edge2.IsNull() ) {
1989     edge1 = seam1; edge2 = seam2;
1990   }
1991   bool hasNodesOnEdge = (! edge2.IsNull() );
1992   if ( !hasNodesOnEdge ) {
1993     // 0020338 - nb segments == 1
1994     edge1 = anyEdge1; edge2 = anyEdge2;
1995   }
1996
1997   // get 2 matching vertices
1998   TopoDS_Vertex V2 = TopExp::FirstVertex( TopoDS::Edge( edge2 ));
1999   if ( !assocMap.IsBound( V2, /*is2nd=*/true ))
2000   {
2001     V2 = TopExp::LastVertex( TopoDS::Edge( edge2 ));
2002     if ( !assocMap.IsBound( V2, /*is2nd=*/true ))
2003       RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
2004   }
2005   TopoDS_Vertex V1 = TopoDS::Vertex( assocMap( V2, /*is2nd=*/true ));
2006
2007   // nodes on vertices
2008   const SMDS_MeshNode* vNode1 = SMESH_Algo::VertexNode( V1, meshDS1 );
2009   const SMDS_MeshNode* vNode2 = SMESH_Algo::VertexNode( V2, meshDS2 );
2010   if ( !vNode1 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS1->ShapeToIndex( V1 ));
2011   if ( !vNode2 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS2->ShapeToIndex( V2 ));
2012
2013   // nodes on edges linked with nodes on vertices
2014   const SMDS_MeshNode* nullNode = 0;
2015   vector< const SMDS_MeshNode*> eNode1( 2, nullNode );
2016   vector< const SMDS_MeshNode*> eNode2( 2, nullNode );
2017   if ( hasNodesOnEdge )
2018   {
2019     int nbNodeToGet = 1;
2020     if ( helper1.IsClosedEdge( edge1 ) || helper2.IsClosedEdge( edge2 ) )
2021       nbNodeToGet = 2;
2022     for ( int is2 = 0; is2 < 2; ++is2 )
2023     {
2024       TopoDS_Edge &     edge  = is2 ? edge2 : edge1;
2025       SMESHDS_Mesh *    smDS  = is2 ? meshDS2 : meshDS1;
2026       SMESHDS_SubMesh* edgeSM = smDS->MeshElements( edge );
2027       // nodes linked with ones on vertices
2028       const SMDS_MeshNode*           vNode = is2 ? vNode2 : vNode1;
2029       vector< const SMDS_MeshNode*>& eNode = is2 ? eNode2 : eNode1;
2030       int nbGotNode = 0;
2031       SMDS_ElemIteratorPtr vElem = vNode->GetInverseElementIterator(SMDSAbs_Edge);
2032       while ( vElem->more() && nbGotNode != nbNodeToGet ) {
2033         const SMDS_MeshElement* elem = vElem->next();
2034         if ( edgeSM->Contains( elem ))
2035           eNode[ nbGotNode++ ] = 
2036             ( elem->GetNode(0) == vNode ) ? elem->GetNode(1) : elem->GetNode(0);
2037       }
2038       if ( nbGotNode > 1 ) // sort found nodes by param on edge
2039       {
2040         SMESH_MesherHelper* helper = is2 ? &helper2 : &helper1;
2041         double u0 = helper->GetNodeU( edge, eNode[ 0 ]);
2042         double u1 = helper->GetNodeU( edge, eNode[ 1 ]);
2043         if ( u0 > u1 ) std::swap( eNode[ 0 ], eNode[ 1 ]);
2044       }
2045       if ( nbGotNode == 0 )
2046         RETURN_BAD_RESULT("Found no nodes on edge " << smDS->ShapeToIndex( edge ) <<
2047                           " linked to " << vNode );
2048     }
2049   }
2050   else // 0020338 - nb segments == 1
2051   {
2052     // get 2 other matching vertices
2053     V2 = TopExp::LastVertex( TopoDS::Edge( edge2 ));
2054     if ( !assocMap.IsBound( V2, /*is2nd=*/true ))
2055       RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
2056     V1 = TopoDS::Vertex( assocMap( V2, /*is2nd=*/true ));
2057
2058     // nodes on vertices
2059     eNode1[0] = SMESH_Algo::VertexNode( V1, meshDS1 );
2060     eNode2[0] = SMESH_Algo::VertexNode( V2, meshDS2 );
2061     if ( !eNode1[0] ) RETURN_BAD_RESULT("No node on vertex #" << meshDS1->ShapeToIndex( V1 ));
2062     if ( !eNode2[0] ) RETURN_BAD_RESULT("No node on vertex #" << meshDS2->ShapeToIndex( V2 ));
2063   }
2064
2065   // 2. face sets
2066
2067   int assocRes;
2068   for ( int iAttempt = 0; iAttempt < 2; ++iAttempt )
2069   {
2070     set<const SMDS_MeshElement*> Elems1, Elems2;
2071     for ( int is2 = 0; is2 < 2; ++is2 )
2072     {
2073       set<const SMDS_MeshElement*> & elems = is2 ? Elems2 : Elems1;
2074       SMESHDS_SubMesh*                  sm = is2 ? SM2 : SM1;
2075       SMESH_MesherHelper*           helper = is2 ? &helper2 : &helper1;
2076       const TopoDS_Face &             face = is2 ? face2 : face1;
2077       SMDS_ElemIteratorPtr eIt = sm->GetElements();
2078
2079       if ( !helper->IsRealSeam( is2 ? edge2 : edge1 ))
2080       {
2081         while ( eIt->more() ) elems.insert( elems.end(), eIt->next() );
2082       }
2083       else
2084       {
2085         // the only suitable edge is seam, i.e. it is a sphere.
2086         // FindMatchingNodes() will not know which way to go from any edge.
2087         // So we ignore all faces having nodes on edges or vertices except
2088         // one of faces sharing current start nodes
2089
2090         // find a face to keep
2091         const SMDS_MeshElement* faceToKeep = 0;
2092         const SMDS_MeshNode* vNode = is2 ? vNode2 : vNode1;
2093         const SMDS_MeshNode* eNode = is2 ? eNode2[0] : eNode1[0];
2094         TIDSortedElemSet inSet, notInSet;
2095
2096         const SMDS_MeshElement* f1 =
2097           SMESH_MeshAlgos::FindFaceInSet( vNode, eNode, inSet, notInSet );
2098         if ( !f1 ) RETURN_BAD_RESULT("The first face on seam not found");
2099         notInSet.insert( f1 );
2100
2101         const SMDS_MeshElement* f2 =
2102           SMESH_MeshAlgos::FindFaceInSet( vNode, eNode, inSet, notInSet );
2103         if ( !f2 ) RETURN_BAD_RESULT("The second face on seam not found");
2104
2105         // select a face with less UV of vNode
2106         const SMDS_MeshNode* notSeamNode[2] = {0, 0};
2107         for ( int iF = 0; iF < 2; ++iF ) {
2108           const SMDS_MeshElement* f = ( iF ? f2 : f1 );
2109           for ( int i = 0; !notSeamNode[ iF ] && i < f->NbNodes(); ++i ) {
2110             const SMDS_MeshNode* node = f->GetNode( i );
2111             if ( !helper->IsSeamShape( node->getshapeId() ))
2112               notSeamNode[ iF ] = node;
2113           }
2114         }
2115         gp_Pnt2d uv1 = helper->GetNodeUV( face, vNode, notSeamNode[0] );
2116         gp_Pnt2d uv2 = helper->GetNodeUV( face, vNode, notSeamNode[1] );
2117         if ( uv1.X() + uv1.Y() > uv2.X() + uv2.Y() )
2118           faceToKeep = f2;
2119         else
2120           faceToKeep = f1;
2121
2122         // fill elem set
2123         elems.insert( faceToKeep );
2124         while ( eIt->more() ) {
2125           const SMDS_MeshElement* f = eIt->next();
2126           int nbNodes = f->NbNodes();
2127           if ( f->IsQuadratic() )
2128             nbNodes /= 2;
2129           bool onBnd = false;
2130           for ( int i = 0; !onBnd && i < nbNodes; ++i ) {
2131             const SMDS_MeshNode* node = f->GetNode( i );
2132             onBnd = ( node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE);
2133           }
2134           if ( !onBnd )
2135             elems.insert( f );
2136         }
2137         // add also faces adjacent to faceToKeep
2138         int nbNodes = faceToKeep->NbNodes();
2139         if ( faceToKeep->IsQuadratic() ) nbNodes /= 2;
2140         notInSet.insert( f1 );
2141         notInSet.insert( f2 );
2142         for ( int i = 0; i < nbNodes; ++i ) {
2143           const SMDS_MeshNode* n1 = faceToKeep->GetNode( i );
2144           const SMDS_MeshNode* n2 = faceToKeep->GetNode(( i+1 ) % nbNodes );
2145           f1 = SMESH_MeshAlgos::FindFaceInSet( n1, n2, inSet, notInSet );
2146           if ( f1 )
2147             elems.insert( f1 );
2148         }
2149       } // case on a sphere
2150     } // loop on 2 faces
2151
2152     node1To2Map.clear();
2153     assocRes = SMESH_MeshEditor::FindMatchingNodes( Elems1, Elems2,
2154                                                     vNode1, vNode2,
2155                                                     eNode1[0], eNode2[0],
2156                                                     node1To2Map);
2157     if (( assocRes != SMESH_MeshEditor::SEW_OK ) &&
2158         ( eNode1[1] || eNode2[1] )) // there is another node to try (on a closed EDGE)
2159     {
2160       node1To2Map.clear();
2161       if ( eNode1[1] ) std::swap( eNode1[0], eNode1[1] );
2162       else             std::swap( eNode2[0], eNode2[1] );
2163       continue; // one more attempt
2164     }
2165
2166     break;
2167   }
2168   if ( assocRes != SMESH_MeshEditor::SEW_OK )
2169     RETURN_BAD_RESULT("FindMatchingNodes() result " << assocRes );
2170
2171   // On a sphere, add matching nodes on the edge
2172
2173   if ( helper1.IsRealSeam( edge1 ))
2174   {
2175     // sort nodes on edges by param on edge
2176     map< double, const SMDS_MeshNode* > u2nodesMaps[2];
2177     for ( int is2 = 0; is2 < 2; ++is2 )
2178     {
2179       TopoDS_Edge &     edge  = is2 ? edge2 : edge1;
2180       SMESHDS_Mesh *    smDS  = is2 ? meshDS2 : meshDS1;
2181       SMESHDS_SubMesh* edgeSM = smDS->MeshElements( edge );
2182       map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[ is2 ];
2183
2184       SMDS_NodeIteratorPtr nIt = edgeSM->GetNodes();
2185       while ( nIt->more() ) {
2186         const SMDS_MeshNode* node = nIt->next();
2187         const SMDS_EdgePosition* pos =
2188           static_cast<const SMDS_EdgePosition*>(node->GetPosition());
2189         pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
2190       }
2191       if ((int) pos2nodes.size() != edgeSM->NbNodes() )
2192         RETURN_BAD_RESULT("Equal params of nodes on edge "
2193                           << smDS->ShapeToIndex( edge ) << " of face " << is2 );
2194     }
2195     if ( u2nodesMaps[0].size() != u2nodesMaps[1].size() )
2196       RETURN_BAD_RESULT("Different nb of new nodes on edges or wrong params");
2197
2198     // compare edge orientation
2199     double u1 = helper1.GetNodeU( edge1, vNode1 );
2200     double u2 = helper2.GetNodeU( edge2, vNode2 );
2201     bool isFirst1 = ( u1 < u2nodesMaps[0].begin()->first );
2202     bool isFirst2 = ( u2 < u2nodesMaps[1].begin()->first );
2203     bool reverse ( isFirst1 != isFirst2 );
2204
2205     // associate matching nodes
2206     map< double, const SMDS_MeshNode* >::iterator u_Node1, u_Node2, end1;
2207     map< double, const SMDS_MeshNode* >::reverse_iterator uR_Node2;
2208     u_Node1 = u2nodesMaps[0].begin();
2209     u_Node2 = u2nodesMaps[1].begin();
2210     uR_Node2 = u2nodesMaps[1].rbegin();
2211     end1 = u2nodesMaps[0].end();
2212     for ( ; u_Node1 != end1; ++u_Node1 ) {
2213       const SMDS_MeshNode* n1 = u_Node1->second;
2214       const SMDS_MeshNode* n2 = ( reverse ? (uR_Node2++)->second : (u_Node2++)->second );
2215       node1To2Map.insert( make_pair( n1, n2 ));
2216     }
2217
2218     // associate matching nodes on the last vertices
2219     V2 = TopExp::LastVertex( TopoDS::Edge( edge2 ));
2220     if ( !assocMap.IsBound( V2, /*is2nd=*/true ))
2221       RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
2222     V1 = TopoDS::Vertex( assocMap( V2, /*is2nd=*/true ));
2223     vNode1 = SMESH_Algo::VertexNode( V1, meshDS1 );
2224     vNode2 = SMESH_Algo::VertexNode( V2, meshDS2 );
2225     if ( !vNode1 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS1->ShapeToIndex( V1 ));
2226     if ( !vNode2 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS2->ShapeToIndex( V2 ));
2227     node1To2Map.insert( make_pair( vNode1, vNode2 ));
2228   }
2229
2230   // don't know why this condition is usually true :(
2231   //   if ( node1To2Map.size() * quadFactor < SM1->NbNodes() )
2232   //     MESSAGE("FindMatchingNodes() found too few node pairs starting from nodes ("
2233   //             << vNode1->GetID() << " - " << eNode1[0]->GetID() << ") ("
2234   //             << vNode2->GetID() << " - " << eNode2[0]->GetID() << "):"
2235   //             << node1To2Map.size() * quadFactor << " < " << SM1->NbNodes());
2236
2237   return true;
2238 }
2239
2240 //================================================================================
2241 /*
2242  * Return any sub-shape of a face belonging to the outer wire
2243  *  \param face - the face
2244  *  \param type - type of sub-shape to return
2245  *  \retval TopoDS_Shape - the found sub-shape
2246  */
2247 //================================================================================
2248
2249 TopoDS_Shape StdMeshers_ProjectionUtils::OuterShape( const TopoDS_Face& face,
2250                                                      TopAbs_ShapeEnum   type)
2251 {
2252   TopExp_Explorer exp( BRepTools::OuterWire( face ), type );
2253   if ( exp.More() )
2254     return exp.Current();
2255   return TopoDS_Shape();
2256 }
2257
2258 //================================================================================
2259 /*
2260  * Check that sub-mesh is computed and try to compute it if is not
2261  *  \param sm - sub-mesh to compute
2262  *  \param iterationNb - int used to stop infinite recursive call
2263  *  \retval bool - true if computed
2264  */
2265 //================================================================================
2266
2267 bool StdMeshers_ProjectionUtils::MakeComputed(SMESH_subMesh * sm, const int iterationNb)
2268 {
2269   if ( iterationNb > 10 )
2270     RETURN_BAD_RESULT("Infinite recursive projection");
2271   if ( !sm )
2272     RETURN_BAD_RESULT("NULL submesh");
2273   if ( sm->IsMeshComputed() )
2274     return true;
2275
2276   SMESH_Mesh*   mesh = sm->GetFather();
2277   SMESH_Gen*     gen = mesh->GetGen();
2278   SMESH_Algo*   algo = sm->GetAlgo();
2279   TopoDS_Shape shape = sm->GetSubShape();
2280   if ( !algo )
2281   {
2282     if ( shape.ShapeType() != TopAbs_COMPOUND )
2283     {
2284       // No algo assigned to a non-compound sub-mesh.
2285       // Try to find an all-dimensional algo of an upper dimension
2286       int dim = gen->GetShapeDim( shape );
2287       for ( ++dim; ( dim <= 3 && !algo ); ++dim )
2288       {
2289         SMESH_HypoFilter hypoFilter( SMESH_HypoFilter::IsAlgo() );
2290         hypoFilter.And( SMESH_HypoFilter::HasDim( dim ));
2291         list <const SMESHDS_Hypothesis * > hyps;
2292         list< TopoDS_Shape >               assignedTo;
2293         int nbAlgos =
2294           mesh->GetHypotheses( shape, hypoFilter, hyps, true, &assignedTo );
2295         if ( nbAlgos > 1 ) // concurrent algos
2296         {
2297           vector<SMESH_subMesh*> smList; // where an algo is assigned
2298           list< TopoDS_Shape >::iterator shapeIt = assignedTo.begin();
2299           for ( ; shapeIt != assignedTo.end(); ++shapeIt )
2300             smList.push_back( mesh->GetSubMesh( *shapeIt ));
2301
2302           mesh->SortByMeshOrder( smList );
2303           algo  = smList.front()->GetAlgo();
2304           shape = smList.front()->GetSubShape();
2305         }
2306         else if ( nbAlgos == 1 )
2307         {
2308           algo = (SMESH_Algo*) hyps.front();
2309           shape = assignedTo.front();
2310         }
2311       }
2312       if ( !algo )
2313         return false;
2314     }
2315     else
2316     {
2317       // group
2318       bool computed = true;
2319       for ( TopoDS_Iterator grMember( shape ); grMember.More(); grMember.Next())
2320         if ( SMESH_subMesh* grSub = mesh->GetSubMesh( grMember.Value() ))
2321           if ( !MakeComputed( grSub, iterationNb + 1 ))
2322             computed = false;
2323       return computed;
2324     }
2325   }
2326
2327   string algoType = algo->GetName();
2328   if ( algoType.substr(0, 11) != "Projection_")
2329     return gen->Compute( *mesh, shape, SMESH_Gen::SHAPE_ONLY );
2330
2331   // try to compute source mesh
2332
2333   const list <const SMESHDS_Hypothesis *> & hyps =
2334     algo->GetUsedHypothesis( *mesh, shape );
2335
2336   TopoDS_Shape srcShape;
2337   SMESH_Mesh* srcMesh = 0;
2338   list <const SMESHDS_Hypothesis*>::const_iterator hIt = hyps.begin();
2339   for ( ; srcShape.IsNull() && hIt != hyps.end(); ++hIt ) {
2340     string hypName = (*hIt)->GetName();
2341     if ( hypName == "ProjectionSource1D" ) {
2342       const StdMeshers_ProjectionSource1D * hyp =
2343         static_cast<const StdMeshers_ProjectionSource1D*>( *hIt );
2344       srcShape = hyp->GetSourceEdge();
2345       srcMesh = hyp->GetSourceMesh();
2346     }
2347     else if ( hypName == "ProjectionSource2D" ) {
2348       const StdMeshers_ProjectionSource2D * hyp =
2349         static_cast<const StdMeshers_ProjectionSource2D*>( *hIt );
2350       srcShape = hyp->GetSourceFace();
2351       srcMesh = hyp->GetSourceMesh();
2352     }
2353     else if ( hypName == "ProjectionSource3D" ) {
2354       const StdMeshers_ProjectionSource3D * hyp =
2355         static_cast<const StdMeshers_ProjectionSource3D*>( *hIt );
2356       srcShape = hyp->GetSource3DShape();
2357       srcMesh = hyp->GetSourceMesh();
2358     }
2359   }
2360   if ( srcShape.IsNull() ) // no projection source defined
2361     return gen->Compute( *mesh, shape, /*shapeOnly=*/true );
2362
2363   if ( srcShape.IsSame( shape ))
2364     RETURN_BAD_RESULT("Projection from self");
2365     
2366   if ( !srcMesh )
2367     srcMesh = mesh;
2368
2369   if ( MakeComputed( srcMesh->GetSubMesh( srcShape ), iterationNb + 1 ) &&
2370        gen->Compute( *mesh, shape, SMESH_Gen::SHAPE_ONLY ))
2371     return sm->IsMeshComputed();
2372
2373   return false;
2374 }
2375
2376
2377 //================================================================================
2378 /*
2379  * Returns an error message to show in case if MakeComputed( sm ) fails.
2380  */
2381 //================================================================================
2382
2383 std::string StdMeshers_ProjectionUtils::SourceNotComputedError( SMESH_subMesh * sm,
2384                                                                 SMESH_Algo*     projAlgo )
2385 {
2386   const char usualMessage [] = "Source mesh not computed";
2387   if ( !projAlgo )
2388     return usualMessage;
2389   if ( !sm || sm->GetAlgoState() != SMESH_subMesh::NO_ALGO )
2390     return usualMessage; // algo is OK, anything else is KO.
2391
2392   // Try to find a type of all-dimensional algorithm that would compute the
2393   // given sub-mesh if it could be launched before projection
2394   const TopoDS_Shape shape = sm->GetSubShape();
2395   const int       shapeDim = SMESH_Gen::GetShapeDim( shape );
2396
2397   for ( int dimIncrement = 1; shapeDim + dimIncrement < 4; ++dimIncrement )
2398   {
2399     SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
2400     filter.And( filter.HasDim( shapeDim + dimIncrement ));
2401
2402     SMESH_Algo* algo = (SMESH_Algo*) sm->GetFather()->GetHypothesis( shape, filter, true );
2403     if ( algo && !algo->NeedDiscreteBoundary() )
2404       return SMESH_Comment("\"")
2405         << algo->GetFeatures()._label << "\""
2406         << " can't be used to compute the source mesh for \""
2407         << projAlgo->GetFeatures()._label << "\" in this case";
2408   }
2409   return usualMessage;
2410 }
2411
2412 //================================================================================
2413 /*
2414  * Return a boundary EDGE (or all boundary EDGEs) of edgeContainer
2415  */
2416 //================================================================================
2417
2418 TopoDS_Edge
2419 StdMeshers_ProjectionUtils::GetBoundaryEdge(const TopoDS_Shape&       edgeContainer,
2420                                             const SMESH_Mesh&         mesh,
2421                                             std::list< TopoDS_Edge >* allBndEdges)
2422 {
2423   TopTools_IndexedMapOfShape facesOfEdgeContainer, facesNearEdge;
2424   TopExp::MapShapes( edgeContainer, TopAbs_FACE, facesOfEdgeContainer );
2425
2426   if ( !facesOfEdgeContainer.IsEmpty() ) 
2427     for ( TopExp_Explorer exp(edgeContainer, TopAbs_EDGE); exp.More(); exp.Next() )
2428     {
2429       const TopoDS_Edge& edge = TopoDS::Edge( exp.Current() );
2430       facesNearEdge.Clear();
2431       PShapeIteratorPtr faceIt = SMESH_MesherHelper::GetAncestors( edge, mesh, TopAbs_FACE );
2432       while ( const TopoDS_Shape* face = faceIt->next() )
2433         if ( facesOfEdgeContainer.Contains( *face ))
2434           if ( facesNearEdge.Add( *face ) && facesNearEdge.Extent() > 1 )
2435             break;
2436       if ( facesNearEdge.Extent() == 1 ) {
2437         if ( allBndEdges )
2438           allBndEdges->push_back( edge );
2439         else
2440           return edge;
2441       }
2442     }
2443
2444   return TopoDS_Edge();
2445 }
2446
2447
2448 namespace { // Definition of event listeners
2449
2450   SMESH_subMeshEventListener* getSrcSubMeshListener();
2451
2452   //================================================================================
2453   /*!
2454    * \brief Listener that resets an event listener on source submesh when 
2455    * "ProjectionSource*D" hypothesis is modified
2456    */
2457   //================================================================================
2458
2459   struct HypModifWaiter: SMESH_subMeshEventListener
2460   {
2461     HypModifWaiter():SMESH_subMeshEventListener(false,// won't be deleted by submesh
2462                                                 "StdMeshers_ProjectionUtils::HypModifWaiter") {}
2463     void ProcessEvent(const int event, const int eventType, SMESH_subMesh* subMesh,
2464                       EventListenerData*, const SMESH_Hypothesis*)
2465     {
2466       if ( event     == SMESH_subMesh::MODIF_HYP &&
2467            eventType == SMESH_subMesh::ALGO_EVENT)
2468       {
2469         // delete current source listener
2470         subMesh->DeleteEventListener( getSrcSubMeshListener() );
2471         // let algo set a new one
2472         if ( SMESH_Algo* algo = subMesh->GetAlgo() )
2473           algo->SetEventListener( subMesh );
2474       }
2475     }
2476   };
2477   //================================================================================
2478   /*!
2479    * \brief return static HypModifWaiter
2480    */
2481   //================================================================================
2482
2483   SMESH_subMeshEventListener* getHypModifWaiter() {
2484     static HypModifWaiter aHypModifWaiter;
2485     return &aHypModifWaiter;
2486   }
2487   //================================================================================
2488   /*!
2489    * \brief return static listener for source shape submeshes
2490    */
2491   //================================================================================
2492
2493   SMESH_subMeshEventListener* getSrcSubMeshListener() {
2494     static SMESH_subMeshEventListener srcListener(false, // won't be deleted by submesh
2495                                                   "StdMeshers_ProjectionUtils::SrcSubMeshListener");
2496     return &srcListener;
2497   }
2498 }
2499
2500 //================================================================================
2501 /*
2502  * Set event listeners to submesh with projection algo
2503  *  \param subMesh - submesh with projection algo
2504  *  \param srcShape - source shape
2505  *  \param srcMesh - source mesh
2506  */
2507 //================================================================================
2508
2509 void StdMeshers_ProjectionUtils::SetEventListener(SMESH_subMesh* subMesh,
2510                                                   TopoDS_Shape   srcShape,
2511                                                   SMESH_Mesh*    srcMesh)
2512 {
2513   // Set the listener that resets an event listener on source submesh when
2514   // "ProjectionSource*D" hypothesis is modified since source shape can be changed
2515   subMesh->SetEventListener( getHypModifWaiter(),0,subMesh);
2516
2517   // Set an event listener to submesh of the source shape
2518   if ( !srcShape.IsNull() )
2519   {
2520     if ( !srcMesh )
2521       srcMesh = subMesh->GetFather();
2522
2523     SMESH_subMesh* srcShapeSM = srcMesh->GetSubMesh( srcShape );
2524
2525     if ( srcShapeSM != subMesh ) {
2526       if ( srcShapeSM->GetSubMeshDS() &&
2527            srcShapeSM->GetSubMeshDS()->IsComplexSubmesh() )
2528       {  // source shape is a group
2529         TopExp_Explorer it(srcShapeSM->GetSubShape(), // explore the group into sub-shapes...
2530                            subMesh->GetSubShape().ShapeType()); // ...of target shape type
2531         for (; it.More(); it.Next())
2532         {
2533           SMESH_subMesh* srcSM = srcMesh->GetSubMesh( it.Current() );
2534           if ( srcSM != subMesh )
2535           {
2536             SMESH_subMeshEventListenerData* data =
2537               srcSM->GetEventListenerData(getSrcSubMeshListener());
2538             if ( data )
2539               data->mySubMeshes.push_back( subMesh );
2540             else
2541               data = SMESH_subMeshEventListenerData::MakeData( subMesh );
2542             subMesh->SetEventListener ( getSrcSubMeshListener(), data, srcSM );
2543           }
2544         }
2545       }
2546       else
2547       {
2548         if ( SMESH_subMeshEventListenerData* data =
2549              srcShapeSM->GetEventListenerData( getSrcSubMeshListener() ))
2550         {
2551           bool alreadyIn =
2552             (std::find( data->mySubMeshes.begin(),
2553                         data->mySubMeshes.end(), subMesh ) != data->mySubMeshes.end() );
2554           if ( !alreadyIn )
2555             data->mySubMeshes.push_back( subMesh );
2556         }
2557         else
2558         {
2559           subMesh->SetEventListener( getSrcSubMeshListener(),
2560                                      SMESH_subMeshEventListenerData::MakeData( subMesh ),
2561                                      srcShapeSM );
2562         }
2563       }
2564     }
2565   }
2566 }
2567
2568 namespace StdMeshers_ProjectionUtils
2569 {
2570
2571   //================================================================================
2572   /*!
2573    * \brief Computes transformation between two sets of 2D points using
2574    *        a least square approximation
2575    *
2576    * See "Surface Mesh Projection For Hexahedral Mesh Generation By Sweeping"
2577    * by X.Roca, J.Sarrate, A.Huerta. (2.2)
2578    */
2579   //================================================================================
2580
2581   bool TrsfFinder2D::Solve( const vector< gp_XY >& srcPnts,
2582                             const vector< gp_XY >& tgtPnts )
2583   {
2584     // find gravity centers
2585     gp_XY srcGC( 0,0 ), tgtGC( 0,0 );
2586     for ( size_t i = 0; i < srcPnts.size(); ++i )
2587     {
2588       srcGC += srcPnts[i];
2589       tgtGC += tgtPnts[i];
2590     }
2591     srcGC /= srcPnts.size();
2592     tgtGC /= tgtPnts.size();
2593
2594     // find trsf
2595
2596     math_Matrix mat (1,4,1,4, 0.);
2597     math_Vector vec (1,4, 0.);
2598
2599     // cout << "m1 = smesh.Mesh('src')" << endl
2600     //      << "m2 = smesh.Mesh('tgt')" << endl;
2601     double xx = 0, xy = 0, yy = 0;
2602     for ( size_t i = 0; i < srcPnts.size(); ++i )
2603     {
2604       gp_XY srcUV = srcPnts[i] - srcGC;
2605       gp_XY tgtUV = tgtPnts[i] - tgtGC;
2606       xx += srcUV.X() * srcUV.X();
2607       yy += srcUV.Y() * srcUV.Y();
2608       xy += srcUV.X() * srcUV.Y();
2609       vec( 1 ) += srcUV.X() * tgtUV.X();
2610       vec( 2 ) += srcUV.Y() * tgtUV.X();
2611       vec( 3 ) += srcUV.X() * tgtUV.Y();
2612       vec( 4 ) += srcUV.Y() * tgtUV.Y();
2613       // cout << "m1.AddNode( " << srcUV.X() << ", " << srcUV.Y() << ", 0 )" << endl
2614       //      << "m2.AddNode( " << tgtUV.X() << ", " << tgtUV.Y() << ", 0 )" << endl;
2615     }
2616     mat( 1,1 ) = mat( 3,3 ) = xx;
2617     mat( 2,2 ) = mat( 4,4 ) = yy;
2618     mat( 1,2 ) = mat( 2,1 ) = mat( 3,4 ) = mat( 4,3 ) = xy;
2619
2620     math_Gauss solver( mat );
2621     if ( !solver.IsDone() )
2622       return false;
2623     solver.Solve( vec );
2624     if ( vec.Norm2() < gp::Resolution() )
2625       return false;
2626     // cout << vec( 1 ) << "\t " << vec( 2 ) << endl
2627     //      << vec( 3 ) << "\t " << vec( 4 ) << endl;
2628
2629     _trsf.SetTranslationPart( tgtGC );
2630     _srcOrig = srcGC;
2631
2632     gp_Mat2d& M = const_cast< gp_Mat2d& >( _trsf.VectorialPart());
2633     M( 1,1 ) = vec( 1 );
2634     M( 2,1 ) = vec( 2 ); // | 1 3 | -- is it correct ????????
2635     M( 1,2 ) = vec( 3 ); // | 2 4 |
2636     M( 2,2 ) = vec( 4 );
2637
2638     return true;
2639   }
2640
2641   //================================================================================
2642   /*!
2643    * \brief Transforms a 2D points using a found transformation
2644    */
2645   //================================================================================
2646
2647   gp_XY TrsfFinder2D::Transform( const gp_Pnt2d& srcUV ) const
2648   {
2649     gp_XY uv = srcUV.XY() - _srcOrig ;
2650     _trsf.Transforms( uv );
2651     return uv;
2652   }
2653
2654   //================================================================================
2655   /*!
2656    * \brief Computes transformation between two sets of 3D points using
2657    *        a least square approximation
2658    *
2659    * See "Surface Mesh Projection For Hexahedral Mesh Generation By Sweeping"
2660    * by X.Roca, J.Sarrate, A.Huerta. (2.4)
2661    */
2662   //================================================================================
2663
2664   bool TrsfFinder3D::Solve( const vector< gp_XYZ > & srcPnts,
2665                             const vector< gp_XYZ > & tgtPnts )
2666   {
2667     // find gravity center
2668     gp_XYZ srcGC( 0,0,0 ), tgtGC( 0,0,0 );
2669     for ( size_t i = 0; i < srcPnts.size(); ++i )
2670     {
2671       srcGC += srcPnts[i];
2672       tgtGC += tgtPnts[i];
2673     }
2674     srcGC /= srcPnts.size();
2675     tgtGC /= tgtPnts.size();
2676
2677     gp_XYZ srcOrig = 2 * srcGC - tgtGC;
2678     gp_XYZ tgtOrig = srcGC;
2679
2680     // find trsf
2681
2682     math_Matrix mat (1,9,1,9, 0.);
2683     math_Vector vec (1,9, 0.);
2684
2685     double xx = 0, yy = 0, zz = 0;
2686     double xy = 0, xz = 0, yz = 0;
2687     for ( size_t i = 0; i < srcPnts.size(); ++i )
2688     {
2689       gp_XYZ src = srcPnts[i] - srcOrig;
2690       gp_XYZ tgt = tgtPnts[i] - tgtOrig;
2691       xx += src.X() * src.X();
2692       yy += src.Y() * src.Y();
2693       zz += src.Z() * src.Z();
2694       xy += src.X() * src.Y();
2695       xz += src.X() * src.Z();
2696       yz += src.Y() * src.Z();
2697       vec( 1 ) += src.X() * tgt.X();
2698       vec( 2 ) += src.Y() * tgt.X();
2699       vec( 3 ) += src.Z() * tgt.X();
2700       vec( 4 ) += src.X() * tgt.Y();
2701       vec( 5 ) += src.Y() * tgt.Y();
2702       vec( 6 ) += src.Z() * tgt.Y();
2703       vec( 7 ) += src.X() * tgt.Z();
2704       vec( 8 ) += src.Y() * tgt.Z();
2705       vec( 9 ) += src.Z() * tgt.Z();
2706     }
2707     mat( 1,1 ) = mat( 4,4 ) = mat( 7,7 ) = xx;
2708     mat( 2,2 ) = mat( 5,5 ) = mat( 8,8 ) = yy;
2709     mat( 3,3 ) = mat( 6,6 ) = mat( 9,9 ) = zz;
2710     mat( 1,2 ) = mat( 2,1 ) = mat( 4,5 ) = mat( 5,4 ) = mat( 7,8 ) = mat( 8,7 ) = xy;
2711     mat( 1,3 ) = mat( 3,1 ) = mat( 4,6 ) = mat( 6,4 ) = mat( 7,9 ) = mat( 9,7 ) = xz;
2712     mat( 2,3 ) = mat( 3,2 ) = mat( 5,6 ) = mat( 6,5 ) = mat( 8,9 ) = mat( 9,8 ) = yz;
2713
2714     math_Gauss solver( mat );
2715     if ( !solver.IsDone() )
2716       return false;
2717     solver.Solve( vec );
2718     if ( vec.Norm2() < gp::Resolution() )
2719       return false;
2720     // cout << endl
2721     //      << vec( 1 ) << "\t " << vec( 2 ) << "\t " << vec( 3 ) << endl
2722     //      << vec( 4 ) << "\t " << vec( 5 ) << "\t " << vec( 6 ) << endl
2723     //      << vec( 7 ) << "\t " << vec( 8 ) << "\t " << vec( 9 ) << endl;
2724
2725     _srcOrig = srcOrig;
2726     _trsf.SetTranslationPart( tgtOrig );
2727
2728     gp_Mat& M = const_cast< gp_Mat& >( _trsf.VectorialPart() );
2729     M.SetRows( gp_XYZ( vec( 1 ), vec( 2 ), vec( 3 )),
2730                gp_XYZ( vec( 4 ), vec( 5 ), vec( 6 )),
2731                gp_XYZ( vec( 7 ), vec( 8 ), vec( 9 )));
2732     return true;
2733   }
2734
2735   //================================================================================
2736   /*!
2737    * \brief Transforms a 3D point using a found transformation
2738    */
2739   //================================================================================
2740
2741   gp_XYZ TrsfFinder3D::Transform( const gp_Pnt& srcP ) const
2742   {
2743     gp_XYZ p = srcP.XYZ() - _srcOrig;
2744     _trsf.Transforms( p );
2745     return p;
2746   }
2747
2748   //================================================================================
2749   /*!
2750    * \brief Transforms a 3D vector using a found transformation
2751    */
2752   //================================================================================
2753
2754   gp_XYZ TrsfFinder3D::TransformVec( const gp_Vec& v ) const
2755   {
2756     return v.XYZ().Multiplied( _trsf.VectorialPart() );
2757   }
2758   //================================================================================
2759   /*!
2760    * \brief Inversion
2761    */
2762   //================================================================================
2763
2764   bool TrsfFinder3D::Invert()
2765   {
2766     if (( _trsf.Form() == gp_Translation ) &&
2767         ( _srcOrig.X() != 0 || _srcOrig.Y() != 0 || _srcOrig.Z() != 0 ))
2768     {
2769       // seems to be defined via Solve()
2770       gp_XYZ newSrcOrig = _trsf.TranslationPart();
2771       gp_Mat& M = const_cast< gp_Mat& >( _trsf.VectorialPart() );
2772       const double D = M.Determinant();
2773       if ( D < 1e-3 * ( newSrcOrig - _srcOrig ).Modulus() )
2774       {
2775 #ifdef _DEBUG_
2776         cerr << "TrsfFinder3D::Invert()"
2777              << "D " << M.Determinant() << " IsSingular " << M.IsSingular() << endl;
2778 #endif
2779         return false;
2780       }
2781       gp_Mat Minv = M.Inverted();
2782       _trsf.SetTranslationPart( _srcOrig );
2783       _srcOrig = newSrcOrig;
2784       M = Minv;
2785     }
2786     else
2787     {
2788       _trsf.Invert();
2789     }
2790     return true;
2791   }
2792
2793   //================================================================================
2794   /*!
2795    * \brief Add in-FACE nodes surrounding a given node to a queue
2796    */
2797   //================================================================================
2798
2799   typedef list< pair< const SMDS_MeshNode*, const BRepMesh_Triangle* > > TNodeTriaList;
2800
2801   void addCloseNodes( const SMDS_MeshNode*     srcNode,
2802                       const BRepMesh_Triangle* bmTria,
2803                       const int                srcFaceID,
2804                       TNodeTriaList &          noTriQueue )
2805   {
2806     // find in-FACE nodes
2807     SMDS_ElemIteratorPtr elems = srcNode->GetInverseElementIterator(SMDSAbs_Face);
2808     while ( elems->more() )
2809     {
2810       const SMDS_MeshElement* elem = elems->next();
2811       if ( elem->getshapeId() == srcFaceID )
2812       {
2813         for ( int i = 0, nb = elem->NbNodes(); i < nb; ++i )
2814         {
2815           const SMDS_MeshNode* n = elem->GetNode( i );
2816           if ( !n->isMarked() )
2817             noTriQueue.push_back( make_pair( n, bmTria ));
2818         }
2819       }
2820     }
2821   }
2822
2823   //================================================================================
2824   /*!
2825    * \brief Find a delauney triangle containing a given 2D point and return
2826    *        barycentric coordinates within the found triangle
2827    */
2828   //================================================================================
2829
2830   const BRepMesh_Triangle* findTriangle( const gp_XY&                            uv,
2831                                          const BRepMesh_Triangle*                bmTria,
2832                                          Handle(BRepMesh_DataStructureOfDelaun)& triaDS,
2833                                          double                                  bc[3] )
2834   {
2835     int   nodeIDs[3];
2836     gp_XY nodeUVs[3];
2837     int   linkIDs[3];
2838     Standard_Boolean ori[3];
2839
2840     while ( bmTria )
2841     {
2842       // check bmTria
2843
2844       triaDS->ElementNodes( *bmTria, nodeIDs );
2845       nodeUVs[0] = triaDS->GetNode( nodeIDs[0] ).Coord();
2846       nodeUVs[1] = triaDS->GetNode( nodeIDs[1] ).Coord();
2847       nodeUVs[2] = triaDS->GetNode( nodeIDs[2] ).Coord();
2848
2849       SMESH_MeshAlgos::GetBarycentricCoords( uv,
2850                                              nodeUVs[0], nodeUVs[1], nodeUVs[2],
2851                                              bc[0], bc[1] );
2852       if ( bc[0] >= 0 && bc[1] >= 0 && bc[0] + bc[1] <= 1 )
2853       {
2854         bc[2] = 1 - bc[0] - bc[1];
2855         return bmTria;
2856       }
2857
2858       // look for a neighbor triangle, which is adjacent to a link intersected
2859       // by a segment( triangle center -> uv )
2860
2861       gp_XY gc = ( nodeUVs[0] + nodeUVs[1] + nodeUVs[2] ) / 3.;
2862       gp_XY seg = uv - gc;
2863
2864       bmTria->Edges( linkIDs, ori );
2865       int triaID = triaDS->IndexOf( *bmTria );
2866       bmTria = 0;
2867
2868       for ( int i = 0; i < 3; ++i )
2869       {
2870         const BRepMesh_PairOfIndex & triIDs = triaDS->ElementsConnectedTo( linkIDs[i] );
2871         if ( triIDs.Extent() < 2 )
2872           continue; // no neighbor triangle
2873
2874         // check if a link intersects gc2uv
2875         const BRepMesh_Edge & link = triaDS->GetLink( linkIDs[i] );
2876         const BRepMesh_Vertex & n1 = triaDS->GetNode( link.FirstNode() );
2877         const BRepMesh_Vertex & n2 = triaDS->GetNode( link.LastNode() );
2878         gp_XY uv1 = n1.Coord();
2879         gp_XY lin = n2.Coord() - uv1; // link direction
2880
2881         double crossSegLin = seg ^ lin;
2882         if ( Abs( crossSegLin ) < std::numeric_limits<double>::min() )
2883           continue; // parallel
2884
2885         double uSeg = ( uv1 - gc ) ^ lin / crossSegLin;
2886         if ( 0. <= uSeg && uSeg <= 1. )
2887         {
2888           bmTria = & triaDS->GetElement( triIDs.Index( 1 + ( triIDs.Index(1) == triaID )));
2889           break;
2890         }
2891       }
2892     }
2893     return bmTria;
2894   }
2895
2896   //================================================================================
2897   /*!
2898    * \brief triangulate the srcFace in 2D
2899    *  \param [in] srcWires - boundary of the src FACE
2900    */
2901   //================================================================================
2902
2903   Morph::Morph(const TSideVector& srcWires)
2904   {
2905     _srcSubMesh = srcWires[0]->GetMesh()->GetSubMesh( srcWires[0]->Face() );
2906
2907     // compute _scale
2908     {
2909       BRepAdaptor_Surface surf( srcWires[0]->Face() );
2910       const int nbDiv = 100;
2911       const double uRange = surf.LastUParameter() - surf.FirstUParameter();
2912       const double vRange = surf.LastVParameter() - surf.FirstVParameter();
2913       const double dU = uRange / nbDiv;
2914       const double dV = vRange / nbDiv;
2915       double u = surf.FirstUParameter(), v = surf.FirstVParameter();
2916       gp_Pnt p0U = surf.Value( u, v ), p0V = p0U;
2917       double lenU = 0, lenV = 0;
2918       for ( ; u < surf.LastUParameter(); u += dU, v += dV )
2919       {
2920         gp_Pnt p1U = surf.Value( u, surf.FirstVParameter() );
2921         lenU += p1U.Distance( p0U );
2922         p0U = p1U;
2923         gp_Pnt p1V = surf.Value( surf.FirstUParameter(), v );
2924         lenV += p1V.Distance( p0V );
2925         p0V = p1V;
2926       }
2927       _scale.SetCoord( lenU / uRange, lenV / vRange );
2928     }
2929
2930     // count boundary points
2931     int iP = 1, nbP = 0;
2932     for ( size_t iW = 0; iW < srcWires.size(); ++iW )
2933       nbP += srcWires[iW]->NbPoints() - 1; // 1st and last points coincide
2934
2935     _bndSrcNodes.resize( nbP + 1 ); _bndSrcNodes[0] = 0;
2936
2937     // fill boundary points
2938     BRepMesh::Array1OfVertexOfDelaun srcVert( 1, 1 + nbP );
2939     BRepMesh_Vertex v( 0, 0, BRepMesh_Frontier );
2940     for ( size_t iW = 0; iW < srcWires.size(); ++iW )
2941     {
2942       const UVPtStructVec& srcPnt = srcWires[iW]->GetUVPtStruct();
2943       for ( int i = 0, nb = srcPnt.size() - 1;  i < nb;  ++i, ++iP )
2944       {
2945         _bndSrcNodes[ iP ]  = srcPnt[i].node;
2946         srcPnt[i].node->setIsMarked( true );
2947
2948         v.ChangeCoord() = srcPnt[i].UV().Multiplied( _scale );
2949         srcVert( iP )   = v;
2950       }
2951     }
2952     // triangulate the srcFace in 2D
2953     BRepMesh_Delaun delauney( srcVert );
2954     _triaDS = delauney.Result();
2955   }
2956
2957   //================================================================================
2958   /*!
2959    * \brief Move non-marked target nodes
2960    *  \param [in,out] tgtHelper - helper
2961    *  \param [in] tgtWires - boundary nodes of the target FACE; must be in the
2962    *         same order as the nodes in srcWires given in the constructor
2963    *  \param [in] src2tgtNodes - map of src -> tgt nodes
2964    *  \param [in] moveAll - to move all nodes; if \c false, move only non-marked nodes
2965    *  \return bool - Ok or not
2966    */
2967   //================================================================================
2968
2969   bool Morph::Perform(SMESH_MesherHelper&           tgtHelper,
2970                       const TSideVector&            tgtWires,
2971                       Handle(ShapeAnalysis_Surface) tgtSurface,
2972                       const TNodeNodeMap&           src2tgtNodes,
2973                       const bool                    moveAll)
2974   {
2975     // get tgt boundary points corresponding to _bndSrcNodes
2976     size_t nbP = 0;
2977     for ( size_t iW = 0; iW < tgtWires.size(); ++iW )
2978       nbP += tgtWires[iW]->NbPoints() - 1; // 1st and last points coincide
2979     if ( nbP != _bndSrcNodes.size() - 1 )
2980       return false;
2981
2982     BRepMesh::Array1OfVertexOfDelaun tgtVert( 1, 1 + nbP );
2983     BRepMesh_Vertex v( 0, 0, BRepMesh_Frontier );
2984     for ( size_t iW = 0, iP = 1; iW < tgtWires.size(); ++iW )
2985     {
2986       const UVPtStructVec& tgtPnt = tgtWires[iW]->GetUVPtStruct();
2987       for ( int i = 0, nb = tgtPnt.size() - 1;  i < nb;  ++i, ++iP )
2988       {
2989         v.ChangeCoord() = tgtPnt[i].UV().Multiplied( _scale );
2990         tgtVert( iP )   = v;
2991       }
2992     }
2993
2994     const TopoDS_Face& srcFace = TopoDS::Face( _srcSubMesh->GetSubShape() );
2995     const int        srcFaceID = _srcSubMesh->GetId();
2996     SMESHDS_Mesh* tgtMesh = tgtHelper.GetMeshDS();
2997     const SMDS_MeshNode *srcNode, *tgtNode;
2998     const BRepMesh_Triangle *bmTria;
2999
3000     // initialize a queue of nodes with starting triangles
3001     TNodeTriaList noTriQueue;
3002     size_t iBndSrcN = 1;
3003     for ( ; iBndSrcN < _bndSrcNodes.size() &&  noTriQueue.empty();  ++iBndSrcN )
3004     {
3005       // get a triangle
3006       const BRepMesh::ListOfInteger & linkIds = _triaDS->LinksConnectedTo( iBndSrcN );
3007       const BRepMesh_PairOfIndex &    triaIds = _triaDS->ElementsConnectedTo( linkIds.First() );
3008       const BRepMesh_Triangle&           tria = _triaDS->GetElement( triaIds.Index(1) );
3009
3010       addCloseNodes( _bndSrcNodes[ iBndSrcN ], &tria, srcFaceID, noTriQueue );
3011     }
3012
3013     // un-mark internal src nodes; later we will mark moved nodes
3014     int nbSrcNodes = 0;
3015     SMDS_NodeIteratorPtr nIt = _srcSubMesh->GetSubMeshDS()->GetNodes();
3016     if ( !nIt || !nIt->more() ) return true;
3017     if ( moveAll )
3018     {
3019       nbSrcNodes = _srcSubMesh->GetSubMeshDS()->NbNodes();
3020       while ( nIt->more() )
3021         nIt->next()->setIsMarked( false );
3022     }
3023     else
3024     {
3025       while ( nIt->more() )
3026         nbSrcNodes += int( !nIt->next()->isMarked() );
3027     }
3028
3029     // Move tgt nodes
3030
3031     double bc[3]; // barycentric coordinates
3032     int    nodeIDs[3];
3033     bool   checkUV = true;
3034     const SMDS_FacePosition* pos;
3035
3036     while ( nbSrcNodes > 0 )
3037     {
3038       while ( !noTriQueue.empty() )
3039       {
3040         srcNode = noTriQueue.front().first;
3041         bmTria  = noTriQueue.front().second;
3042         noTriQueue.pop_front();
3043         if ( srcNode->isMarked() )
3044           continue;
3045         --nbSrcNodes;
3046         srcNode->setIsMarked( true );
3047
3048         // find a delauney triangle containing the src node
3049         gp_XY uv = tgtHelper.GetNodeUV( srcFace, srcNode, NULL, &checkUV );
3050         uv *= _scale;
3051         bmTria = findTriangle( uv, bmTria, _triaDS, bc );
3052         if ( !bmTria )
3053           continue;
3054
3055         // compute new coordinates for a corresponding tgt node
3056         gp_XY uvNew( 0., 0. ), nodeUV;
3057         _triaDS->ElementNodes( *bmTria, nodeIDs );
3058         for ( int i = 0; i < 3; ++i )
3059           uvNew += bc[i] * tgtVert( nodeIDs[i]).Coord();
3060         uvNew.SetCoord( uvNew.X() / _scale.X(), uvNew.Y() / _scale.Y() );
3061         gp_Pnt xyz = tgtSurface->Value( uvNew );
3062
3063         // find and move tgt node
3064         TNodeNodeMap::const_iterator n2n = src2tgtNodes.find( srcNode );
3065         if ( n2n == src2tgtNodes.end() ) continue;
3066         tgtNode = n2n->second;
3067         tgtMesh->MoveNode( tgtNode, xyz.X(), xyz.Y(), xyz.Z() );
3068
3069         if (( pos = dynamic_cast< const SMDS_FacePosition* >( tgtNode->GetPosition() )))
3070           const_cast<SMDS_FacePosition*>( pos )->SetParameters( uvNew.X(), uvNew.Y() );
3071
3072         addCloseNodes( srcNode, bmTria, srcFaceID, noTriQueue );
3073       }
3074
3075       if ( nbSrcNodes > 0 )
3076       {
3077         // assure that all src nodes are visited
3078         for ( ; iBndSrcN < _bndSrcNodes.size() &&  noTriQueue.empty();  ++iBndSrcN )
3079         {
3080           const BRepMesh::ListOfInteger & linkIds = _triaDS->LinksConnectedTo( iBndSrcN );
3081           const BRepMesh_PairOfIndex &    triaIds = _triaDS->ElementsConnectedTo( linkIds.First() );
3082           const BRepMesh_Triangle&           tria = _triaDS->GetElement( triaIds.Index(1) );
3083           addCloseNodes( _bndSrcNodes[ iBndSrcN ], &tria, srcFaceID, noTriQueue );
3084         }
3085         if ( noTriQueue.empty() )
3086         {
3087           SMDS_NodeIteratorPtr nIt = _srcSubMesh->GetSubMeshDS()->GetNodes();
3088           while ( nIt->more() )
3089           {
3090             srcNode = nIt->next();
3091             if ( !srcNode->isMarked() )
3092               noTriQueue.push_back( make_pair( srcNode, bmTria ));
3093           }
3094         }
3095       }
3096     }
3097
3098     return true;
3099
3100   } // Morph::Perform
3101
3102 gp_XY Morph::GetBndUV(const int iNode) const
3103 {
3104     return _triaDS->GetNode( iNode ).Coord();
3105   }
3106
3107
3108 } // namespace StdMeshers_ProjectionUtils