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