Salome HOME
a bit more comments
[modules/smesh.git] / src / SMESH / SMESH_MesherHelper.cxx
1 // Copyright (C) 2007-2012  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.
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 // File:      SMESH_MesherHelper.cxx
24 // Created:   15.02.06 15:22:41
25 // Author:    Sergey KUUL
26 //
27 #include "SMESH_MesherHelper.hxx"
28
29 #include "SMDS_EdgePosition.hxx"
30 #include "SMDS_FaceOfNodes.hxx"
31 #include "SMDS_FacePosition.hxx" 
32 #include "SMDS_IteratorOnIterators.hxx"
33 #include "SMDS_VolumeTool.hxx"
34 #include "SMESH_Block.hxx"
35 #include "SMESH_ProxyMesh.hxx"
36 #include "SMESH_subMesh.hxx"
37
38 #include <BRepAdaptor_Curve.hxx>
39 #include <BRepAdaptor_Surface.hxx>
40 #include <BRepTools.hxx>
41 #include <BRep_Tool.hxx>
42 #include <Geom2d_Curve.hxx>
43 #include <GeomAPI_ProjectPointOnCurve.hxx>
44 #include <GeomAPI_ProjectPointOnSurf.hxx>
45 #include <Geom_Curve.hxx>
46 #include <Geom_RectangularTrimmedSurface.hxx>
47 #include <Geom_Surface.hxx>
48 #include <ShapeAnalysis.hxx>
49 #include <TopExp.hxx>
50 #include <TopExp_Explorer.hxx>
51 #include <TopTools_ListIteratorOfListOfShape.hxx>
52 #include <TopTools_MapIteratorOfMapOfShape.hxx>
53 #include <TopTools_MapOfShape.hxx>
54 #include <TopoDS.hxx>
55 #include <gp_Ax3.hxx>
56 #include <gp_Pnt2d.hxx>
57 #include <gp_Trsf.hxx>
58
59 #include <Standard_Failure.hxx>
60 #include <Standard_ErrorHandler.hxx>
61
62 #include <utilities.h>
63
64 #include <limits>
65
66 using namespace std;
67
68 #define RETURN_BAD_RESULT(msg) { MESSAGE(msg); return false; }
69
70 namespace {
71
72   gp_XYZ XYZ(const SMDS_MeshNode* n) { return gp_XYZ(n->X(), n->Y(), n->Z()); }
73
74   enum { U_periodic = 1, V_periodic = 2 };
75 }
76
77 //================================================================================
78 /*!
79  * \brief Constructor
80  */
81 //================================================================================
82
83 SMESH_MesherHelper::SMESH_MesherHelper(SMESH_Mesh& theMesh)
84   : myParIndex(0), myMesh(&theMesh), myShapeID(0), myCreateQuadratic(false),
85     myFixNodeParameters(false)
86 {
87   myPar1[0] = myPar2[0] = myPar1[1] = myPar2[1] = 0;
88   mySetElemOnShape = ( ! myMesh->HasShapeToMesh() );
89 }
90
91 //=======================================================================
92 //function : ~SMESH_MesherHelper
93 //purpose  : 
94 //=======================================================================
95
96 SMESH_MesherHelper::~SMESH_MesherHelper()
97 {
98   {
99     TID2ProjectorOnSurf::iterator i_proj = myFace2Projector.begin();
100     for ( ; i_proj != myFace2Projector.end(); ++i_proj )
101       delete i_proj->second;
102   }
103   {
104     TID2ProjectorOnCurve::iterator i_proj = myEdge2Projector.begin();
105     for ( ; i_proj != myEdge2Projector.end(); ++i_proj )
106       delete i_proj->second;
107   }
108 }
109
110 //=======================================================================
111 //function : IsQuadraticSubMesh
112 //purpose  : Check submesh for given shape: if all elements on this shape 
113 //           are quadratic, quadratic elements will be created.
114 //           Also fill myTLinkNodeMap
115 //=======================================================================
116
117 bool SMESH_MesherHelper::IsQuadraticSubMesh(const TopoDS_Shape& aSh)
118 {
119   SMESHDS_Mesh* meshDS = GetMeshDS();
120   // we can create quadratic elements only if all elements
121   // created on sub-shapes of given shape are quadratic
122   // also we have to fill myTLinkNodeMap
123   myCreateQuadratic = true;
124   mySeamShapeIds.clear();
125   myDegenShapeIds.clear();
126   TopAbs_ShapeEnum subType( aSh.ShapeType()==TopAbs_FACE ? TopAbs_EDGE : TopAbs_FACE );
127   if ( aSh.ShapeType()==TopAbs_COMPOUND )
128   {
129     TopoDS_Iterator subIt( aSh );
130     if ( subIt.More() )
131       subType = ( subIt.Value().ShapeType()==TopAbs_FACE ) ? TopAbs_EDGE : TopAbs_FACE;
132   }
133   SMDSAbs_ElementType elemType( subType==TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
134
135
136   int nbOldLinks = myTLinkNodeMap.size();
137
138   if ( !myMesh->HasShapeToMesh() )
139   {
140     if (( myCreateQuadratic = myMesh->NbFaces( ORDER_QUADRATIC )))
141     {
142       SMDS_FaceIteratorPtr fIt = meshDS->facesIterator();
143       while ( fIt->more() )
144         AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
145     }
146   }
147   else
148   {
149     TopExp_Explorer exp( aSh, subType );
150     TopTools_MapOfShape checkedSubShapes;
151     for (; exp.More() && myCreateQuadratic; exp.Next()) {
152       if ( !checkedSubShapes.Add( exp.Current() ))
153         continue; // needed if aSh is compound of solids
154       if ( SMESHDS_SubMesh * subMesh = meshDS->MeshElements( exp.Current() )) {
155         if ( SMDS_ElemIteratorPtr it = subMesh->GetElements() ) {
156           while(it->more()) {
157             const SMDS_MeshElement* e = it->next();
158             if ( e->GetType() != elemType || !e->IsQuadratic() ) {
159               myCreateQuadratic = false;
160               break;
161             }
162             else {
163               // fill TLinkNodeMap
164               switch ( e->NbNodes() ) {
165               case 3:
166                 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(2)); break;
167               case 6:
168                 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(3));
169                 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(4));
170                 AddTLinkNode(e->GetNode(2),e->GetNode(0),e->GetNode(5)); break;
171               case 8:
172                 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(4));
173                 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(5));
174                 AddTLinkNode(e->GetNode(2),e->GetNode(3),e->GetNode(6));
175                 AddTLinkNode(e->GetNode(3),e->GetNode(0),e->GetNode(7));
176                 break;
177               default:
178                 myCreateQuadratic = false;
179                 break;
180               }
181             }
182           }
183         }
184       }
185     }
186   }
187
188   if ( nbOldLinks == myTLinkNodeMap.size() )
189     myCreateQuadratic = false;
190
191   if(!myCreateQuadratic) {
192     myTLinkNodeMap.clear();
193   }
194   SetSubShape( aSh );
195
196   return myCreateQuadratic;
197 }
198
199 //=======================================================================
200 //function : SetSubShape
201 //purpose  : Set geometry to make elements on
202 //=======================================================================
203
204 void SMESH_MesherHelper::SetSubShape(const int aShID)
205 {
206   if ( aShID == myShapeID )
207     return;
208   if ( aShID > 0 )
209     SetSubShape( GetMeshDS()->IndexToShape( aShID ));
210   else
211     SetSubShape( TopoDS_Shape() );
212 }
213
214 //=======================================================================
215 //function : SetSubShape
216 //purpose  : Set geometry to create elements on
217 //=======================================================================
218
219 void SMESH_MesherHelper::SetSubShape(const TopoDS_Shape& aSh)
220 {
221   if ( myShape.IsSame( aSh ))
222     return;
223
224   myShape = aSh;
225   mySeamShapeIds.clear();
226   myDegenShapeIds.clear();
227
228   if ( myShape.IsNull() ) {
229     myShapeID  = 0;
230     return;
231   }
232   SMESHDS_Mesh* meshDS = GetMeshDS();
233   myShapeID = meshDS->ShapeToIndex(aSh);
234   myParIndex = 0;
235
236   // treatment of periodic faces
237   for ( TopExp_Explorer eF( aSh, TopAbs_FACE ); eF.More(); eF.Next() )
238   {
239     const TopoDS_Face& face = TopoDS::Face( eF.Current() );
240     TopLoc_Location loc;
241     Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
242
243     if ( surface->IsUPeriodic() || surface->IsVPeriodic() ||
244          surface->IsUClosed()   || surface->IsVClosed() )
245     {
246       //while ( surface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface )))
247       //surface = Handle(Geom_RectangularTrimmedSurface)::DownCast( surface )->BasisSurface();
248       GeomAdaptor_Surface surf( surface );
249
250       for (TopExp_Explorer exp( face, TopAbs_EDGE ); exp.More(); exp.Next())
251       {
252         // look for a seam edge
253         const TopoDS_Edge& edge = TopoDS::Edge( exp.Current() );
254         if ( BRep_Tool::IsClosed( edge, face )) {
255           // initialize myPar1, myPar2 and myParIndex
256           gp_Pnt2d uv1, uv2;
257           BRep_Tool::UVPoints( edge, face, uv1, uv2 );
258           if ( Abs( uv1.Coord(1) - uv2.Coord(1) ) < Abs( uv1.Coord(2) - uv2.Coord(2) ))
259           {
260             myParIndex |= U_periodic;
261             myPar1[0] = surf.FirstUParameter();
262             myPar2[0] = surf.LastUParameter();
263           }
264           else {
265             myParIndex |= V_periodic;
266             myPar1[1] = surf.FirstVParameter();
267             myPar2[1] = surf.LastVParameter();
268           }
269           // store seam shape indices, negative if shape encounters twice
270           int edgeID = meshDS->ShapeToIndex( edge );
271           mySeamShapeIds.insert( IsSeamShape( edgeID ) ? -edgeID : edgeID );
272           for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() ) {
273             int vertexID = meshDS->ShapeToIndex( v.Current() );
274             mySeamShapeIds.insert( IsSeamShape( vertexID ) ? -vertexID : vertexID );
275           }
276         }
277
278         // look for a degenerated edge
279         if ( BRep_Tool::Degenerated( edge )) {
280           myDegenShapeIds.insert( meshDS->ShapeToIndex( edge ));
281           for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() )
282             myDegenShapeIds.insert( meshDS->ShapeToIndex( v.Current() ));
283         }
284       }
285       if ( !myDegenShapeIds.empty() && !myParIndex ) {
286         if ( surface->IsUPeriodic() || surface->IsUClosed() ) {
287           myParIndex |= U_periodic;
288           myPar1[0] = surf.FirstUParameter();
289           myPar2[0] = surf.LastUParameter();
290         }
291         else if ( surface->IsVPeriodic() || surface->IsVClosed() ) {
292           myParIndex |= V_periodic;
293           myPar1[1] = surf.FirstVParameter();
294           myPar2[1] = surf.LastVParameter();
295         }
296       }
297     }
298   }
299 }
300
301 //=======================================================================
302 //function : GetNodeUVneedInFaceNode
303 //purpose  : Check if inFaceNode argument is necessary for call GetNodeUV(F,..)
304 //           Return true if the face is periodic.
305 //           If F is Null, answer about sub-shape set through IsQuadraticSubMesh() or
306 //           * SetSubShape()
307 //=======================================================================
308
309 bool SMESH_MesherHelper::GetNodeUVneedInFaceNode(const TopoDS_Face& F) const
310 {
311   if ( F.IsNull() ) return !mySeamShapeIds.empty();
312
313   if ( !F.IsNull() && !myShape.IsNull() && myShape.IsSame( F ))
314     return !mySeamShapeIds.empty();
315
316   TopLoc_Location loc;
317   Handle(Geom_Surface) aSurface = BRep_Tool::Surface( F,loc );
318   if ( !aSurface.IsNull() )
319     return ( aSurface->IsUPeriodic() || aSurface->IsVPeriodic() );
320
321   return false;
322 }
323
324 //=======================================================================
325 //function : IsMedium
326 //purpose  : 
327 //=======================================================================
328
329 bool SMESH_MesherHelper::IsMedium(const SMDS_MeshNode*      node,
330                                   const SMDSAbs_ElementType typeToCheck)
331 {
332   return SMESH_MeshEditor::IsMedium( node, typeToCheck );
333 }
334
335 //=======================================================================
336 //function : GetSubShapeByNode
337 //purpose  : Return support shape of a node
338 //=======================================================================
339
340 TopoDS_Shape SMESH_MesherHelper::GetSubShapeByNode(const SMDS_MeshNode* node,
341                                                    const SMESHDS_Mesh*  meshDS)
342 {
343   int shapeID = node ? node->getshapeId() : 0;
344   if ( 0 < shapeID && shapeID <= meshDS->MaxShapeIndex() )
345     return meshDS->IndexToShape( shapeID );
346   else
347     return TopoDS_Shape();
348 }
349
350
351 //=======================================================================
352 //function : AddTLinkNode
353 //purpose  : add a link in my data structure
354 //=======================================================================
355
356 void SMESH_MesherHelper::AddTLinkNode(const SMDS_MeshNode* n1,
357                                       const SMDS_MeshNode* n2,
358                                       const SMDS_MeshNode* n12)
359 {
360   // add new record to map
361   SMESH_TLink link( n1, n2 );
362   myTLinkNodeMap.insert( make_pair(link,n12));
363 }
364
365 //================================================================================
366 /*!
367  * \brief Add quadratic links of edge to own data structure
368  */
369 //================================================================================
370
371 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshEdge* edge)
372 {
373   if ( edge->IsQuadratic() )
374     AddTLinkNode(edge->GetNode(0), edge->GetNode(1), edge->GetNode(2));
375 }
376
377 //================================================================================
378 /*!
379  * \brief Add quadratic links of face to own data structure
380  */
381 //================================================================================
382
383 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshFace* f)
384 {
385   if ( !f->IsPoly() )
386     switch ( f->NbNodes() ) {
387     case 6:
388       AddTLinkNode(f->GetNode(0),f->GetNode(1),f->GetNode(3));
389       AddTLinkNode(f->GetNode(1),f->GetNode(2),f->GetNode(4));
390       AddTLinkNode(f->GetNode(2),f->GetNode(0),f->GetNode(5)); break;
391     case 8:
392       AddTLinkNode(f->GetNode(0),f->GetNode(1),f->GetNode(4));
393       AddTLinkNode(f->GetNode(1),f->GetNode(2),f->GetNode(5));
394       AddTLinkNode(f->GetNode(2),f->GetNode(3),f->GetNode(6));
395       AddTLinkNode(f->GetNode(3),f->GetNode(0),f->GetNode(7));
396     default:;
397     }
398 }
399
400 //================================================================================
401 /*!
402  * \brief Add quadratic links of volume to own data structure
403  */
404 //================================================================================
405
406 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshVolume* volume)
407 {
408   if ( volume->IsQuadratic() )
409   {
410     SMDS_VolumeTool vTool( volume );
411     const SMDS_MeshNode** nodes = vTool.GetNodes();
412     set<int> addedLinks;
413     for ( int iF = 1; iF < vTool.NbFaces(); ++iF )
414     {
415       const int nbN = vTool.NbFaceNodes( iF );
416       const int* iNodes = vTool.GetFaceNodesIndices( iF );
417       for ( int i = 0; i < nbN; )
418       {
419         int iN1  = iNodes[i++];
420         int iN12 = iNodes[i++];
421         int iN2  = iNodes[i];
422         if ( iN1 > iN2 ) std::swap( iN1, iN2 );
423         int linkID = iN1 * vTool.NbNodes() + iN2;
424         pair< set<int>::iterator, bool > it_isNew = addedLinks.insert( linkID );
425         if ( it_isNew.second )
426           AddTLinkNode( nodes[iN1], nodes[iN2], nodes[iN12] );
427         else
428           addedLinks.erase( it_isNew.first ); // each link encounters only twice
429       }
430     }
431   }
432 }
433
434 //================================================================================
435 /*!
436  * \brief Return true if position of nodes on the shape hasn't yet been checked or
437  * the positions proved to be invalid
438  */
439 //================================================================================
440
441 bool SMESH_MesherHelper::toCheckPosOnShape(int shapeID ) const
442 {
443   map< int,bool >::const_iterator id_ok = myNodePosShapesValidity.find( shapeID );
444   return ( id_ok == myNodePosShapesValidity.end() || !id_ok->second );
445 }
446
447 //================================================================================
448 /*!
449  * \brief Set validity of positions of nodes on the shape.
450  * Once set, validity is not changed
451  */
452 //================================================================================
453
454 void SMESH_MesherHelper::setPosOnShapeValidity(int shapeID, bool ok ) const
455 {
456   ((SMESH_MesherHelper*)this)->myNodePosShapesValidity.insert( make_pair( shapeID, ok));
457 }
458
459 //=======================================================================
460 //function : ToFixNodeParameters
461 //purpose  : Enables fixing node parameters on EDGEs and FACEs in 
462 //           GetNodeU(...,check=true), GetNodeUV(...,check=true), CheckNodeUV() and
463 //           CheckNodeU() in case if a node lies on a shape set via SetSubShape().
464 //           Default is False
465 //=======================================================================
466
467 void SMESH_MesherHelper::ToFixNodeParameters(bool toFix)
468 {
469   myFixNodeParameters = toFix;
470 }
471
472
473 //=======================================================================
474 //function : GetUVOnSeam
475 //purpose  : Select UV on either of 2 pcurves of a seam edge, closest to the given UV
476 //=======================================================================
477
478 gp_Pnt2d SMESH_MesherHelper::GetUVOnSeam( const gp_Pnt2d& uv1, const gp_Pnt2d& uv2 ) const
479 {
480   gp_Pnt2d result = uv1;
481   for ( int i = U_periodic; i <= V_periodic ; ++i )
482   {
483     if ( myParIndex & i )
484     {
485       double p1 = uv1.Coord( i );
486       double dp1 = Abs( p1-myPar1[i-1]), dp2 = Abs( p1-myPar2[i-1]);
487       if ( myParIndex == i ||
488            dp1 < ( myPar2[i-1] - myPar2[i-1] ) / 100. ||
489            dp2 < ( myPar2[i-1] - myPar2[i-1] ) / 100. )
490       {
491         double p2 = uv2.Coord( i );
492         double p1Alt = ( dp1 < dp2 ) ? myPar2[i-1] : myPar1[i-1];
493         if ( Abs( p2 - p1 ) > Abs( p2 - p1Alt ))
494           result.SetCoord( i, p1Alt );
495       }
496     }
497   }
498   return result;
499 }
500
501 //=======================================================================
502 //function : GetNodeUV
503 //purpose  : Return node UV on face
504 //=======================================================================
505
506 gp_XY SMESH_MesherHelper::GetNodeUV(const TopoDS_Face&   F,
507                                     const SMDS_MeshNode* n,
508                                     const SMDS_MeshNode* n2,
509                                     bool*                check) const
510 {
511   gp_Pnt2d uv( Precision::Infinite(), Precision::Infinite() );
512   const SMDS_PositionPtr Pos = n->GetPosition();
513   bool uvOK = false;
514   if(Pos->GetTypeOfPosition()==SMDS_TOP_FACE)
515   {
516     // node has position on face
517     const SMDS_FacePosition* fpos =
518       static_cast<const SMDS_FacePosition*>(n->GetPosition());
519     uv.SetCoord(fpos->GetUParameter(),fpos->GetVParameter());
520     if ( check )
521       uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ));
522   }
523   else if(Pos->GetTypeOfPosition()==SMDS_TOP_EDGE)
524   {
525     // node has position on edge => it is needed to find
526     // corresponding edge from face, get pcurve for this
527     // edge and retrieve value from this pcurve
528     const SMDS_EdgePosition* epos =
529       static_cast<const SMDS_EdgePosition*>(n->GetPosition());
530     int edgeID = n->getshapeId();
531     TopoDS_Edge E = TopoDS::Edge(GetMeshDS()->IndexToShape(edgeID));
532     double f, l, u = epos->GetUParameter();
533     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, F, f, l);
534     bool validU = ( f < u && u < l );
535     if ( validU )
536       uv = C2d->Value( u );
537     else
538       uv.SetCoord( Precision::Infinite(),0.);
539     if ( check || !validU )
540       uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ),/*force=*/ !validU );
541
542     // for a node on a seam edge select one of UVs on 2 pcurves
543     if ( n2 && IsSeamShape( edgeID ) )
544     {
545       uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0, check ));
546     }
547     else
548     { // adjust uv to period
549       TopLoc_Location loc;
550       Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
551       Standard_Boolean isUPeriodic = S->IsUPeriodic();
552       Standard_Boolean isVPeriodic = S->IsVPeriodic();
553       if ( isUPeriodic || isVPeriodic ) {
554         Standard_Real UF,UL,VF,VL;
555         S->Bounds(UF,UL,VF,VL);
556         if(isUPeriodic)
557           uv.SetX( uv.X() + ShapeAnalysis::AdjustToPeriod(uv.X(),UF,UL));
558         if(isVPeriodic)
559           uv.SetY( uv.Y() + ShapeAnalysis::AdjustToPeriod(uv.Y(),VF,VL));
560       }
561     }
562   }
563   else if(Pos->GetTypeOfPosition()==SMDS_TOP_VERTEX)
564   {
565     if ( int vertexID = n->getshapeId() ) {
566       const TopoDS_Vertex& V = TopoDS::Vertex(GetMeshDS()->IndexToShape(vertexID));
567       try {
568         uv = BRep_Tool::Parameters( V, F );
569         uvOK = true;
570       }
571       catch (Standard_Failure& exc) {
572       }
573       if ( !uvOK ) {
574         for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() )
575           uvOK = ( V == vert.Current() );
576         if ( !uvOK ) {
577 #ifdef _DEBUG_
578           MESSAGE ( "SMESH_MesherHelper::GetNodeUV(); Vertex " << vertexID
579                << " not in face " << GetMeshDS()->ShapeToIndex( F ) );
580 #endif
581           // get UV of a vertex closest to the node
582           double dist = 1e100;
583           gp_Pnt pn = XYZ( n );
584           for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() ) {
585             TopoDS_Vertex curV = TopoDS::Vertex( vert.Current() );
586             gp_Pnt p = BRep_Tool::Pnt( curV );
587             double curDist = p.SquareDistance( pn );
588             if ( curDist < dist ) {
589               dist = curDist;
590               uv = BRep_Tool::Parameters( curV, F );
591               uvOK = ( dist < DBL_MIN );
592             }
593           }
594         }
595         else {
596           uvOK = false;
597           TopTools_ListIteratorOfListOfShape it( myMesh->GetAncestors( V ));
598           for ( ; it.More(); it.Next() ) {
599             if ( it.Value().ShapeType() == TopAbs_EDGE ) {
600               const TopoDS_Edge & edge = TopoDS::Edge( it.Value() );
601               double f,l;
602               Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(edge, F, f, l);
603               if ( !C2d.IsNull() ) {
604                 double u = ( V == TopExp::FirstVertex( edge ) ) ?  f : l;
605                 uv = C2d->Value( u );
606                 uvOK = true;
607                 break;
608               }
609             }
610           }
611         }
612       }
613       if ( n2 && IsSeamShape( vertexID ) )
614         uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
615     }
616   }
617   else
618   {
619     uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ));
620   }
621
622   if ( check )
623     *check = uvOK;
624
625   return uv.XY();
626 }
627
628 //=======================================================================
629 //function : CheckNodeUV
630 //purpose  : Check and fix node UV on a face
631 //=======================================================================
632
633 bool SMESH_MesherHelper::CheckNodeUV(const TopoDS_Face&   F,
634                                      const SMDS_MeshNode* n,
635                                      gp_XY&               uv,
636                                      const double         tol,
637                                      const bool           force,
638                                      double               distXYZ[4]) const
639 {
640   int shapeID = n->getshapeId();
641   bool infinit = ( Precision::IsInfinite( uv.X() ) || Precision::IsInfinite( uv.Y() ));
642   if ( force || toCheckPosOnShape( shapeID ) || infinit )
643   {
644     // check that uv is correct
645     TopLoc_Location loc;
646     Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
647     gp_Pnt nodePnt = XYZ( n ), surfPnt(0,0,0);
648     double dist = 0;
649     if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
650     if ( infinit ||
651          (dist = nodePnt.Distance( surfPnt = surface->Value( uv.X(), uv.Y() ))) > tol )
652     {
653       setPosOnShapeValidity( shapeID, false );
654       if ( !infinit && distXYZ ) {
655         surfPnt.Transform( loc );
656         distXYZ[0] = dist;
657         distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
658       }
659       // uv incorrect, project the node to surface
660       GeomAPI_ProjectPointOnSurf& projector = GetProjector( F, loc, tol );
661       projector.Perform( nodePnt );
662       if ( !projector.IsDone() || projector.NbPoints() < 1 )
663       {
664         MESSAGE( "SMESH_MesherHelper::CheckNodeUV() failed to project" );
665         return false;
666       }
667       Quantity_Parameter U,V;
668       projector.LowerDistanceParameters(U,V);
669       uv.SetCoord( U,V );
670       surfPnt = surface->Value( U, V );
671       dist = nodePnt.Distance( surfPnt );
672       if ( distXYZ ) {
673         surfPnt.Transform( loc );
674         distXYZ[0] = dist;
675         distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
676       }
677       if ( dist > tol )
678       {
679         MESSAGE( "SMESH_MesherHelper::CheckNodeUV(), invalid projection" );
680         return false;
681       }
682       // store the fixed UV on the face
683       if ( myShape.IsSame(F) && shapeID == myShapeID && myFixNodeParameters )
684         const_cast<SMDS_MeshNode*>(n)->SetPosition
685           ( SMDS_PositionPtr( new SMDS_FacePosition( U, V )));
686     }
687     else if ( uv.Modulus() > numeric_limits<double>::min() )
688     {
689       setPosOnShapeValidity( shapeID, true );
690     }
691   }
692   return true;
693 }
694
695 //=======================================================================
696 //function : GetProjector
697 //purpose  : Return projector intitialized by given face without location, which is returned
698 //=======================================================================
699
700 GeomAPI_ProjectPointOnSurf& SMESH_MesherHelper::GetProjector(const TopoDS_Face& F,
701                                                              TopLoc_Location&   loc,
702                                                              double             tol ) const
703 {
704   Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
705   int faceID = GetMeshDS()->ShapeToIndex( F );
706   TID2ProjectorOnSurf& i2proj = const_cast< TID2ProjectorOnSurf&>( myFace2Projector );
707   TID2ProjectorOnSurf::iterator i_proj = i2proj.find( faceID );
708   if ( i_proj == i2proj.end() )
709   {
710     if ( tol == 0 ) tol = BRep_Tool::Tolerance( F );
711     double U1, U2, V1, V2;
712     surface->Bounds(U1, U2, V1, V2);
713     GeomAPI_ProjectPointOnSurf* proj = new GeomAPI_ProjectPointOnSurf();
714     proj->Init( surface, U1, U2, V1, V2, tol );
715     i_proj = i2proj.insert( make_pair( faceID, proj )).first;
716   }
717   return *( i_proj->second );
718 }
719
720 namespace
721 {
722   gp_XY AverageUV(const gp_XY& uv1, const gp_XY& uv2) { return ( uv1 + uv2 ) / 2.; }
723   gp_XY_FunPtr(Added); // define gp_XY_Added pointer to function calling gp_XY::Added(gp_XY)
724   gp_XY_FunPtr(Subtracted); 
725 }
726
727 //=======================================================================
728 //function : applyIn2D
729 //purpose  : Perform given operation on two 2d points in parameric space of given surface.
730 //           It takes into account period of the surface. Use gp_XY_FunPtr macro
731 //           to easily define pointer to function of gp_XY class.
732 //=======================================================================
733
734 gp_XY SMESH_MesherHelper::applyIn2D(const Handle(Geom_Surface)& surface,
735                                     const gp_XY&                uv1,
736                                     const gp_XY&                uv2,
737                                     xyFunPtr                    fun,
738                                     const bool                  resultInPeriod)
739 {
740   Standard_Boolean isUPeriodic = surface.IsNull() ? false : surface->IsUPeriodic();
741   Standard_Boolean isVPeriodic = surface.IsNull() ? false : surface->IsVPeriodic();
742   if ( !isUPeriodic && !isVPeriodic )
743     return fun(uv1,uv2);
744
745   // move uv2 not far than half-period from uv1
746   double u2 = 
747     uv2.X()+(isUPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.X(),uv1.X(),surface->UPeriod()) :0);
748   double v2 = 
749     uv2.Y()+(isVPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.Y(),uv1.Y(),surface->VPeriod()) :0);
750
751   // execute operation
752   gp_XY res = fun( uv1, gp_XY(u2,v2) );
753
754   // move result within period
755   if ( resultInPeriod )
756   {
757     Standard_Real UF,UL,VF,VL;
758     surface->Bounds(UF,UL,VF,VL);
759     if ( isUPeriodic )
760       res.SetX( res.X() + ShapeAnalysis::AdjustToPeriod(res.X(),UF,UL));
761     if ( isVPeriodic )
762       res.SetY( res.Y() + ShapeAnalysis::AdjustToPeriod(res.Y(),VF,VL));
763   }
764
765   return res;
766 }
767 //=======================================================================
768 //function : GetMiddleUV
769 //purpose  : Return middle UV taking in account surface period
770 //=======================================================================
771
772 gp_XY SMESH_MesherHelper::GetMiddleUV(const Handle(Geom_Surface)& surface,
773                                       const gp_XY&                p1,
774                                       const gp_XY&                p2)
775 {
776   // NOTE:
777   // the proper place of getting basic surface seems to be in applyIn2D()
778   // but we put it here to decrease a risk of regressions just before releasing a version
779   Handle(Geom_Surface) surf = surface;
780   while ( !surf.IsNull() && surf->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface )))
781     surf = Handle(Geom_RectangularTrimmedSurface)::DownCast( surf )->BasisSurface();
782
783   return applyIn2D( surf, p1, p2, & AverageUV );
784 }
785
786 //=======================================================================
787 //function : GetNodeU
788 //purpose  : Return node U on edge
789 //=======================================================================
790
791 double SMESH_MesherHelper::GetNodeU(const TopoDS_Edge&   E,
792                                     const SMDS_MeshNode* n,
793                                     const SMDS_MeshNode* inEdgeNode,
794                                     bool*                check)
795 {
796   double param = 0;
797   const SMDS_PositionPtr pos = n->GetPosition();
798   if ( pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
799   {
800     const SMDS_EdgePosition* epos = static_cast<const SMDS_EdgePosition*>( pos );
801     param =  epos->GetUParameter();
802   }
803   else if( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX )
804   {
805     if ( inEdgeNode && TopExp::FirstVertex( E ).IsSame( TopExp::LastVertex( E ))) // issue 0020128
806     {
807       Standard_Real f,l;
808       BRep_Tool::Range( E, f,l );
809       double uInEdge = GetNodeU( E, inEdgeNode );
810       param = ( fabs( uInEdge - f ) < fabs( l - uInEdge )) ? f : l;
811     }
812     else
813     {
814       SMESHDS_Mesh * meshDS = GetMeshDS();
815       int vertexID = n->getshapeId();
816       const TopoDS_Vertex& V = TopoDS::Vertex(meshDS->IndexToShape(vertexID));
817       param =  BRep_Tool::Parameter( V, E );
818     }
819   }
820   if ( check )
821   {
822     double tol = BRep_Tool::Tolerance( E );
823     double f,l;  BRep_Tool::Range( E, f,l );
824     bool force = ( param < f-tol || param > l+tol );
825     if ( !force && pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
826       force = ( GetMeshDS()->ShapeToIndex( E ) != n->getshapeId() );
827
828     *check = CheckNodeU( E, n, param, 2*tol, force );
829   }
830   return param;
831 }
832
833 //=======================================================================
834 //function : CheckNodeU
835 //purpose  : Check and fix node U on an edge
836 //           Return false if U is bad and could not be fixed
837 //=======================================================================
838
839 bool SMESH_MesherHelper::CheckNodeU(const TopoDS_Edge&   E,
840                                     const SMDS_MeshNode* n,
841                                     double&              u,
842                                     const double         tol,
843                                     const bool           force,
844                                     double               distXYZ[4]) const
845 {
846   int shapeID = n->getshapeId();
847   if ( force || toCheckPosOnShape( shapeID ))
848   {
849     TopLoc_Location loc; double f,l;
850     Handle(Geom_Curve) curve = BRep_Tool::Curve( E,loc,f,l );
851     if ( curve.IsNull() ) // degenerated edge
852     {
853       if ( u+tol < f || u-tol > l )
854       {
855         double r = Max( 0.5, 1 - tol*n->GetID()); // to get a unique u on edge
856         u =  f*r + l*(1-r);
857       }
858     }
859     else
860     {
861       gp_Pnt nodePnt = SMESH_TNodeXYZ( n );
862       if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
863       gp_Pnt curvPnt = curve->Value( u );
864       double dist = nodePnt.Distance( curvPnt );
865       if ( distXYZ ) {
866         curvPnt.Transform( loc );
867         distXYZ[0] = dist;
868         distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
869       }
870       if ( dist > tol )
871       {
872         setPosOnShapeValidity( shapeID, false );
873         // u incorrect, project the node to the curve
874         int edgeID = GetMeshDS()->ShapeToIndex( E );
875         TID2ProjectorOnCurve& i2proj = const_cast< TID2ProjectorOnCurve&>( myEdge2Projector );
876         TID2ProjectorOnCurve::iterator i_proj =
877           i2proj.insert( make_pair( edgeID, (GeomAPI_ProjectPointOnCurve*) 0 )).first;
878         if ( !i_proj->second  )
879         {
880           i_proj->second = new GeomAPI_ProjectPointOnCurve();
881           i_proj->second->Init( curve, f, l );
882         }
883         GeomAPI_ProjectPointOnCurve* projector = i_proj->second;
884         projector->Perform( nodePnt );
885         if ( projector->NbPoints() < 1 )
886         {
887           MESSAGE( "SMESH_MesherHelper::CheckNodeU() failed to project" );
888           return false;
889         }
890         Quantity_Parameter U = projector->LowerDistanceParameter();
891         u = double( U );
892         curvPnt = curve->Value( u );
893         dist = nodePnt.Distance( curvPnt );
894         if ( distXYZ ) {
895           curvPnt.Transform( loc );
896           distXYZ[0] = dist;
897           distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
898         }
899         if ( dist > tol )
900         {
901           MESSAGE( "SMESH_MesherHelper::CheckNodeU(), invalid projection" );
902           MESSAGE("distance " << dist << " " << tol );
903           return false;
904         }
905         // store the fixed U on the edge
906         if ( myShape.IsSame(E) && shapeID == myShapeID && myFixNodeParameters )
907           const_cast<SMDS_MeshNode*>(n)->SetPosition
908             ( SMDS_PositionPtr( new SMDS_EdgePosition( U )));
909       }
910       else if ( fabs( u ) > numeric_limits<double>::min() )
911       {
912         setPosOnShapeValidity( shapeID, true );
913       }
914       if (( u < f-tol || u > l+tol ) && force )
915       {
916         // node is on vertex but is set on periodic but trimmed edge (issue 0020890)
917         try
918         {
919           // do not use IsPeriodic() as Geom_TrimmedCurve::IsPeriodic () returns false
920           double period = curve->Period();
921           u = ( u < f ) ? u + period : u - period;
922         }
923         catch (Standard_Failure& exc)
924         {
925           return false;
926         }
927       }
928     }
929   }
930   return true;
931 }
932
933 //=======================================================================
934 //function : GetMediumPos
935 //purpose  : Return index and type of the shape  (EDGE or FACE only) to
936 //          set a medium node on
937 //param    : useCurSubShape - if true, returns the shape set via SetSubShape()
938 //           if any
939 //=======================================================================
940
941 std::pair<int, TopAbs_ShapeEnum>
942 SMESH_MesherHelper::GetMediumPos(const SMDS_MeshNode* n1,
943                                  const SMDS_MeshNode* n2,
944                                  const bool           useCurSubShape)
945 {
946   if ( useCurSubShape && !myShape.IsNull() )
947     return std::make_pair( myShapeID, myShape.ShapeType() );
948
949   TopAbs_ShapeEnum shapeType = TopAbs_SHAPE;
950   int              shapeID = -1;
951   TopoDS_Shape     shape;
952
953   if (( myShapeID == n1->getshapeId() || myShapeID == n2->getshapeId() ) && myShapeID > 0 )
954   {
955     shapeType = myShape.ShapeType();
956     shapeID   = myShapeID;
957   }
958   else if ( n1->getshapeId() == n2->getshapeId() )
959   {
960     shapeID = n2->getshapeId();
961     shape = GetSubShapeByNode( n1, GetMeshDS() );
962   }
963   else
964   {
965     const SMDS_TypeOfPosition Pos1 = n1->GetPosition()->GetTypeOfPosition();
966     const SMDS_TypeOfPosition Pos2 = n2->GetPosition()->GetTypeOfPosition();
967
968     if ( Pos1 == SMDS_TOP_3DSPACE || Pos2 == SMDS_TOP_3DSPACE )
969     {
970     }
971     else if ( Pos1 == SMDS_TOP_FACE || Pos2 == SMDS_TOP_FACE )
972     {
973       if ( Pos1 != SMDS_TOP_FACE || Pos2 != SMDS_TOP_FACE )
974       {
975         if ( Pos1 != SMDS_TOP_FACE ) std::swap( n1,n2 );
976         TopoDS_Shape F = GetSubShapeByNode( n1, GetMeshDS() );
977         TopoDS_Shape S = GetSubShapeByNode( n2, GetMeshDS() );
978         if ( IsSubShape( S, F ))
979         {
980           shapeType = TopAbs_FACE;
981           shapeID   = n1->getshapeId();
982         }
983       }
984     }
985     else if ( Pos1 == SMDS_TOP_EDGE && Pos2 == SMDS_TOP_EDGE )
986     {
987       TopoDS_Shape E1 = GetSubShapeByNode( n1, GetMeshDS() );
988       TopoDS_Shape E2 = GetSubShapeByNode( n2, GetMeshDS() );
989       shape = GetCommonAncestor( E1, E2, *myMesh, TopAbs_FACE );
990     }
991     else if ( Pos1 == SMDS_TOP_VERTEX && Pos2 == SMDS_TOP_VERTEX )
992     {
993       TopoDS_Shape V1 = GetSubShapeByNode( n1, GetMeshDS() );
994       TopoDS_Shape V2 = GetSubShapeByNode( n2, GetMeshDS() );
995       shape = GetCommonAncestor( V1, V2, *myMesh, TopAbs_EDGE );
996       if ( shape.IsNull() ) shape = GetCommonAncestor( V1, V2, *myMesh, TopAbs_FACE );
997     }
998     else // VERTEX and EDGE
999     {
1000       if ( Pos1 != SMDS_TOP_VERTEX ) std::swap( n1,n2 );
1001       TopoDS_Shape V = GetSubShapeByNode( n1, GetMeshDS() );
1002       TopoDS_Shape E = GetSubShapeByNode( n2, GetMeshDS() );
1003       if ( IsSubShape( V, E ))
1004         shape = E;
1005       else
1006         shape = GetCommonAncestor( V, E, *myMesh, TopAbs_FACE );
1007     }
1008   }
1009
1010   if ( !shape.IsNull() )
1011   {
1012     if ( shapeID < 1 )
1013       shapeID = GetMeshDS()->ShapeToIndex( shape );
1014     shapeType = shape.ShapeType();
1015   }
1016   return make_pair( shapeID, shapeType );
1017 }
1018
1019 //=======================================================================
1020 //function : GetMediumNode
1021 //purpose  : Return existing or create new medium nodes between given ones
1022 //=======================================================================
1023
1024 const SMDS_MeshNode* SMESH_MesherHelper::GetMediumNode(const SMDS_MeshNode* n1,
1025                                                        const SMDS_MeshNode* n2,
1026                                                        bool                 force3d)
1027 {
1028   // Find existing node
1029
1030   SMESH_TLink link(n1,n2);
1031   ItTLinkNode itLN = myTLinkNodeMap.find( link );
1032   if ( itLN != myTLinkNodeMap.end() ) {
1033     return (*itLN).second;
1034   }
1035
1036   // Create medium node
1037
1038   SMDS_MeshNode* n12;
1039   SMESHDS_Mesh* meshDS = GetMeshDS();
1040
1041   if ( IsSeamShape( n1->getshapeId() ))
1042     // to get a correct UV of a node on seam, the second node must have checked UV
1043     std::swap( n1, n2 );
1044
1045   // get type of shape for the new medium node
1046   int faceID = -1, edgeID = -1;
1047   TopoDS_Edge E; double u [2];
1048   TopoDS_Face F; gp_XY  uv[2];
1049   bool uvOK[2] = { false, false };
1050
1051   pair<int, TopAbs_ShapeEnum> pos = GetMediumPos( n1, n2, mySetElemOnShape );
1052
1053   // get positions of the given nodes on shapes
1054   if ( pos.second == TopAbs_FACE )
1055   {
1056     F = TopoDS::Face(meshDS->IndexToShape( faceID = pos.first ));
1057     uv[0] = GetNodeUV(F,n1,n2, force3d ? 0 : &uvOK[0]);
1058     uv[1] = GetNodeUV(F,n2,n1, force3d ? 0 : &uvOK[1]);
1059   }
1060   else if ( pos.second == TopAbs_EDGE )
1061   {
1062     const SMDS_PositionPtr Pos1 = n1->GetPosition();
1063     const SMDS_PositionPtr Pos2 = n2->GetPosition();
1064     if ( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE &&
1065          Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE &&
1066          n1->getshapeId() != n2->getshapeId() )
1067     {
1068       // issue 0021006
1069       return getMediumNodeOnComposedWire(n1,n2,force3d);
1070     }
1071     E = TopoDS::Edge(meshDS->IndexToShape( edgeID = pos.first ));
1072     u[0] = GetNodeU(E,n1,n2, force3d ? 0 : &uvOK[0]);
1073     u[1] = GetNodeU(E,n2,n1, force3d ? 0 : &uvOK[1]);
1074   }
1075
1076   if ( !force3d & uvOK[0] && uvOK[1] )
1077   {
1078     // we try to create medium node using UV parameters of
1079     // nodes, else - medium between corresponding 3d points
1080     if( ! F.IsNull() )
1081     {
1082       //if ( uvOK[0] && uvOK[1] )
1083       {
1084         if ( IsDegenShape( n1->getshapeId() )) {
1085           if ( myParIndex & U_periodic ) uv[0].SetCoord( 1, uv[1].Coord( 1 ));
1086           else                           uv[0].SetCoord( 2, uv[1].Coord( 2 ));
1087         }
1088         else if ( IsDegenShape( n2->getshapeId() )) {
1089           if ( myParIndex & U_periodic ) uv[1].SetCoord( 1, uv[0].Coord( 1 ));
1090           else                           uv[1].SetCoord( 2, uv[0].Coord( 2 ));
1091         }
1092
1093         TopLoc_Location loc;
1094         Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
1095         gp_XY UV = GetMiddleUV( S, uv[0], uv[1] );
1096         gp_Pnt P = S->Value( UV.X(), UV.Y() ).Transformed(loc);
1097         n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
1098         meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y());
1099         myTLinkNodeMap.insert(make_pair(link,n12));
1100         return n12;
1101       }
1102     }
1103     else if ( !E.IsNull() )
1104     {
1105       double f,l;
1106       Handle(Geom_Curve) C = BRep_Tool::Curve(E, f, l);
1107       if(!C.IsNull())
1108       {
1109         Standard_Boolean isPeriodic = C->IsPeriodic();
1110         double U;
1111         if(isPeriodic) {
1112           Standard_Real Period = C->Period();
1113           Standard_Real p = u[1]+ShapeAnalysis::AdjustByPeriod(u[1],u[0],Period);
1114           Standard_Real pmid = (u[0]+p)/2.;
1115           U = pmid+ShapeAnalysis::AdjustToPeriod(pmid,C->FirstParameter(),C->LastParameter());
1116         }
1117         else
1118           U = (u[0]+u[1])/2.;
1119
1120         gp_Pnt P = C->Value( U );
1121         n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
1122         meshDS->SetNodeOnEdge(n12, edgeID, U);
1123         myTLinkNodeMap.insert(make_pair(link,n12));
1124         return n12;
1125       }
1126     }
1127   }
1128
1129   // 3d variant
1130   double x = ( n1->X() + n2->X() )/2.;
1131   double y = ( n1->Y() + n2->Y() )/2.;
1132   double z = ( n1->Z() + n2->Z() )/2.;
1133   n12 = meshDS->AddNode(x,y,z);
1134
1135   if ( !F.IsNull() )
1136   {
1137     gp_XY UV = ( uv[0] + uv[1] ) / 2.;
1138     CheckNodeUV( F, n12, UV, 2*BRep_Tool::Tolerance( F ), /*force=*/true);
1139     meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y() );
1140   }
1141   else if ( !E.IsNull() )
1142   {
1143     double U = ( u[0] + u[1] ) / 2.;
1144     CheckNodeU( E, n12, U, 2*BRep_Tool::Tolerance( E ), /*force=*/true);
1145     meshDS->SetNodeOnEdge(n12, edgeID, U);
1146   }
1147   else if ( myShapeID > 0 )
1148   {
1149     meshDS->SetNodeInVolume(n12, myShapeID);
1150   }
1151
1152   myTLinkNodeMap.insert( make_pair( link, n12 ));
1153   return n12;
1154 }
1155
1156 //================================================================================
1157 /*!
1158  * \brief Makes a medium node if nodes reside different edges
1159  */
1160 //================================================================================
1161
1162 const SMDS_MeshNode* SMESH_MesherHelper::getMediumNodeOnComposedWire(const SMDS_MeshNode* n1,
1163                                                                      const SMDS_MeshNode* n2,
1164                                                                      bool                 force3d)
1165 {
1166   gp_Pnt middle = 0.5 * XYZ(n1) + 0.5 * XYZ(n2);
1167   SMDS_MeshNode* n12 = AddNode( middle.X(), middle.Y(), middle.Z() );
1168
1169   // To find position on edge and 3D position for n12,
1170   // project <middle> to 2 edges and select projection most close to <middle>
1171
1172   double u = 0, distMiddleProj = Precision::Infinite(), distXYZ[4];
1173   int iOkEdge = 0;
1174   TopoDS_Edge edges[2];
1175   for ( int is2nd = 0; is2nd < 2; ++is2nd )
1176   {
1177     // get an edge
1178     const SMDS_MeshNode* n = is2nd ? n2 : n1;
1179     TopoDS_Shape shape = GetSubShapeByNode( n, GetMeshDS() );
1180     if ( shape.IsNull() || shape.ShapeType() != TopAbs_EDGE )
1181       continue;
1182
1183     // project to get U of projection and distance from middle to projection
1184     TopoDS_Edge edge = edges[ is2nd ] = TopoDS::Edge( shape );
1185     double node2MiddleDist = middle.Distance( XYZ(n) );
1186     double foundU = GetNodeU( edge, n );
1187     CheckNodeU( edge, n12, foundU, 2*BRep_Tool::Tolerance(edge), /*force=*/true, distXYZ );
1188     if ( distXYZ[0] < node2MiddleDist )
1189     {
1190       distMiddleProj = distXYZ[0];
1191       u = foundU;
1192       iOkEdge = is2nd;
1193     }
1194   }
1195   if ( Precision::IsInfinite( distMiddleProj ))
1196   {
1197     // both projections failed; set n12 on the edge of n1 with U of a common vertex
1198     TopoDS_Vertex vCommon;
1199     if ( TopExp::CommonVertex( edges[0], edges[1], vCommon ))
1200       u = BRep_Tool::Parameter( vCommon, edges[0] );
1201     else
1202     {
1203       double f,l, u0 = GetNodeU( edges[0], n1 );
1204       BRep_Tool::Range( edges[0],f,l );
1205       u = ( fabs(u0-f) < fabs(u0-l) ) ? f : l;
1206     }
1207     iOkEdge = 0;
1208     distMiddleProj = 0;
1209   }
1210
1211   // move n12 to position of a successfull projection
1212   double tol = BRep_Tool::Tolerance(edges[ iOkEdge ]);
1213   if ( !force3d && distMiddleProj > 2*tol )
1214   {
1215     TopLoc_Location loc; double f,l;
1216     Handle(Geom_Curve) curve = BRep_Tool::Curve( edges[iOkEdge],loc,f,l );
1217     gp_Pnt p = curve->Value( u );
1218     GetMeshDS()->MoveNode( n12, p.X(), p.Y(), p.Z() );
1219   }
1220
1221   GetMeshDS()->SetNodeOnEdge(n12, edges[iOkEdge], u);
1222
1223   myTLinkNodeMap.insert( make_pair( SMESH_TLink(n1,n2), n12 ));
1224
1225   return n12;
1226 }
1227
1228 //=======================================================================
1229 //function : AddNode
1230 //purpose  : Creates a node
1231 //=======================================================================
1232
1233 SMDS_MeshNode* SMESH_MesherHelper::AddNode(double x, double y, double z, int ID,
1234                                            double u, double v)
1235 {
1236   SMESHDS_Mesh * meshDS = GetMeshDS();
1237   SMDS_MeshNode* node = 0;
1238   if ( ID )
1239     node = meshDS->AddNodeWithID( x, y, z, ID );
1240   else
1241     node = meshDS->AddNode( x, y, z );
1242   if ( mySetElemOnShape && myShapeID > 0 ) {
1243     switch ( myShape.ShapeType() ) {
1244     case TopAbs_SOLID:  meshDS->SetNodeInVolume( node, myShapeID);       break;
1245     case TopAbs_SHELL:  meshDS->SetNodeInVolume( node, myShapeID);       break;
1246     case TopAbs_FACE:   meshDS->SetNodeOnFace(   node, myShapeID, u, v); break;
1247     case TopAbs_EDGE:   meshDS->SetNodeOnEdge(   node, myShapeID, u);    break;
1248     case TopAbs_VERTEX: meshDS->SetNodeOnVertex( node, myShapeID);       break;
1249     default: ;
1250     }
1251   }
1252   return node;
1253 }
1254
1255 //=======================================================================
1256 //function : AddEdge
1257 //purpose  : Creates quadratic or linear edge
1258 //=======================================================================
1259
1260 SMDS_MeshEdge* SMESH_MesherHelper::AddEdge(const SMDS_MeshNode* n1,
1261                                            const SMDS_MeshNode* n2,
1262                                            const int            id,
1263                                            const bool           force3d)
1264 {
1265   SMESHDS_Mesh * meshDS = GetMeshDS();
1266   
1267   SMDS_MeshEdge* edge = 0;
1268   if (myCreateQuadratic) {
1269     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1270     if(id)
1271       edge = meshDS->AddEdgeWithID(n1, n2, n12, id);
1272     else
1273       edge = meshDS->AddEdge(n1, n2, n12);
1274   }
1275   else {
1276     if(id)
1277       edge = meshDS->AddEdgeWithID(n1, n2, id);
1278     else
1279       edge = meshDS->AddEdge(n1, n2);
1280   }
1281
1282   if ( mySetElemOnShape && myShapeID > 0 )
1283     meshDS->SetMeshElementOnShape( edge, myShapeID );
1284
1285   return edge;
1286 }
1287
1288 //=======================================================================
1289 //function : AddFace
1290 //purpose  : Creates quadratic or linear triangle
1291 //=======================================================================
1292
1293 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1294                                            const SMDS_MeshNode* n2,
1295                                            const SMDS_MeshNode* n3,
1296                                            const int id,
1297                                            const bool force3d)
1298 {
1299   SMESHDS_Mesh * meshDS = GetMeshDS();
1300   SMDS_MeshFace* elem = 0;
1301
1302   if( n1==n2 || n2==n3 || n3==n1 )
1303     return elem;
1304
1305   if(!myCreateQuadratic) {
1306     if(id)
1307       elem = meshDS->AddFaceWithID(n1, n2, n3, id);
1308     else
1309       elem = meshDS->AddFace(n1, n2, n3);
1310   }
1311   else {
1312     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1313     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1314     const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1315
1316     if(id)
1317       elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, id);
1318     else
1319       elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31);
1320   }
1321   if ( mySetElemOnShape && myShapeID > 0 )
1322     meshDS->SetMeshElementOnShape( elem, myShapeID );
1323
1324   return elem;
1325 }
1326
1327 //=======================================================================
1328 //function : AddFace
1329 //purpose  : Creates quadratic or linear quadrangle
1330 //=======================================================================
1331
1332 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1333                                            const SMDS_MeshNode* n2,
1334                                            const SMDS_MeshNode* n3,
1335                                            const SMDS_MeshNode* n4,
1336                                            const int            id,
1337                                            const bool           force3d)
1338 {
1339   SMESHDS_Mesh * meshDS = GetMeshDS();
1340   SMDS_MeshFace* elem = 0;
1341
1342   if( n1==n2 ) {
1343     return AddFace(n1,n3,n4,id,force3d);
1344   }
1345   if( n1==n3 ) {
1346     return AddFace(n1,n2,n4,id,force3d);
1347   }
1348   if( n1==n4 ) {
1349     return AddFace(n1,n2,n3,id,force3d);
1350   }
1351   if( n2==n3 ) {
1352     return AddFace(n1,n2,n4,id,force3d);
1353   }
1354   if( n2==n4 ) {
1355     return AddFace(n1,n2,n3,id,force3d);
1356   }
1357   if( n3==n4 ) {
1358     return AddFace(n1,n2,n3,id,force3d);
1359   }
1360
1361   if(!myCreateQuadratic) {
1362     if(id)
1363       elem = meshDS->AddFaceWithID(n1, n2, n3, n4, id);
1364     else
1365       elem = meshDS->AddFace(n1, n2, n3, n4);
1366   }
1367   else {
1368     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1369     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1370     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1371     const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1372
1373     if(id)
1374       elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, id);
1375     else
1376       elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41);
1377   }
1378   if ( mySetElemOnShape && myShapeID > 0 )
1379     meshDS->SetMeshElementOnShape( elem, myShapeID );
1380
1381   return elem;
1382 }
1383
1384 //=======================================================================
1385 //function : AddPolygonalFace
1386 //purpose  : Creates polygon, with additional nodes in quadratic mesh
1387 //=======================================================================
1388
1389 SMDS_MeshFace* SMESH_MesherHelper::AddPolygonalFace (const vector<const SMDS_MeshNode*>& nodes,
1390                                                      const int                           id,
1391                                                      const bool                          force3d)
1392 {
1393   SMESHDS_Mesh * meshDS = GetMeshDS();
1394   SMDS_MeshFace* elem = 0;
1395
1396   if(!myCreateQuadratic) {
1397     if(id)
1398       elem = meshDS->AddPolygonalFaceWithID(nodes, id);
1399     else
1400       elem = meshDS->AddPolygonalFace(nodes);
1401   }
1402   else {
1403     vector<const SMDS_MeshNode*> newNodes;
1404     for ( int i = 0; i < nodes.size(); ++i )
1405     {
1406       const SMDS_MeshNode* n1 = nodes[i];
1407       const SMDS_MeshNode* n2 = nodes[(i+1)%nodes.size()];
1408       const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1409       newNodes.push_back( n1 );
1410       newNodes.push_back( n12 );
1411     }
1412     if(id)
1413       elem = meshDS->AddPolygonalFaceWithID(newNodes, id);
1414     else
1415       elem = meshDS->AddPolygonalFace(newNodes);
1416   }
1417   if ( mySetElemOnShape && myShapeID > 0 )
1418     meshDS->SetMeshElementOnShape( elem, myShapeID );
1419
1420   return elem;
1421 }
1422
1423 //=======================================================================
1424 //function : AddVolume
1425 //purpose  : Creates quadratic or linear prism
1426 //=======================================================================
1427
1428 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1429                                                const SMDS_MeshNode* n2,
1430                                                const SMDS_MeshNode* n3,
1431                                                const SMDS_MeshNode* n4,
1432                                                const SMDS_MeshNode* n5,
1433                                                const SMDS_MeshNode* n6,
1434                                                const int id,
1435                                                const bool force3d)
1436 {
1437   SMESHDS_Mesh * meshDS = GetMeshDS();
1438   SMDS_MeshVolume* elem = 0;
1439   if(!myCreateQuadratic) {
1440     if(id)
1441       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, id);
1442     else
1443       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6);
1444   }
1445   else {
1446     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1447     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1448     const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1449
1450     const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1451     const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1452     const SMDS_MeshNode* n64 = GetMediumNode(n6,n4,force3d);
1453
1454     const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1455     const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1456     const SMDS_MeshNode* n36 = GetMediumNode(n3,n6,force3d);
1457
1458     if(id)
1459       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, 
1460                                      n12, n23, n31, n45, n56, n64, n14, n25, n36, id);
1461     else
1462       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6,
1463                                n12, n23, n31, n45, n56, n64, n14, n25, n36);
1464   }
1465   if ( mySetElemOnShape && myShapeID > 0 )
1466     meshDS->SetMeshElementOnShape( elem, myShapeID );
1467
1468   return elem;
1469 }
1470
1471 //=======================================================================
1472 //function : AddVolume
1473 //purpose  : Creates quadratic or linear tetrahedron
1474 //=======================================================================
1475
1476 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1477                                                const SMDS_MeshNode* n2,
1478                                                const SMDS_MeshNode* n3,
1479                                                const SMDS_MeshNode* n4,
1480                                                const int id, 
1481                                                const bool force3d)
1482 {
1483   SMESHDS_Mesh * meshDS = GetMeshDS();
1484   SMDS_MeshVolume* elem = 0;
1485   if(!myCreateQuadratic) {
1486     if(id)
1487       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, id);
1488     else
1489       elem = meshDS->AddVolume(n1, n2, n3, n4);
1490   }
1491   else {
1492     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1493     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1494     const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1495
1496     const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1497     const SMDS_MeshNode* n24 = GetMediumNode(n2,n4,force3d);
1498     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1499
1500     if(id)
1501       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34, id);
1502     else
1503       elem = meshDS->AddVolume(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34);
1504   }
1505   if ( mySetElemOnShape && myShapeID > 0 )
1506     meshDS->SetMeshElementOnShape( elem, myShapeID );
1507
1508   return elem;
1509 }
1510
1511 //=======================================================================
1512 //function : AddVolume
1513 //purpose  : Creates quadratic or linear pyramid
1514 //=======================================================================
1515
1516 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1517                                                const SMDS_MeshNode* n2,
1518                                                const SMDS_MeshNode* n3,
1519                                                const SMDS_MeshNode* n4,
1520                                                const SMDS_MeshNode* n5,
1521                                                const int id, 
1522                                                const bool force3d)
1523 {
1524   SMDS_MeshVolume* elem = 0;
1525   if(!myCreateQuadratic) {
1526     if(id)
1527       elem = GetMeshDS()->AddVolumeWithID(n1, n2, n3, n4, n5, id);
1528     else
1529       elem = GetMeshDS()->AddVolume(n1, n2, n3, n4, n5);
1530   }
1531   else {
1532     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1533     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1534     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1535     const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1536
1537     const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1538     const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1539     const SMDS_MeshNode* n35 = GetMediumNode(n3,n5,force3d);
1540     const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1541
1542     if(id)
1543       elem = GetMeshDS()->AddVolumeWithID ( n1,  n2,  n3,  n4,  n5,
1544                                             n12, n23, n34, n41,
1545                                             n15, n25, n35, n45,
1546                                             id);
1547     else
1548       elem = GetMeshDS()->AddVolume( n1,  n2,  n3,  n4,  n5,
1549                                      n12, n23, n34, n41,
1550                                      n15, n25, n35, n45);
1551   }
1552   if ( mySetElemOnShape && myShapeID > 0 )
1553     GetMeshDS()->SetMeshElementOnShape( elem, myShapeID );
1554
1555   return elem;
1556 }
1557
1558 //=======================================================================
1559 //function : AddVolume
1560 //purpose  : Creates quadratic or linear hexahedron
1561 //=======================================================================
1562
1563 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1564                                                const SMDS_MeshNode* n2,
1565                                                const SMDS_MeshNode* n3,
1566                                                const SMDS_MeshNode* n4,
1567                                                const SMDS_MeshNode* n5,
1568                                                const SMDS_MeshNode* n6,
1569                                                const SMDS_MeshNode* n7,
1570                                                const SMDS_MeshNode* n8,
1571                                                const int id,
1572                                                const bool force3d)
1573 {
1574   SMESHDS_Mesh * meshDS = GetMeshDS();
1575   SMDS_MeshVolume* elem = 0;
1576   if(!myCreateQuadratic) {
1577     if(id)
1578       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8, id);
1579     else
1580       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8);
1581   }
1582   else {
1583     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1584     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1585     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1586     const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1587
1588     const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1589     const SMDS_MeshNode* n67 = GetMediumNode(n6,n7,force3d);
1590     const SMDS_MeshNode* n78 = GetMediumNode(n7,n8,force3d);
1591     const SMDS_MeshNode* n85 = GetMediumNode(n8,n5,force3d);
1592
1593     const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1594     const SMDS_MeshNode* n26 = GetMediumNode(n2,n6,force3d);
1595     const SMDS_MeshNode* n37 = GetMediumNode(n3,n7,force3d);
1596     const SMDS_MeshNode* n48 = GetMediumNode(n4,n8,force3d);
1597
1598     if(id)
1599       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
1600                                      n12, n23, n34, n41, n56, n67,
1601                                      n78, n85, n15, n26, n37, n48, id);
1602     else
1603       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
1604                                n12, n23, n34, n41, n56, n67,
1605                                n78, n85, n15, n26, n37, n48);
1606   }
1607   if ( mySetElemOnShape && myShapeID > 0 )
1608     meshDS->SetMeshElementOnShape( elem, myShapeID );
1609
1610   return elem;
1611 }
1612
1613 //=======================================================================
1614 //function : AddVolume
1615 //purpose  : Creates LINEAR!!!!!!!!! octahedron
1616 //=======================================================================
1617
1618 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1619                                                const SMDS_MeshNode* n2,
1620                                                const SMDS_MeshNode* n3,
1621                                                const SMDS_MeshNode* n4,
1622                                                const SMDS_MeshNode* n5,
1623                                                const SMDS_MeshNode* n6,
1624                                                const SMDS_MeshNode* n7,
1625                                                const SMDS_MeshNode* n8,
1626                                                const SMDS_MeshNode* n9,
1627                                                const SMDS_MeshNode* n10,
1628                                                const SMDS_MeshNode* n11,
1629                                                const SMDS_MeshNode* n12,
1630                                                const int id, 
1631                                                bool force3d)
1632 {
1633   SMESHDS_Mesh * meshDS = GetMeshDS();
1634   SMDS_MeshVolume* elem = 0;
1635   if(id)
1636     elem = meshDS->AddVolumeWithID(n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,id);
1637   else
1638     elem = meshDS->AddVolume(n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12);
1639   if ( mySetElemOnShape && myShapeID > 0 )
1640     meshDS->SetMeshElementOnShape( elem, myShapeID );
1641   return elem;
1642 }
1643
1644 //=======================================================================
1645 //function : AddPolyhedralVolume
1646 //purpose  : Creates polyhedron. In quadratic mesh, adds medium nodes
1647 //=======================================================================
1648
1649 SMDS_MeshVolume*
1650 SMESH_MesherHelper::AddPolyhedralVolume (const std::vector<const SMDS_MeshNode*>& nodes,
1651                                          const std::vector<int>&                  quantities,
1652                                          const int                                id,
1653                                          const bool                               force3d)
1654 {
1655   SMESHDS_Mesh * meshDS = GetMeshDS();
1656   SMDS_MeshVolume* elem = 0;
1657   if(!myCreateQuadratic)
1658   {
1659     if(id)
1660       elem = meshDS->AddPolyhedralVolumeWithID(nodes, quantities, id);
1661     else
1662       elem = meshDS->AddPolyhedralVolume(nodes, quantities);
1663   }
1664   else
1665   {
1666     vector<const SMDS_MeshNode*> newNodes;
1667     vector<int> newQuantities;
1668     for ( int iFace=0, iN=0; iFace < quantities.size(); ++iFace)
1669     {
1670       int nbNodesInFace = quantities[iFace];
1671       newQuantities.push_back(0);
1672       for ( int i = 0; i < nbNodesInFace; ++i )
1673       {
1674         const SMDS_MeshNode* n1 = nodes[ iN + i ];
1675         newNodes.push_back( n1 );
1676         newQuantities.back()++;
1677         
1678         const SMDS_MeshNode* n2 = nodes[ iN + ( i+1==nbNodesInFace ? 0 : i+1 )];
1679 //         if ( n1->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE &&
1680 //              n2->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE )
1681         {
1682           const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1683           newNodes.push_back( n12 );
1684           newQuantities.back()++;
1685         }
1686       }
1687       iN += nbNodesInFace;
1688     }
1689     if(id)
1690       elem = meshDS->AddPolyhedralVolumeWithID( newNodes, newQuantities, id );
1691     else
1692       elem = meshDS->AddPolyhedralVolume( newNodes, newQuantities );
1693   }
1694   if ( mySetElemOnShape && myShapeID > 0 )
1695     meshDS->SetMeshElementOnShape( elem, myShapeID );
1696
1697   return elem;
1698 }
1699
1700 namespace
1701 {
1702   //================================================================================
1703   /*!
1704    * \brief Check if a node belongs to any face of sub-mesh
1705    */
1706   //================================================================================
1707
1708   bool isNodeInSubMesh( const SMDS_MeshNode* n, const SMESHDS_SubMesh* sm )
1709   {
1710     SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator( SMDSAbs_Face );
1711     while ( fIt->more() )
1712       if ( sm->Contains( fIt->next() ))
1713         return true;
1714     return false;
1715   }
1716 }
1717
1718 //=======================================================================
1719 //function : IsSameElemGeometry
1720 //purpose  : Returns true if all elements of a sub-mesh are of same shape
1721 //=======================================================================
1722
1723 bool SMESH_MesherHelper::IsSameElemGeometry(const SMESHDS_SubMesh* smDS,
1724                                             SMDSAbs_GeometryType   shape,
1725                                             const bool             nullSubMeshRes)
1726 {
1727   if ( !smDS ) return nullSubMeshRes;
1728
1729   SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
1730   while ( elemIt->more() ) {
1731     const SMDS_MeshElement* e = elemIt->next();
1732     if ( e->GetGeomType() != shape )
1733       return false;
1734   }
1735   return true;
1736 }
1737
1738 //=======================================================================
1739 //function : LoadNodeColumns
1740 //purpose  : Load nodes bound to face into a map of node columns
1741 //=======================================================================
1742
1743 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
1744                                          const TopoDS_Face& theFace,
1745                                          const TopoDS_Edge& theBaseEdge,
1746                                          SMESHDS_Mesh*      theMesh,
1747                                          SMESH_ProxyMesh*   theProxyMesh)
1748 {
1749   return LoadNodeColumns(theParam2ColumnMap,
1750                          theFace,
1751                          std::list<TopoDS_Edge>(1,theBaseEdge),
1752                          theMesh,
1753                          theProxyMesh);
1754 }
1755
1756 //=======================================================================
1757 //function : LoadNodeColumns
1758 //purpose  : Load nodes bound to face into a map of node columns
1759 //=======================================================================
1760
1761 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap &            theParam2ColumnMap,
1762                                          const TopoDS_Face&            theFace,
1763                                          const std::list<TopoDS_Edge>& theBaseSide,
1764                                          SMESHDS_Mesh*                 theMesh,
1765                                          SMESH_ProxyMesh*              theProxyMesh)
1766 {
1767   // get a right sub-mesh of theFace
1768
1769   const SMESHDS_SubMesh* faceSubMesh = 0;
1770   if ( theProxyMesh )
1771   {
1772     faceSubMesh = theProxyMesh->GetSubMesh( theFace );
1773     if ( !faceSubMesh ||
1774          faceSubMesh->NbElements() == 0 ||
1775          theProxyMesh->IsTemporary( faceSubMesh->GetElements()->next() ))
1776     {
1777       // can use a proxy sub-mesh with not temporary elements only
1778       faceSubMesh = 0;
1779       theProxyMesh = 0;
1780     }
1781   }
1782   if ( !faceSubMesh )
1783     faceSubMesh = theMesh->MeshElements( theFace );
1784   if ( !faceSubMesh || faceSubMesh->NbElements() == 0 )
1785     return false;
1786
1787   if ( theParam2ColumnMap.empty() )
1788   {
1789     // get data of edges for normalization of params
1790
1791     vector< double > length;
1792     double fullLen = 0;
1793     list<TopoDS_Edge>::const_iterator edge;
1794     {
1795       for ( edge = theBaseSide.begin(); edge != theBaseSide.end(); ++edge )
1796       {
1797         double len = std::max( 1e-10, SMESH_Algo::EdgeLength( *edge ));
1798         fullLen += len;
1799         length.push_back( len );
1800       }
1801     }
1802
1803     // get nodes on theBaseEdge sorted by param on edge and initialize theParam2ColumnMap with them
1804     edge = theBaseSide.begin();
1805     for ( int iE = 0; edge != theBaseSide.end(); ++edge, ++iE )
1806     {
1807       map< double, const SMDS_MeshNode*> sortedBaseNN;
1808       SMESH_Algo::GetSortedNodesOnEdge( theMesh, *edge,/*noMedium=*/true, sortedBaseNN);
1809       if ( sortedBaseNN.empty() ) continue;
1810
1811       map< double, const SMDS_MeshNode*>::iterator u_n = sortedBaseNN.begin();
1812       if ( theProxyMesh ) // from sortedBaseNN remove nodes not shared by faces of faceSubMesh
1813       {
1814         const SMDS_MeshNode* n1 = sortedBaseNN.begin()->second;
1815         const SMDS_MeshNode* n2 = sortedBaseNN.rbegin()->second;
1816         bool allNodesAreProxy = ( n1 != theProxyMesh->GetProxyNode( n1 ) &&
1817                                   n2 != theProxyMesh->GetProxyNode( n2 ));
1818         if ( allNodesAreProxy )
1819           for ( u_n = sortedBaseNN.begin(); u_n != sortedBaseNN.end(); u_n++ )
1820             u_n->second = theProxyMesh->GetProxyNode( u_n->second );
1821
1822         if ( u_n = sortedBaseNN.begin(), !isNodeInSubMesh( u_n->second, faceSubMesh ))
1823         {
1824           while ( ++u_n != sortedBaseNN.end() && !isNodeInSubMesh( u_n->second, faceSubMesh ));
1825           sortedBaseNN.erase( sortedBaseNN.begin(), u_n );
1826         }
1827         else if ( u_n = --sortedBaseNN.end(), !isNodeInSubMesh( u_n->second, faceSubMesh ))
1828         {
1829           while ( u_n != sortedBaseNN.begin() && !isNodeInSubMesh( (--u_n)->second, faceSubMesh ));
1830           sortedBaseNN.erase( ++u_n, sortedBaseNN.end() );
1831         }
1832         if ( sortedBaseNN.empty() ) continue;
1833       }
1834
1835       double f, l;
1836       BRep_Tool::Range( *edge, f, l );
1837       if ( edge->Orientation() == TopAbs_REVERSED ) std::swap( f, l );
1838       const double coeff = 1. / ( l - f ) * length[iE] / fullLen;
1839       const double prevPar = theParam2ColumnMap.empty() ? 0 : theParam2ColumnMap.rbegin()->first;
1840       for ( u_n = sortedBaseNN.begin(); u_n != sortedBaseNN.end(); u_n++ )
1841       {
1842         double par = prevPar + coeff * ( u_n->first - f );
1843         TParam2ColumnMap::iterator u2nn =
1844           theParam2ColumnMap.insert( theParam2ColumnMap.end(), make_pair( par, TNodeColumn()));
1845         u2nn->second.push_back( u_n->second );
1846       }
1847     }
1848     if ( theParam2ColumnMap.empty() )
1849       return false;
1850   }
1851
1852   // nb rows of nodes
1853   int prevNbRows     = theParam2ColumnMap.begin()->second.size(); // current, at least 1 here
1854   int expectedNbRows = faceSubMesh->NbElements() / ( theParam2ColumnMap.size()-1 ); // to be added
1855
1856   // fill theParam2ColumnMap column by column by passing from nodes on
1857   // theBaseEdge up via mesh faces on theFace
1858
1859   TParam2ColumnMap::iterator par_nVec_1, par_nVec_2;
1860   par_nVec_2 = theParam2ColumnMap.begin();
1861   par_nVec_1 = par_nVec_2++;
1862   TIDSortedElemSet emptySet, avoidSet;
1863   for ( ; par_nVec_2 != theParam2ColumnMap.end(); ++par_nVec_1, ++par_nVec_2 )
1864   {
1865     vector<const SMDS_MeshNode*>& nCol1 = par_nVec_1->second;
1866     vector<const SMDS_MeshNode*>& nCol2 = par_nVec_2->second;
1867     nCol1.resize( prevNbRows + expectedNbRows );
1868     nCol2.resize( prevNbRows + expectedNbRows );
1869
1870     int i1, i2, foundNbRows = 0;
1871     const SMDS_MeshNode *n1 = nCol1[ prevNbRows-1 ];
1872     const SMDS_MeshNode *n2 = nCol2[ prevNbRows-1 ];
1873     // find face sharing node n1 and n2 and belonging to faceSubMesh
1874     while ( const SMDS_MeshElement* face =
1875             SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, avoidSet, &i1, &i2))
1876     {
1877       if ( faceSubMesh->Contains( face ))
1878       {
1879         int nbNodes = face->NbCornerNodes();
1880         if ( nbNodes != 4 )
1881           return false;
1882         if ( foundNbRows + 1 > expectedNbRows )
1883           return false;
1884         n1 = face->GetNode( (i2+2) % 4 ); // opposite corner of quadrangle face
1885         n2 = face->GetNode( (i1+2) % 4 );
1886         nCol1[ prevNbRows + foundNbRows] = n1;
1887         nCol2[ prevNbRows + foundNbRows] = n2;
1888         ++foundNbRows;
1889       }
1890       avoidSet.insert( face );
1891     }
1892     if ( foundNbRows != expectedNbRows )
1893       return false;
1894     avoidSet.clear();
1895   }
1896   return ( theParam2ColumnMap.size() > 1 &&
1897            theParam2ColumnMap.begin()->second.size() == prevNbRows + expectedNbRows );
1898 }
1899
1900 namespace
1901 {
1902   //================================================================================
1903   /*!
1904    * \brief Return true if a node is at a corner of a 2D structured mesh of FACE
1905    */
1906   //================================================================================
1907
1908   bool isCornerOfStructure( const SMDS_MeshNode*   n,
1909                             const SMESHDS_SubMesh* faceSM,
1910                             SMESH_MesherHelper&    faceAnalyser )
1911   {
1912     int nbFacesInSM = 0;
1913     if ( n ) {
1914       SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator( SMDSAbs_Face );
1915       while ( fIt->more() )
1916         nbFacesInSM += faceSM->Contains( fIt->next() );
1917     }
1918     if ( nbFacesInSM == 1 )
1919       return true;
1920
1921     if ( nbFacesInSM == 2 && n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
1922     {
1923       return faceAnalyser.IsRealSeam( n->getshapeId() );
1924     }
1925     return false;
1926   }
1927 }
1928
1929 //=======================================================================
1930 //function : IsStructured
1931 //purpose  : Return true if 2D mesh on FACE is structured
1932 //=======================================================================
1933
1934 bool SMESH_MesherHelper::IsStructured( SMESH_subMesh* faceSM )
1935 {
1936   SMESHDS_SubMesh* fSM = faceSM->GetSubMeshDS();
1937   if ( !fSM || fSM->NbElements() == 0 )
1938     return false;
1939
1940   list< TopoDS_Edge > edges;
1941   list< int > nbEdgesInWires;
1942   int nbWires = SMESH_Block::GetOrderedEdges( TopoDS::Face( faceSM->GetSubShape() ),
1943                                               edges, nbEdgesInWires );
1944   if ( nbWires != 1 || nbEdgesInWires.front() != 4 )
1945     return false;
1946
1947   // algo: find corners of a structure and then analyze nb of faces and
1948   // length of structure sides
1949
1950   SMESHDS_Mesh* meshDS = faceSM->GetFather()->GetMeshDS();
1951   SMESH_MesherHelper faceAnalyser( *faceSM->GetFather() );
1952   faceAnalyser.SetSubShape( faceSM->GetSubShape() );
1953
1954   // rotate edges to get the first node being at corner
1955   // (in principle it's not necessary but so far none SALOME algo can make
1956   //  such a structured mesh that all corner nodes are not on VERTEXes)
1957   bool isCorner     = false;
1958   int nbRemainEdges = nbEdgesInWires.front();
1959   do {
1960     TopoDS_Vertex V = IthVertex( 0, edges.front() );
1961     isCorner = isCornerOfStructure( SMESH_Algo::VertexNode( V, meshDS ),
1962                                     fSM, faceAnalyser);
1963     if ( !isCorner ) {
1964       edges.splice( edges.end(), edges, edges.begin() );
1965       --nbRemainEdges;
1966     }
1967   }
1968   while ( !isCorner && nbRemainEdges > 0 );
1969
1970   if ( !isCorner )
1971     return false;
1972
1973   // get all nodes from EDGEs
1974   list< const SMDS_MeshNode* > nodes;
1975   list< TopoDS_Edge >::iterator edge = edges.begin();
1976   for ( ; edge != edges.end(); ++edge )
1977   {
1978     map< double, const SMDS_MeshNode* > u2Nodes;
1979     if ( !SMESH_Algo::GetSortedNodesOnEdge( meshDS, *edge,
1980                                             /*skipMedium=*/true, u2Nodes ))
1981       return false;
1982
1983     list< const SMDS_MeshNode* > edgeNodes;
1984     map< double, const SMDS_MeshNode* >::iterator u2n = u2Nodes.begin();
1985     for ( ; u2n != u2Nodes.end(); ++u2n )
1986       edgeNodes.push_back( u2n->second );
1987     if ( edge->Orientation() == TopAbs_REVERSED )
1988       edgeNodes.reverse();
1989
1990     if ( !nodes.empty() && nodes.back() == edgeNodes.front() )
1991       edgeNodes.pop_front();
1992     nodes.splice( nodes.end(), edgeNodes, edgeNodes.begin(), edgeNodes.end() );
1993   }
1994
1995   // get length of structured sides
1996   vector<int> nbEdgesInSide;
1997   int nbEdges = 0;
1998   list< const SMDS_MeshNode* >::iterator n = ++nodes.begin();
1999   for ( ; n != nodes.end(); ++n )
2000   {
2001     ++nbEdges;
2002     if ( isCornerOfStructure( *n, fSM, faceAnalyser )) {
2003       nbEdgesInSide.push_back( nbEdges );
2004       nbEdges = 0;
2005     }
2006   }
2007
2008   // checks
2009   if ( nbEdgesInSide.size() != 4 )
2010     return false;
2011   if ( nbEdgesInSide[0] != nbEdgesInSide[2] )
2012     return false;
2013   if ( nbEdgesInSide[1] != nbEdgesInSide[3] )
2014     return false;
2015   if ( nbEdgesInSide[0] * nbEdgesInSide[1] != fSM->NbElements() )
2016     return false;
2017
2018   return true;
2019 }
2020
2021 //================================================================================
2022 /*!
2023  * \brief Find out elements orientation on a geometrical face
2024  * \param theFace - The face correctly oriented in the shape being meshed
2025  * \retval bool - true if the face normal and the normal of first element
2026  *                in the correspoding submesh point in different directions
2027  */
2028 //================================================================================
2029
2030 bool SMESH_MesherHelper::IsReversedSubMesh (const TopoDS_Face& theFace)
2031 {
2032   if ( theFace.IsNull() )
2033     return false;
2034
2035   // find out orientation of a meshed face
2036   int faceID = GetMeshDS()->ShapeToIndex( theFace );
2037   TopoDS_Shape aMeshedFace = GetMeshDS()->IndexToShape( faceID );
2038   bool isReversed = ( theFace.Orientation() != aMeshedFace.Orientation() );
2039
2040   const SMESHDS_SubMesh * aSubMeshDSFace = GetMeshDS()->MeshElements( faceID );
2041   if ( !aSubMeshDSFace )
2042     return isReversed;
2043
2044   // find an element with a good normal
2045   gp_Vec Ne;
2046   bool normalOK = false;
2047   gp_XY uv;
2048   SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
2049   while ( !normalOK && iteratorElem->more() ) // loop on elements on theFace
2050   {
2051     const SMDS_MeshElement* elem = iteratorElem->next();
2052     if ( elem && elem->NbCornerNodes() > 2 )
2053     {
2054       SMESH_TNodeXYZ nPnt[3];
2055       SMDS_ElemIteratorPtr nodesIt = elem->nodesIterator();
2056       for ( int iN = 0; nodesIt->more() && iN < 3; ++iN) // loop on nodes
2057         nPnt[ iN ] = nodesIt->next();
2058
2059       // compute normal
2060       gp_Vec v01( nPnt[0], nPnt[1] ), v02( nPnt[0], nPnt[2] );
2061       if ( v01.SquareMagnitude() > RealSmall() &&
2062            v02.SquareMagnitude() > RealSmall() )
2063       {
2064         Ne = v01 ^ v02;
2065         if (( normalOK = ( Ne.SquareMagnitude() > RealSmall() )))
2066           uv = GetNodeUV( theFace, nPnt[0]._node, nPnt[2]._node, &normalOK );
2067       }
2068     }
2069   }
2070   if ( !normalOK )
2071     return isReversed;
2072
2073   // face normal at node position
2074   TopLoc_Location loc;
2075   Handle(Geom_Surface) surf = BRep_Tool::Surface( theFace, loc );
2076   // if ( surf.IsNull() || surf->Continuity() < GeomAbs_C1 )
2077   // some surfaces not detected as GeomAbs_C1 are nevertheless correct for meshing
2078   if ( surf.IsNull() || surf->Continuity() < GeomAbs_C0 )
2079     {
2080       if (!surf.IsNull())
2081         MESSAGE("surf->Continuity() < GeomAbs_C1 " << (surf->Continuity() < GeomAbs_C1));
2082       return isReversed;
2083     }
2084   gp_Vec d1u, d1v; gp_Pnt p;
2085   surf->D1( uv.X(), uv.Y(), p, d1u, d1v );
2086   gp_Vec Nf = (d1u ^ d1v).Transformed( loc );
2087
2088   if ( theFace.Orientation() == TopAbs_REVERSED )
2089     Nf.Reverse();
2090
2091   return Ne * Nf < 0.;
2092 }
2093
2094 //=======================================================================
2095 //function : Count
2096 //purpose  : Count nb of sub-shapes
2097 //=======================================================================
2098
2099 int SMESH_MesherHelper::Count(const TopoDS_Shape&    shape,
2100                               const TopAbs_ShapeEnum type,
2101                               const bool             ignoreSame)
2102 {
2103   if ( ignoreSame ) {
2104     TopTools_IndexedMapOfShape map;
2105     TopExp::MapShapes( shape, type, map );
2106     return map.Extent();
2107   }
2108   else {
2109     int nb = 0;
2110     for ( TopExp_Explorer exp( shape, type ); exp.More(); exp.Next() )
2111       ++nb;
2112     return nb;
2113   }
2114 }
2115
2116 //=======================================================================
2117 //function : NbAncestors
2118 //purpose  : Return number of unique ancestors of the shape
2119 //=======================================================================
2120
2121 int SMESH_MesherHelper::NbAncestors(const TopoDS_Shape& shape,
2122                                     const SMESH_Mesh&   mesh,
2123                                     TopAbs_ShapeEnum    ancestorType/*=TopAbs_SHAPE*/)
2124 {
2125   TopTools_MapOfShape ancestors;
2126   TopTools_ListIteratorOfListOfShape ansIt( mesh.GetAncestors(shape) );
2127   for ( ; ansIt.More(); ansIt.Next() ) {
2128     if ( ancestorType == TopAbs_SHAPE || ansIt.Value().ShapeType() == ancestorType )
2129       ancestors.Add( ansIt.Value() );
2130   }
2131   return ancestors.Extent();
2132 }
2133
2134 //=======================================================================
2135 //function : GetSubShapeOri
2136 //purpose  : Return orientation of sub-shape in the main shape
2137 //=======================================================================
2138
2139 TopAbs_Orientation SMESH_MesherHelper::GetSubShapeOri(const TopoDS_Shape& shape,
2140                                                       const TopoDS_Shape& subShape)
2141 {
2142   TopAbs_Orientation ori = TopAbs_Orientation(-1);
2143   if ( !shape.IsNull() && !subShape.IsNull() )
2144   {
2145     TopExp_Explorer e( shape, subShape.ShapeType() );
2146     if ( shape.Orientation() >= TopAbs_INTERNAL ) // TopAbs_INTERNAL or TopAbs_EXTERNAL
2147       e.Init( shape.Oriented(TopAbs_FORWARD), subShape.ShapeType() );
2148     for ( ; e.More(); e.Next())
2149       if ( subShape.IsSame( e.Current() ))
2150         break;
2151     if ( e.More() )
2152       ori = e.Current().Orientation();
2153   }
2154   return ori;
2155 }
2156
2157 //=======================================================================
2158 //function : IsSubShape
2159 //purpose  : 
2160 //=======================================================================
2161
2162 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape,
2163                                      const TopoDS_Shape& mainShape )
2164 {
2165   if ( !shape.IsNull() && !mainShape.IsNull() )
2166   {
2167     for ( TopExp_Explorer exp( mainShape, shape.ShapeType());
2168           exp.More();
2169           exp.Next() )
2170       if ( shape.IsSame( exp.Current() ))
2171         return true;
2172   }
2173   SCRUTE((shape.IsNull()));
2174   SCRUTE((mainShape.IsNull()));
2175   return false;
2176 }
2177
2178 //=======================================================================
2179 //function : IsSubShape
2180 //purpose  : 
2181 //=======================================================================
2182
2183 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape, SMESH_Mesh* aMesh )
2184 {
2185   if ( shape.IsNull() || !aMesh )
2186     return false;
2187   return
2188     aMesh->GetMeshDS()->ShapeToIndex( shape ) ||
2189     // PAL16202
2190     (shape.ShapeType() == TopAbs_COMPOUND && aMesh->GetMeshDS()->IsGroupOfSubShapes( shape ));
2191 }
2192
2193 //================================================================================
2194 /*!
2195  * \brief Return maximal tolerance of shape
2196  */
2197 //================================================================================
2198
2199 double SMESH_MesherHelper::MaxTolerance( const TopoDS_Shape& shape )
2200 {
2201   double tol = Precision::Confusion();
2202   TopExp_Explorer exp;
2203   for ( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next() )
2204     tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Face( exp.Current())));
2205   for ( exp.Init( shape, TopAbs_EDGE ); exp.More(); exp.Next() )
2206     tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Edge( exp.Current())));
2207   for ( exp.Init( shape, TopAbs_VERTEX ); exp.More(); exp.Next() )
2208     tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Vertex( exp.Current())));
2209
2210   return tol;
2211 }
2212
2213 //================================================================================
2214 /*!
2215  * \brief Check if the first and last vertices of an edge are the same
2216  * \param anEdge - the edge to check
2217  * \retval bool - true if same
2218  */
2219 //================================================================================
2220
2221 bool SMESH_MesherHelper::IsClosedEdge( const TopoDS_Edge& anEdge )
2222 {
2223   if ( anEdge.Orientation() >= TopAbs_INTERNAL )
2224     return IsClosedEdge( TopoDS::Edge( anEdge.Oriented( TopAbs_FORWARD )));
2225   return TopExp::FirstVertex( anEdge ).IsSame( TopExp::LastVertex( anEdge ));
2226 }
2227
2228 //================================================================================
2229 /*!
2230  * \brief Wrapper over TopExp::FirstVertex() and TopExp::LastVertex() fixing them
2231  *  in the case of INTERNAL edge
2232  */
2233 //================================================================================
2234
2235 TopoDS_Vertex SMESH_MesherHelper::IthVertex( const bool  is2nd,
2236                                              TopoDS_Edge anEdge,
2237                                              const bool  CumOri )
2238 {
2239   if ( anEdge.Orientation() >= TopAbs_INTERNAL )
2240     anEdge.Orientation( TopAbs_FORWARD );
2241
2242   const TopAbs_Orientation tgtOri = is2nd ? TopAbs_REVERSED : TopAbs_FORWARD;
2243   TopoDS_Iterator vIt( anEdge, CumOri );
2244   while ( vIt.More() && vIt.Value().Orientation() != tgtOri )
2245     vIt.Next();
2246
2247   return ( vIt.More() ? TopoDS::Vertex(vIt.Value()) : TopoDS_Vertex() );
2248 }
2249
2250 //================================================================================
2251 /*!
2252  * \brief Return type of shape contained in a group 
2253  *  \param group - a shape of type TopAbs_COMPOUND
2254  *  \param avoidCompound - not to return TopAbs_COMPOUND
2255  */
2256 //================================================================================
2257
2258 TopAbs_ShapeEnum SMESH_MesherHelper::GetGroupType(const TopoDS_Shape& group,
2259                                                   const bool          avoidCompound)
2260 {
2261   if ( !group.IsNull() )
2262   {
2263     if ( group.ShapeType() != TopAbs_COMPOUND )
2264       return group.ShapeType();
2265
2266     // iterate on a compound
2267     TopoDS_Iterator it( group );
2268     if ( it.More() )
2269       return avoidCompound ? GetGroupType( it.Value() ) : it.Value().ShapeType();
2270   }
2271   return TopAbs_SHAPE;
2272 }
2273
2274 //=======================================================================
2275 //function : IsQuadraticMesh
2276 //purpose  : Check mesh without geometry for: if all elements on this shape are quadratic,
2277 //           quadratic elements will be created.
2278 //           Used then generated 3D mesh without geometry.
2279 //=======================================================================
2280
2281 SMESH_MesherHelper:: MType SMESH_MesherHelper::IsQuadraticMesh()
2282 {
2283   int NbAllEdgsAndFaces=0;
2284   int NbQuadFacesAndEdgs=0;
2285   int NbFacesAndEdges=0;
2286   //All faces and edges
2287   NbAllEdgsAndFaces = myMesh->NbEdges() + myMesh->NbFaces();
2288   if ( NbAllEdgsAndFaces == 0 )
2289     return SMESH_MesherHelper::LINEAR;
2290   
2291   //Quadratic faces and edges
2292   NbQuadFacesAndEdgs = myMesh->NbEdges(ORDER_QUADRATIC) + myMesh->NbFaces(ORDER_QUADRATIC);
2293
2294   //Linear faces and edges
2295   NbFacesAndEdges = myMesh->NbEdges(ORDER_LINEAR) + myMesh->NbFaces(ORDER_LINEAR);
2296   
2297   if (NbAllEdgsAndFaces == NbQuadFacesAndEdgs) {
2298     //Quadratic mesh
2299     return SMESH_MesherHelper::QUADRATIC;
2300   }
2301   else if (NbAllEdgsAndFaces == NbFacesAndEdges) {
2302     //Linear mesh
2303     return SMESH_MesherHelper::LINEAR;
2304   }
2305   else
2306     //Mesh with both type of elements
2307     return SMESH_MesherHelper::COMP;
2308 }
2309
2310 //=======================================================================
2311 //function : GetOtherParam
2312 //purpose  : Return an alternative parameter for a node on seam
2313 //=======================================================================
2314
2315 double SMESH_MesherHelper::GetOtherParam(const double param) const
2316 {
2317   int i = myParIndex & U_periodic ? 0 : 1;
2318   return fabs(param-myPar1[i]) < fabs(param-myPar2[i]) ? myPar2[i] : myPar1[i];
2319 }
2320
2321 namespace {
2322
2323   //=======================================================================
2324   /*!
2325    * \brief Iterator on ancestors of the given type
2326    */
2327   //=======================================================================
2328
2329   struct TAncestorsIterator : public SMDS_Iterator<const TopoDS_Shape*>
2330   {
2331     TopTools_ListIteratorOfListOfShape _ancIter;
2332     TopAbs_ShapeEnum                   _type;
2333     TopTools_MapOfShape                _encountered;
2334     TAncestorsIterator( const TopTools_ListOfShape& ancestors, TopAbs_ShapeEnum type)
2335       : _ancIter( ancestors ), _type( type )
2336     {
2337       if ( _ancIter.More() ) {
2338         if ( _ancIter.Value().ShapeType() != _type ) next();
2339         else _encountered.Add( _ancIter.Value() );
2340       }
2341     }
2342     virtual bool more()
2343     {
2344       return _ancIter.More();
2345     }
2346     virtual const TopoDS_Shape* next()
2347     {
2348       const TopoDS_Shape* s = _ancIter.More() ? & _ancIter.Value() : 0;
2349       if ( _ancIter.More() )
2350         for ( _ancIter.Next();  _ancIter.More(); _ancIter.Next())
2351           if ( _ancIter.Value().ShapeType() == _type && _encountered.Add( _ancIter.Value() ))
2352             break;
2353       return s;
2354     }
2355   };
2356
2357 } // namespace
2358
2359 //=======================================================================
2360 /*!
2361  * \brief Return iterator on ancestors of the given type
2362  */
2363 //=======================================================================
2364
2365 PShapeIteratorPtr SMESH_MesherHelper::GetAncestors(const TopoDS_Shape& shape,
2366                                                    const SMESH_Mesh&   mesh,
2367                                                    TopAbs_ShapeEnum    ancestorType)
2368 {
2369   return PShapeIteratorPtr( new TAncestorsIterator( mesh.GetAncestors(shape), ancestorType));
2370 }
2371
2372 //=======================================================================
2373 //function : GetCommonAncestor
2374 //purpose  : Find a common ancestors of two shapes of the given type
2375 //=======================================================================
2376
2377 TopoDS_Shape SMESH_MesherHelper::GetCommonAncestor(const TopoDS_Shape& shape1,
2378                                                    const TopoDS_Shape& shape2,
2379                                                    const SMESH_Mesh&   mesh,
2380                                                    TopAbs_ShapeEnum    ancestorType)
2381 {
2382   TopoDS_Shape commonAnc;
2383   if ( !shape1.IsNull() && !shape2.IsNull() )
2384   {
2385     PShapeIteratorPtr ancIt = GetAncestors( shape1, mesh, ancestorType );
2386     while ( const TopoDS_Shape* anc = ancIt->next() )
2387       if ( IsSubShape( shape2, *anc ))
2388       {
2389         commonAnc = *anc;
2390         break;
2391       }
2392   }
2393   return commonAnc;
2394 }
2395
2396 //#include <Perf_Meter.hxx>
2397
2398 //=======================================================================
2399 namespace { // Structures used by FixQuadraticElements()
2400 //=======================================================================
2401
2402 #define __DMP__(txt) \
2403   //cout << txt
2404 #define MSG(txt) __DMP__(txt<<endl)
2405 #define MSGBEG(txt) __DMP__(txt)
2406
2407   //const double straightTol2 = 1e-33; // to detect straing links
2408   bool isStraightLink(double linkLen2, double middleNodeMove2)
2409   {
2410     // straight if <node move> < 1/15 * <link length>
2411     return middleNodeMove2 < 1/15./15. * linkLen2;
2412   }
2413
2414   struct QFace;
2415   // ---------------------------------------
2416   /*!
2417    * \brief Quadratic link knowing its faces
2418    */
2419   struct QLink: public SMESH_TLink
2420   {
2421     const SMDS_MeshNode*          _mediumNode;
2422     mutable vector<const QFace* > _faces;
2423     mutable gp_Vec                _nodeMove;
2424     mutable int                   _nbMoves;
2425
2426     QLink(const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshNode* nm):
2427       SMESH_TLink( n1,n2 ), _mediumNode(nm), _nodeMove(0,0,0), _nbMoves(0) {
2428       _faces.reserve(4);
2429       //if ( MediumPos() != SMDS_TOP_3DSPACE )
2430         _nodeMove = MediumPnt() - MiddlePnt();
2431     }
2432     void SetContinuesFaces() const;
2433     const QFace* GetContinuesFace( const QFace* face ) const;
2434     bool OnBoundary() const;
2435     gp_XYZ MiddlePnt() const { return ( XYZ( node1() ) + XYZ( node2() )) / 2.; }
2436     gp_XYZ MediumPnt() const { return XYZ( _mediumNode ); }
2437
2438     SMDS_TypeOfPosition MediumPos() const
2439     { return _mediumNode->GetPosition()->GetTypeOfPosition(); }
2440     SMDS_TypeOfPosition EndPos(bool isSecond) const
2441     { return (isSecond ? node2() : node1())->GetPosition()->GetTypeOfPosition(); }
2442     const SMDS_MeshNode* EndPosNode(SMDS_TypeOfPosition pos) const
2443     { return EndPos(0) == pos ? node1() : EndPos(1) == pos ? node2() : 0; }
2444
2445     void Move(const gp_Vec& move, bool sum=false) const
2446     { _nodeMove += move; _nbMoves += sum ? (_nbMoves==0) : 1; }
2447     gp_XYZ Move() const { return _nodeMove.XYZ() / _nbMoves; }
2448     bool IsMoved() const { return (_nbMoves > 0 /*&& !IsStraight()*/); }
2449     bool IsStraight() const
2450     { return isStraightLink( (XYZ(node1())-XYZ(node2())).SquareModulus(),
2451                              _nodeMove.SquareMagnitude());
2452     }
2453     bool operator<(const QLink& other) const {
2454       return (node1()->GetID() == other.node1()->GetID() ?
2455               node2()->GetID() < other.node2()->GetID() :
2456               node1()->GetID() < other.node1()->GetID());
2457     }
2458 //     struct PtrComparator {
2459 //       bool operator() (const QLink* l1, const QLink* l2 ) const { return *l1 < *l2; }
2460 //     };
2461   };
2462   // ---------------------------------------------------------
2463   /*!
2464    * \brief Link in the chain of links; it connects two faces
2465    */
2466   struct TChainLink
2467   {
2468     const QLink*         _qlink;
2469     mutable const QFace* _qfaces[2];
2470
2471     TChainLink(const QLink* qlink=0):_qlink(qlink) {
2472       _qfaces[0] = _qfaces[1] = 0;
2473     }
2474     void SetFace(const QFace* face) const { int iF = _qfaces[0] ? 1 : 0; _qfaces[iF]=face; }
2475
2476     bool IsBoundary() const { return !_qfaces[1]; }
2477
2478     void RemoveFace( const QFace* face ) const
2479     { _qfaces[(face == _qfaces[1])] = 0; if (!_qfaces[0]) std::swap(_qfaces[0],_qfaces[1]); }
2480
2481     const QFace* NextFace( const QFace* f ) const
2482     { return _qfaces[0]==f ? _qfaces[1] : _qfaces[0]; }
2483
2484     const SMDS_MeshNode* NextNode( const SMDS_MeshNode* n ) const
2485     { return n == _qlink->node1() ? _qlink->node2() : _qlink->node1(); }
2486
2487     bool operator<(const TChainLink& other) const { return *_qlink < *other._qlink; }
2488
2489     operator bool() const { return (_qlink); }
2490
2491     const QLink* operator->() const { return _qlink; }
2492
2493     gp_Vec Normal() const;
2494
2495     bool IsStraight() const;
2496   };
2497   // --------------------------------------------------------------------
2498   typedef list< TChainLink > TChain;
2499   typedef set < TChainLink > TLinkSet;
2500   typedef TLinkSet::const_iterator TLinkInSet;
2501
2502   const int theFirstStep = 5;
2503
2504   enum { ERR_OK, ERR_TRI, ERR_PRISM, ERR_UNKNOWN }; // errors of QFace::GetLinkChain()
2505   // --------------------------------------------------------------------
2506   /*!
2507    * \brief Face shared by two volumes and bound by QLinks
2508    */
2509   struct QFace: public TIDSortedNodeSet
2510   {
2511     mutable const SMDS_MeshElement* _volumes[2];
2512     mutable vector< const QLink* >  _sides;
2513     mutable bool                    _sideIsAdded[4]; // added in chain of links
2514     gp_Vec                          _normal;
2515 #ifdef _DEBUG_
2516     mutable const SMDS_MeshElement* _face;
2517 #endif
2518
2519     QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face=0 );
2520
2521     void SetVolume(const SMDS_MeshElement* v) const { _volumes[ _volumes[0] ? 1 : 0 ] = v; }
2522
2523     int NbVolumes() const { return !_volumes[0] ? 0 : !_volumes[1] ? 1 : 2; }
2524
2525     void AddSelfToLinks() const {
2526       for ( int i = 0; i < _sides.size(); ++i )
2527         _sides[i]->_faces.push_back( this );
2528     }
2529     int LinkIndex( const QLink* side ) const {
2530       for (int i=0; i<_sides.size(); ++i ) if ( _sides[i] == side ) return i;
2531       return -1;
2532     }
2533     bool GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& err) const;
2534
2535     bool GetLinkChain( TChainLink& link, TChain& chain, SMDS_TypeOfPosition pos, int& err) const
2536     {
2537       int i = LinkIndex( link._qlink );
2538       if ( i < 0 ) return true;
2539       _sideIsAdded[i] = true;
2540       link.SetFace( this );
2541       // continue from opposite link
2542       return GetLinkChain( (i+2)%_sides.size(), chain, pos, err );
2543     }
2544     bool IsBoundary() const { return !_volumes[1]; }
2545
2546     bool Contains( const SMDS_MeshNode* node ) const { return count(node); }
2547
2548     bool IsSpoiled(const QLink* bentLink ) const;
2549
2550     TLinkInSet GetBoundaryLink( const TLinkSet&      links,
2551                                 const TChainLink&    avoidLink,
2552                                 TLinkInSet *         notBoundaryLink = 0,
2553                                 const SMDS_MeshNode* nodeToContain = 0,
2554                                 bool *               isAdjacentUsed = 0,
2555                                 int                  nbRecursionsLeft = -1) const;
2556
2557     TLinkInSet GetLinkByNode( const TLinkSet&      links,
2558                               const TChainLink&    avoidLink,
2559                               const SMDS_MeshNode* nodeToContain) const;
2560
2561     const SMDS_MeshNode* GetNodeInFace() const {
2562       for ( int iL = 0; iL < _sides.size(); ++iL )
2563         if ( _sides[iL]->MediumPos() == SMDS_TOP_FACE ) return _sides[iL]->_mediumNode;
2564       return 0;
2565     }
2566
2567     gp_Vec LinkNorm(const int i, SMESH_MesherHelper* theFaceHelper=0) const;
2568
2569     double MoveByBoundary( const TChainLink&   theLink,
2570                            const gp_Vec&       theRefVec,
2571                            const TLinkSet&     theLinks,
2572                            SMESH_MesherHelper* theFaceHelper=0,
2573                            const double        thePrevLen=0,
2574                            const int           theStep=theFirstStep,
2575                            gp_Vec*             theLinkNorm=0,
2576                            double              theSign=1.0) const;
2577   };
2578
2579   //================================================================================
2580   /*!
2581    * \brief Dump QLink and QFace
2582    */
2583   ostream& operator << (ostream& out, const QLink& l)
2584   {
2585     out <<"QLink nodes: "
2586         << l.node1()->GetID() << " - "
2587         << l._mediumNode->GetID() << " - "
2588         << l.node2()->GetID() << endl;
2589     return out;
2590   }
2591   ostream& operator << (ostream& out, const QFace& f)
2592   {
2593     out <<"QFace nodes: "/*<< &f << "  "*/;
2594     for ( TIDSortedNodeSet::const_iterator n = f.begin(); n != f.end(); ++n )
2595       out << (*n)->GetID() << " ";
2596     out << " \tvolumes: "
2597         << (f._volumes[0] ? f._volumes[0]->GetID() : 0) << " "
2598         << (f._volumes[1] ? f._volumes[1]->GetID() : 0);
2599     out << "  \tNormal: "<< f._normal.X() <<", "<<f._normal.Y() <<", "<<f._normal.Z() << endl;
2600     return out;
2601   }
2602
2603   //================================================================================
2604   /*!
2605    * \brief Construct QFace from QLinks 
2606    */
2607   //================================================================================
2608
2609   QFace::QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face )
2610   {
2611     _volumes[0] = _volumes[1] = 0;
2612     _sides = links;
2613     _sideIsAdded[0]=_sideIsAdded[1]=_sideIsAdded[2]=_sideIsAdded[3]=false;
2614     _normal.SetCoord(0,0,0);
2615     for ( int i = 1; i < _sides.size(); ++i ) {
2616       const QLink *l1 = _sides[i-1], *l2 = _sides[i];
2617       insert( l1->node1() ); insert( l1->node2() );
2618       // compute normal
2619       gp_Vec v1( XYZ( l1->node2()), XYZ( l1->node1()));
2620       gp_Vec v2( XYZ( l2->node1()), XYZ( l2->node2()));
2621       if ( l1->node1() != l2->node1() && l1->node2() != l2->node2() )
2622         v1.Reverse(); 
2623       _normal += v1 ^ v2;
2624     }
2625     double normSqSize = _normal.SquareMagnitude();
2626     if ( normSqSize > numeric_limits<double>::min() )
2627       _normal /= sqrt( normSqSize );
2628     else
2629       _normal.SetCoord(1e-33,0,0);
2630
2631 #ifdef _DEBUG_
2632     _face = face;
2633 #endif
2634   }
2635   //================================================================================
2636   /*!
2637    * \brief Make up a chain of links
2638    *  \param iSide - link to add first
2639    *  \param chain - chain to fill in
2640    *  \param pos   - postion of medium nodes the links should have
2641    *  \param error - out, specifies what is wrong
2642    *  \retval bool - false if valid chain can't be built; "valid" means that links
2643    *                 of the chain belongs to rectangles bounding hexahedrons
2644    */
2645   //================================================================================
2646
2647   bool QFace::GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& error) const
2648   {
2649     if ( iSide >= _sides.size() ) // wrong argument iSide
2650       return false;
2651     if ( _sideIsAdded[ iSide ]) // already in chain
2652       return true;
2653
2654     if ( _sides.size() != 4 ) { // triangle - visit all my continous faces
2655       MSGBEG( *this );
2656       TLinkSet links;
2657       list< const QFace* > faces( 1, this );
2658       while ( !faces.empty() ) {
2659         const QFace* face = faces.front();
2660         for ( int i = 0; i < face->_sides.size(); ++i ) {
2661           if ( !face->_sideIsAdded[i] && face->_sides[i] ) {
2662             face->_sideIsAdded[i] = true;
2663             // find a face side in the chain
2664             TLinkInSet chLink = links.insert( TChainLink(face->_sides[i])).first;
2665 //             TChain::iterator chLink = chain.begin();
2666 //             for ( ; chLink != chain.end(); ++chLink )
2667 //               if ( chLink->_qlink == face->_sides[i] )
2668 //                 break;
2669 //             if ( chLink == chain.end() )
2670 //               chLink = chain.insert( chain.begin(), TChainLink(face->_sides[i]));
2671             // add a face to a chained link and put a continues face in the queue
2672             chLink->SetFace( face );
2673             if ( face->_sides[i]->MediumPos() == pos )
2674               if ( const QFace* contFace = face->_sides[i]->GetContinuesFace( face ))
2675                 if ( contFace->_sides.size() == 3 )
2676                   faces.push_back( contFace );
2677           }
2678         }
2679         faces.pop_front();
2680       }
2681       if ( error < ERR_TRI )
2682         error = ERR_TRI;
2683       chain.insert( chain.end(), links.begin(),links.end() );
2684       return false;
2685     }
2686     _sideIsAdded[iSide] = true; // not to add this link to chain again
2687     const QLink* link = _sides[iSide];
2688     if ( !link)
2689       return true;
2690
2691     // add link into chain
2692     TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(link));
2693     chLink->SetFace( this );
2694     MSGBEG( *this );
2695
2696     // propagate from quadrangle to neighbour faces
2697     if ( link->MediumPos() >= pos ) {
2698       int nbLinkFaces = link->_faces.size();
2699       if ( nbLinkFaces == 4 || (/*nbLinkFaces < 4 && */link->OnBoundary())) {
2700         // hexahedral mesh or boundary quadrangles - goto a continous face
2701         if ( const QFace* f = link->GetContinuesFace( this ))
2702           if ( f->_sides.size() == 4 )
2703             return f->GetLinkChain( *chLink, chain, pos, error );
2704       }
2705       else {
2706         TChainLink chLink(link); // side face of prismatic mesh - visit all faces of iSide
2707         for ( int i = 0; i < nbLinkFaces; ++i )
2708           if ( link->_faces[i] )
2709             link->_faces[i]->GetLinkChain( chLink, chain, pos, error );
2710         if ( error < ERR_PRISM )
2711           error = ERR_PRISM;
2712         return false;
2713       }
2714     }
2715     return true;
2716   }
2717
2718   //================================================================================
2719   /*!
2720    * \brief Return a boundary link of the triangle face
2721    *  \param links - set of all links
2722    *  \param avoidLink - link not to return
2723    *  \param notBoundaryLink - out, neither the returned link nor avoidLink
2724    *  \param nodeToContain - node the returned link must contain; if provided, search
2725    *                         also performed on adjacent faces
2726    *  \param isAdjacentUsed - returns true if link is found in adjacent faces
2727    *  \param nbRecursionsLeft - to limit recursion
2728    */
2729   //================================================================================
2730
2731   TLinkInSet QFace::GetBoundaryLink( const TLinkSet&      links,
2732                                      const TChainLink&    avoidLink,
2733                                      TLinkInSet *         notBoundaryLink,
2734                                      const SMDS_MeshNode* nodeToContain,
2735                                      bool *               isAdjacentUsed,
2736                                      int                  nbRecursionsLeft) const
2737   {
2738     TLinkInSet linksEnd = links.end(), boundaryLink = linksEnd;
2739
2740     typedef list< pair< const QFace*, TLinkInSet > > TFaceLinkList;
2741     TFaceLinkList adjacentFaces;
2742
2743     for ( int iL = 0; iL < _sides.size(); ++iL )
2744     {
2745       if ( avoidLink._qlink == _sides[iL] )
2746         continue;
2747       TLinkInSet link = links.find( _sides[iL] );
2748       if ( link == linksEnd ) continue;
2749       if ( (*link)->MediumPos() > SMDS_TOP_FACE )
2750         continue; // We work on faces here, don't go inside a solid
2751
2752       // check link
2753       if ( link->IsBoundary() ) {
2754         if ( !nodeToContain ||
2755              (*link)->node1() == nodeToContain ||
2756              (*link)->node2() == nodeToContain )
2757         {
2758           boundaryLink = link;
2759           if ( !notBoundaryLink ) break;
2760         }
2761       }
2762       else if ( notBoundaryLink ) {
2763         *notBoundaryLink = link;
2764         if ( boundaryLink != linksEnd ) break;
2765       }
2766
2767       if ( boundaryLink == linksEnd && nodeToContain ) // collect adjacent faces
2768         if ( const QFace* adj = link->NextFace( this ))
2769           if ( adj->Contains( nodeToContain ))
2770             adjacentFaces.push_back( make_pair( adj, link ));
2771     }
2772
2773     if ( isAdjacentUsed ) *isAdjacentUsed = false;
2774     if ( boundaryLink == linksEnd && nodeToContain && nbRecursionsLeft) // check adjacent faces
2775     {
2776       if ( nbRecursionsLeft < 0 )
2777         nbRecursionsLeft = nodeToContain->NbInverseElements();
2778       TFaceLinkList::iterator adj = adjacentFaces.begin();
2779       for ( ; boundaryLink == linksEnd && adj != adjacentFaces.end(); ++adj )
2780         boundaryLink = adj->first->GetBoundaryLink( links, *(adj->second), 0, nodeToContain,
2781                                                     isAdjacentUsed, nbRecursionsLeft-1);
2782       if ( isAdjacentUsed ) *isAdjacentUsed = true;
2783     }
2784     return boundaryLink;
2785   }
2786   //================================================================================
2787   /*!
2788    * \brief Return a link ending at the given node but not avoidLink
2789    */
2790   //================================================================================
2791
2792   TLinkInSet QFace::GetLinkByNode( const TLinkSet&      links,
2793                                    const TChainLink&    avoidLink,
2794                                    const SMDS_MeshNode* nodeToContain) const
2795   {
2796     for ( int i = 0; i < _sides.size(); ++i )
2797       if ( avoidLink._qlink != _sides[i] &&
2798            (_sides[i]->node1() == nodeToContain || _sides[i]->node2() == nodeToContain ))
2799         return links.find( _sides[ i ]);
2800     return links.end();
2801   }
2802
2803   //================================================================================
2804   /*!
2805    * \brief Return normal to the i-th side pointing outside the face
2806    */
2807   //================================================================================
2808
2809   gp_Vec QFace::LinkNorm(const int i, SMESH_MesherHelper* /*uvHelper*/) const
2810   {
2811     gp_Vec norm, vecOut;
2812 //     if ( uvHelper ) {
2813 //       TopoDS_Face face = TopoDS::Face( uvHelper->GetSubShape());
2814 //       const SMDS_MeshNode* inFaceNode = uvHelper->GetNodeUVneedInFaceNode() ? GetNodeInFace() : 0;
2815 //       gp_XY uv1 = uvHelper->GetNodeUV( face, _sides[i]->node1(), inFaceNode );
2816 //       gp_XY uv2 = uvHelper->GetNodeUV( face, _sides[i]->node2(), inFaceNode );
2817 //       norm.SetCoord( uv1.Y() - uv2.Y(), uv2.X() - uv1.X(), 0 );
2818
2819 //       const QLink* otherLink = _sides[(i + 1) % _sides.size()];
2820 //       const SMDS_MeshNode* otherNode =
2821 //         otherLink->node1() == _sides[i]->node1() ? otherLink->node2() : otherLink->node1();
2822 //       gp_XY pIn = uvHelper->GetNodeUV( face, otherNode, inFaceNode );
2823 //       vecOut.SetCoord( uv1.X() - pIn.X(), uv1.Y() - pIn.Y(), 0 );
2824 //     }
2825 //     else {
2826       norm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
2827       gp_XYZ pIn = ( XYZ( _sides[0]->node1() ) +
2828                      XYZ( _sides[0]->node2() ) +
2829                      XYZ( _sides[1]->node1() )) / 3.;
2830       vecOut.SetXYZ( _sides[i]->MiddlePnt() - pIn );
2831       //}
2832     if ( norm * vecOut < 0 )
2833       norm.Reverse();
2834     double mag2 = norm.SquareMagnitude();
2835     if ( mag2 > numeric_limits<double>::min() )
2836       norm /= sqrt( mag2 );
2837     return norm;
2838   }
2839   //================================================================================
2840   /*!
2841    * \brief Move medium node of theLink according to its distance from boundary
2842    *  \param theLink - link to fix
2843    *  \param theRefVec - movement of boundary
2844    *  \param theLinks - all adjacent links of continous triangles
2845    *  \param theFaceHelper - helper is not used so far
2846    *  \param thePrevLen - distance from the boundary
2847    *  \param theStep - number of steps till movement propagation limit
2848    *  \param theLinkNorm - out normal to theLink
2849    *  \param theSign - 1 or -1 depending on movement of boundary
2850    *  \retval double - distance from boundary to propagation limit or other boundary
2851    */
2852   //================================================================================
2853
2854   double QFace::MoveByBoundary( const TChainLink&   theLink,
2855                                 const gp_Vec&       theRefVec,
2856                                 const TLinkSet&     theLinks,
2857                                 SMESH_MesherHelper* theFaceHelper,
2858                                 const double        thePrevLen,
2859                                 const int           theStep,
2860                                 gp_Vec*             theLinkNorm,
2861                                 double              theSign) const
2862   {
2863     if ( !theStep )
2864       return thePrevLen; // propagation limit reached
2865
2866     int iL; // index of theLink
2867     for ( iL = 0; iL < _sides.size(); ++iL )
2868       if ( theLink._qlink == _sides[ iL ])
2869         break;
2870
2871     MSG(string(theStep,'.')<<" Ref( "<<theRefVec.X()<<","<<theRefVec.Y()<<","<<theRefVec.Z()<<" )"
2872         <<" thePrevLen " << thePrevLen);
2873     MSG(string(theStep,'.')<<" "<<*theLink._qlink);
2874
2875     gp_Vec linkNorm = -LinkNorm( iL/*, theFaceHelper*/ ); // normal to theLink
2876     double refProj = theRefVec * linkNorm; // project movement vector to normal of theLink
2877     if ( theStep == theFirstStep )
2878       theSign = refProj < 0. ? -1. : 1.;
2879     else if ( theSign * refProj < 0.4 * theRefVec.Magnitude())
2880       return thePrevLen; // to propagate movement forward only, not in side dir or backward
2881
2882     int iL1 = (iL + 1) % 3, iL2 = (iL + 2) % 3; // indices of the two other links of triangle
2883     TLinkInSet link1 = theLinks.find( _sides[iL1] );
2884     TLinkInSet link2 = theLinks.find( _sides[iL2] );
2885     if ( link1 == theLinks.end() || link2 == theLinks.end() )
2886       return thePrevLen;
2887     const QFace* f1 = link1->NextFace( this ); // adjacent faces
2888     const QFace* f2 = link2->NextFace( this );
2889
2890     // propagate to adjacent faces till limit step or boundary
2891     double len1 = thePrevLen + (theLink->MiddlePnt() - _sides[iL1]->MiddlePnt()).Modulus();
2892     double len2 = thePrevLen + (theLink->MiddlePnt() - _sides[iL2]->MiddlePnt()).Modulus();
2893     gp_Vec linkDir1(0,0,0); // initialize to avoid valgrind error ("Conditional jump...")
2894     gp_Vec linkDir2(0,0,0);
2895     try {
2896       OCC_CATCH_SIGNALS;
2897       if ( f1 && theLink->MediumPos() <= (*link1)->MediumPos() )
2898         len1 = f1->MoveByBoundary
2899           ( *link1, theRefVec, theLinks, theFaceHelper, len1, theStep-1, &linkDir1, theSign);
2900       else
2901         linkDir1 = LinkNorm( iL1/*, theFaceHelper*/ );
2902     } catch (...) {
2903       MSG( " --------------- EXCEPTION");
2904       return thePrevLen;
2905     }
2906     try {
2907       OCC_CATCH_SIGNALS;
2908       if ( f2 && theLink->MediumPos() <= (*link2)->MediumPos() )
2909         len2 = f2->MoveByBoundary
2910           ( *link2, theRefVec, theLinks, theFaceHelper, len2, theStep-1, &linkDir2, theSign);
2911       else
2912         linkDir2 = LinkNorm( iL2/*, theFaceHelper*/ );
2913     } catch (...) {
2914       MSG( " --------------- EXCEPTION");
2915       return thePrevLen;
2916     }
2917
2918     double fullLen = 0;
2919     if ( theStep != theFirstStep )
2920     {
2921       // choose chain length by direction of propagation most codirected with theRefVec
2922       bool choose1 = ( theRefVec * linkDir1 * theSign > theRefVec * linkDir2 * theSign );
2923       fullLen = choose1 ? len1 : len2;
2924       double r = thePrevLen / fullLen;
2925
2926       gp_Vec move = linkNorm * refProj * ( 1 - r );
2927       theLink->Move( move, true );
2928
2929       MSG(string(theStep,'.')<<" Move "<< theLink->_mediumNode->GetID()<<
2930           " by " << refProj * ( 1 - r ) << " following " <<
2931           (choose1 ? *link1->_qlink : *link2->_qlink));
2932
2933       if ( theLinkNorm ) *theLinkNorm = linkNorm;
2934     }
2935     return fullLen;
2936   }
2937
2938   //================================================================================
2939   /*!
2940    * \brief Checks if the face is distorted due to bentLink
2941    */
2942   //================================================================================
2943
2944   bool QFace::IsSpoiled(const QLink* bentLink ) const
2945   {
2946     // code is valid for convex faces only
2947     gp_XYZ gc(0,0,0);
2948     for ( TIDSortedNodeSet::const_iterator n = begin(); n!=end(); ++n)
2949       gc += XYZ( *n ) / size();
2950     for (unsigned i = 0; i < _sides.size(); ++i )
2951     {
2952       if ( _sides[i] == bentLink ) continue;
2953       gp_Vec linkNorm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
2954       gp_Vec vecOut( gc, _sides[i]->MiddlePnt() );
2955       if ( linkNorm * vecOut < 0 )
2956         linkNorm.Reverse();
2957       double mag2 = linkNorm.SquareMagnitude();
2958       if ( mag2 > numeric_limits<double>::min() )
2959         linkNorm /= sqrt( mag2 );
2960       gp_Vec vecBent    ( _sides[i]->MiddlePnt(), bentLink->MediumPnt());
2961       gp_Vec vecStraight( _sides[i]->MiddlePnt(), bentLink->MiddlePnt());
2962       if ( vecBent * linkNorm > -0.1*vecStraight.Magnitude() )
2963         return true;
2964     }
2965     return false;
2966     
2967   }
2968
2969   //================================================================================
2970   /*!
2971    * \brief Find pairs of continues faces 
2972    */
2973   //================================================================================
2974
2975   void QLink::SetContinuesFaces() const
2976   {
2977     //       x0         x - QLink, [-|] - QFace, v - volume
2978     //   v0  |   v1   
2979     //       |          Between _faces of link x2 two vertical faces are continues
2980     // x1----x2-----x3  and two horizontal faces are continues. We set vertical faces
2981     //       |          to _faces[0] and _faces[1] and horizontal faces to
2982     //   v2  |   v3     _faces[2] and _faces[3] (or vise versa).
2983     //       x4
2984
2985     if ( _faces.empty() )
2986       return;
2987     int iFaceCont = -1, nbBoundary = 0, iBoundary[2]={-1,-1};
2988     if ( _faces[0]->IsBoundary() )
2989       iBoundary[ nbBoundary++ ] = 0;
2990     for ( int iF = 1; iFaceCont < 0 && iF < _faces.size(); ++iF )
2991     {
2992       // look for a face bounding none of volumes bound by _faces[0]
2993       bool sameVol = false;
2994       int nbVol = _faces[iF]->NbVolumes();
2995       for ( int iV = 0; !sameVol && iV < nbVol; ++iV )
2996         sameVol = ( _faces[iF]->_volumes[iV] == _faces[0]->_volumes[0] ||
2997                     _faces[iF]->_volumes[iV] == _faces[0]->_volumes[1]);
2998       if ( !sameVol )
2999         iFaceCont = iF;
3000       if ( _faces[iF]->IsBoundary() )
3001         iBoundary[ nbBoundary++ ] = iF;
3002     }
3003     // Set continues faces: arrange _faces to have
3004     // _faces[0] continues to _faces[1]
3005     // _faces[2] continues to _faces[3]
3006     if ( nbBoundary == 2 ) // bnd faces are continues
3007     {
3008       if (( iBoundary[0] < 2 ) != ( iBoundary[1] < 2 ))
3009       {
3010         int iNear0 = iBoundary[0] < 2 ? 1-iBoundary[0] : 5-iBoundary[0];
3011         std::swap( _faces[ iBoundary[1] ], _faces[iNear0] );
3012       }
3013     }
3014     else if ( iFaceCont > 0 ) // continues faces found
3015     {
3016       if ( iFaceCont != 1 )
3017         std::swap( _faces[1], _faces[iFaceCont] );
3018     }
3019     else if ( _faces.size() > 1 ) // not found, set NULL by the first face
3020     {
3021       _faces.insert( ++_faces.begin(), 0 );
3022     }
3023   }
3024   //================================================================================
3025   /*!
3026    * \brief Return a face continues to the given one
3027    */
3028   //================================================================================
3029
3030   const QFace* QLink::GetContinuesFace( const QFace* face ) const
3031   {
3032     for ( int i = 0; i < _faces.size(); ++i ) {
3033       if ( _faces[i] == face ) {
3034         int iF = i < 2 ? 1-i : 5-i;
3035         return iF < _faces.size() ? _faces[iF] : 0;
3036       }
3037     }
3038     return 0;
3039   }
3040   //================================================================================
3041   /*!
3042    * \brief True if link is on mesh boundary
3043    */
3044   //================================================================================
3045
3046   bool QLink::OnBoundary() const
3047   {
3048     for ( int i = 0; i < _faces.size(); ++i )
3049       if (_faces[i] && _faces[i]->IsBoundary()) return true;
3050     return false;
3051   }
3052   //================================================================================
3053   /*!
3054    * \brief Return normal of link of the chain
3055    */
3056   //================================================================================
3057
3058   gp_Vec TChainLink::Normal() const {
3059     gp_Vec norm;
3060     if (_qfaces[0]) norm  = _qfaces[0]->_normal;
3061     if (_qfaces[1]) norm += _qfaces[1]->_normal;
3062     return norm;
3063   }
3064   //================================================================================
3065   /*!
3066    * \brief Test link curvature taking into account size of faces
3067    */
3068   //================================================================================
3069
3070   bool TChainLink::IsStraight() const
3071   {
3072     bool isStraight = _qlink->IsStraight();
3073     if ( isStraight && _qfaces[0] && !_qfaces[1] )
3074     {
3075       int i = _qfaces[0]->LinkIndex( _qlink );
3076       int iOpp = ( i + 2 ) % _qfaces[0]->_sides.size();
3077       gp_XYZ mid1 = _qlink->MiddlePnt();
3078       gp_XYZ mid2 = _qfaces[0]->_sides[ iOpp ]->MiddlePnt();
3079       double faceSize2 = (mid1-mid2).SquareModulus();
3080       isStraight = _qlink->_nodeMove.SquareMagnitude() < 1/10./10. * faceSize2;
3081     }
3082     return isStraight;
3083   }
3084   
3085   //================================================================================
3086   /*!
3087    * \brief Move medium nodes of vertical links of pentahedrons adjacent by side faces
3088    */
3089   //================================================================================
3090
3091   void fixPrism( TChain& allLinks )
3092   {
3093     // separate boundary links from internal ones
3094     typedef set<const QLink*/*, QLink::PtrComparator*/> QLinkSet;
3095     QLinkSet interLinks, bndLinks1, bndLink2;
3096
3097     bool isCurved = false;
3098     for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
3099       if ( (*lnk)->OnBoundary() )
3100         bndLinks1.insert( lnk->_qlink );
3101       else
3102         interLinks.insert( lnk->_qlink );
3103       isCurved = isCurved || !lnk->IsStraight();
3104     }
3105     if ( !isCurved )
3106       return; // no need to move
3107
3108     QLinkSet *curBndLinks = &bndLinks1, *newBndLinks = &bndLink2;
3109
3110     while ( !interLinks.empty() && !curBndLinks->empty() )
3111     {
3112       // propagate movement from boundary links to connected internal links
3113       QLinkSet::iterator bnd = curBndLinks->begin(), bndEnd = curBndLinks->end();
3114       for ( ; bnd != bndEnd; ++bnd )
3115       {
3116         const QLink* bndLink = *bnd;
3117         for ( int i = 0; i < bndLink->_faces.size(); ++i ) // loop on faces of bndLink
3118         {
3119           const QFace* face = bndLink->_faces[i]; // quadrange lateral face of a prism
3120           if ( !face ) continue;
3121           // find and move internal link opposite to bndLink within the face
3122           int interInd = ( face->LinkIndex( bndLink ) + 2 ) % face->_sides.size();
3123           const QLink* interLink = face->_sides[ interInd ];
3124           QLinkSet::iterator pInterLink = interLinks.find( interLink );
3125           if ( pInterLink == interLinks.end() ) continue; // not internal link
3126           interLink->Move( bndLink->_nodeMove );
3127           // treated internal links become new boundary ones
3128           interLinks. erase( pInterLink );
3129           newBndLinks->insert( interLink );
3130         }
3131       }
3132       curBndLinks->clear();
3133       std::swap( curBndLinks, newBndLinks );
3134     }
3135   }
3136
3137   //================================================================================
3138   /*!
3139    * \brief Fix links of continues triangles near curved boundary
3140    */
3141   //================================================================================
3142
3143   void fixTriaNearBoundary( TChain & allLinks, SMESH_MesherHelper& /*helper*/)
3144   {
3145     if ( allLinks.empty() ) return;
3146
3147     TLinkSet linkSet( allLinks.begin(), allLinks.end());
3148     TLinkInSet linkIt = linkSet.begin(), linksEnd = linkSet.end();
3149
3150     for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt)
3151     {
3152       if ( linkIt->IsBoundary() && !linkIt->IsStraight() && linkIt->_qfaces[0])
3153       {
3154         // move iff a boundary link is bent towards inside of a face (issue 0021084)
3155         const QFace* face = linkIt->_qfaces[0];
3156         gp_XYZ pIn = ( face->_sides[0]->MiddlePnt() +
3157                        face->_sides[1]->MiddlePnt() +
3158                        face->_sides[2]->MiddlePnt() ) / 3.;
3159         gp_XYZ insideDir( pIn - (*linkIt)->MiddlePnt());
3160         bool linkBentInside = ((*linkIt)->_nodeMove.Dot( insideDir ) > 0 );
3161         //if ( face->IsSpoiled( linkIt->_qlink ))
3162         if ( linkBentInside )
3163           face->MoveByBoundary( *linkIt, (*linkIt)->_nodeMove, linkSet );
3164       }
3165     }
3166   }
3167
3168   //================================================================================
3169   /*!
3170    * \brief Detect rectangular structure of links and build chains from them
3171    */
3172   //================================================================================
3173
3174   enum TSplitTriaResult {
3175     _OK, _NO_CORNERS, _FEW_ROWS, _MANY_ROWS, _NO_SIDELINK, _BAD_MIDQUAD, _NOT_RECT,
3176     _NO_MIDQUAD, _NO_UPTRIA, _BAD_SET_SIZE, _BAD_CORNER, _BAD_START, _NO_BOTLINK, _TWISTED_CHAIN };
3177
3178   TSplitTriaResult splitTrianglesIntoChains( TChain &            allLinks,
3179                                              vector< TChain> &   resultChains,
3180                                              SMDS_TypeOfPosition pos )
3181   {
3182     // put links in the set and evalute number of result chains by number of boundary links
3183     TLinkSet linkSet;
3184     int nbBndLinks = 0;
3185     for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
3186       linkSet.insert( *lnk );
3187       nbBndLinks += lnk->IsBoundary();
3188     }
3189     resultChains.clear();
3190     resultChains.reserve( nbBndLinks / 2 );
3191
3192     TLinkInSet linkIt, linksEnd = linkSet.end();
3193
3194     // find a boundary link with corner node; corner node has position pos-2
3195     // i.e. SMDS_TOP_VERTEX for links on faces and SMDS_TOP_EDGE for
3196     // links in volume
3197     SMDS_TypeOfPosition cornerPos = SMDS_TypeOfPosition(pos-2);
3198     const SMDS_MeshNode* corner = 0;
3199     for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt )
3200       if ( linkIt->IsBoundary() && (corner = (*linkIt)->EndPosNode(cornerPos)))
3201         break;
3202     if ( !corner)
3203       return _NO_CORNERS;
3204
3205     TLinkInSet           startLink = linkIt;
3206     const SMDS_MeshNode* startCorner = corner;
3207     vector< TChain* >    rowChains;
3208     int iCol = 0;
3209
3210     while ( startLink != linksEnd) // loop on columns
3211     {
3212       // We suppose we have a rectangular structure like shown here. We have found a
3213       //               corner of the rectangle (startCorner) and a boundary link sharing  
3214       //    |/  |/  |  the startCorner (startLink). We are going to loop on rows of the   
3215       //  --o---o---o  structure making several chains at once. One chain (columnChain)   
3216       //    |\  |  /|  starts at startLink and continues upward (we look at the structure 
3217       //  \ | \ | / |  from such point that startLink is on the bottom of the structure). 
3218       //   \|  \|/  |  While going upward we also fill horizontal chains (rowChains) we   
3219       //  --o---o---o  encounter.                                                         
3220       //   /|\  |\  |
3221       //  / | \ | \ |  startCorner
3222       //    |  \|  \|,'
3223       //  --o---o---o
3224       //          `.startLink
3225
3226       if ( resultChains.size() == nbBndLinks / 2 )
3227         return _NOT_RECT;
3228       resultChains.push_back( TChain() );
3229       TChain& columnChain = resultChains.back();
3230
3231       TLinkInSet botLink = startLink; // current horizontal link to go up from
3232       corner = startCorner; // current corner the botLink ends at
3233       int iRow = 0;
3234       while ( botLink != linksEnd ) // loop on rows
3235       {
3236         // add botLink to the columnChain
3237         columnChain.push_back( *botLink );
3238
3239         const QFace* botTria = botLink->_qfaces[0]; // bottom triangle bound by botLink
3240         if ( !botTria )
3241         { // the column ends
3242           if ( botLink == startLink )
3243             return _TWISTED_CHAIN; // issue 0020951
3244           linkSet.erase( botLink );
3245           if ( iRow != rowChains.size() )
3246             return _FEW_ROWS; // different nb of rows in columns
3247           break;
3248         }
3249         // find the link dividing the quadrangle (midQuadLink) and vertical boundary
3250         // link ending at <corner> (sideLink); there are two cases:
3251         // 1) midQuadLink does not end at <corner>, then we easily find it by botTria,
3252         //   since midQuadLink is not at boundary while sideLink is.
3253         // 2) midQuadLink ends at <corner>
3254         bool isCase2;
3255         TLinkInSet midQuadLink = linksEnd;
3256         TLinkInSet sideLink = botTria->GetBoundaryLink( linkSet, *botLink, &midQuadLink,
3257                                                         corner, &isCase2 );
3258         if ( isCase2 ) { // find midQuadLink among links of botTria
3259           midQuadLink = botTria->GetLinkByNode( linkSet, *botLink, corner );
3260           if ( midQuadLink->IsBoundary() )
3261             return _BAD_MIDQUAD;
3262         }
3263         if ( sideLink == linksEnd || midQuadLink == linksEnd || sideLink == midQuadLink )
3264           return sideLink == linksEnd ? _NO_SIDELINK : _NO_MIDQUAD;
3265
3266         // fill chains
3267         columnChain.push_back( *midQuadLink );
3268         if ( iRow >= rowChains.size() ) {
3269           if ( iCol > 0 )
3270             return _MANY_ROWS; // different nb of rows in columns
3271           if ( resultChains.size() == nbBndLinks / 2 )
3272             return _NOT_RECT;
3273           resultChains.push_back( TChain() );
3274           rowChains.push_back( & resultChains.back() );
3275         }
3276         rowChains[iRow]->push_back( *sideLink );
3277         rowChains[iRow]->push_back( *midQuadLink );
3278
3279         const QFace* upTria = midQuadLink->NextFace( botTria ); // upper tria of the rectangle
3280         if ( !upTria)
3281           return _NO_UPTRIA;
3282         if ( iRow == 0 ) {
3283           // prepare startCorner and startLink for the next column
3284           startCorner = startLink->NextNode( startCorner );
3285           if (isCase2)
3286             startLink = botTria->GetBoundaryLink( linkSet, *botLink, 0, startCorner );
3287           else
3288             startLink = upTria->GetBoundaryLink( linkSet, *midQuadLink, 0, startCorner );
3289           // check if no more columns remains
3290           if ( startLink != linksEnd ) {
3291             const SMDS_MeshNode* botNode = startLink->NextNode( startCorner );
3292             if ( (isCase2 ? botTria : upTria)->Contains( botNode ))
3293               startLink = linksEnd; // startLink bounds upTria or botTria
3294             else if ( startLink == botLink || startLink == midQuadLink || startLink == sideLink )
3295               return _BAD_START;
3296           }
3297         }
3298         // find bottom link and corner for the next row
3299         corner = sideLink->NextNode( corner );
3300         // next bottom link ends at the new corner
3301         linkSet.erase( botLink );
3302         botLink = upTria->GetLinkByNode( linkSet, (isCase2 ? *sideLink : *midQuadLink), corner );
3303         if ( botLink == linksEnd || botLink == midQuadLink || botLink == sideLink)
3304           return _NO_BOTLINK;
3305         if ( midQuadLink == startLink || sideLink == startLink )
3306           return _TWISTED_CHAIN; // issue 0020951
3307         linkSet.erase( midQuadLink );
3308         linkSet.erase( sideLink );
3309
3310         // make faces neighboring the found ones be boundary
3311         if ( startLink != linksEnd ) {
3312           const QFace* tria = isCase2 ? botTria : upTria;
3313           for ( int iL = 0; iL < 3; ++iL ) {
3314             linkIt = linkSet.find( tria->_sides[iL] );
3315             if ( linkIt != linksEnd )
3316               linkIt->RemoveFace( tria );
3317           }
3318         }
3319         if ( botLink->_qfaces[0] == upTria || botLink->_qfaces[1] == upTria )
3320           botLink->RemoveFace( upTria ); // make next botTria first in vector
3321
3322         iRow++;
3323       } // loop on rows
3324
3325       iCol++;
3326     }
3327     // In the linkSet, there must remain the last links of rowChains; add them
3328     if ( linkSet.size() != rowChains.size() )
3329       return _BAD_SET_SIZE;
3330     for ( int iRow = 0; iRow < rowChains.size(); ++iRow ) {
3331       // find the link (startLink) ending at startCorner
3332       corner = 0;
3333       for ( startLink = linkSet.begin(); startLink != linksEnd; ++startLink ) {
3334         if ( (*startLink)->node1() == startCorner ) {
3335           corner = (*startLink)->node2(); break;
3336         }
3337         else if ( (*startLink)->node2() == startCorner) {
3338           corner = (*startLink)->node1(); break;
3339         }
3340       }
3341       if ( startLink == linksEnd )
3342         return _BAD_CORNER;
3343       rowChains[ iRow ]->push_back( *startLink );
3344       linkSet.erase( startLink );
3345       startCorner = corner;
3346     }
3347
3348     return _OK;
3349   }
3350
3351   //================================================================================
3352   /*!
3353    * \brief Place medium nodes at the link middle for elements whose corner nodes
3354    *        are out of geometrical boundary to prevent distorting elements.
3355    *        Issue 0020982, note 0013990
3356    */
3357   //================================================================================
3358
3359   void force3DOutOfBoundary( SMESH_MesherHelper&    theHelper,
3360                              SMESH_ComputeErrorPtr& theError)
3361   {
3362     SMESHDS_Mesh* meshDS = theHelper.GetMeshDS();
3363     TopoDS_Shape  shape = theHelper.GetSubShape().Oriented( TopAbs_FORWARD );
3364     if ( shape.IsNull() ) return;
3365
3366     if ( !theError ) theError = SMESH_ComputeError::New();
3367
3368     gp_XYZ faceNorm;
3369
3370     if ( shape.ShapeType() == TopAbs_FACE ) // 2D
3371     {
3372       if ( theHelper.GetMesh()->NbTriangles( ORDER_QUADRATIC ) < 1 ) return;
3373
3374       SMESHDS_SubMesh* faceSM = meshDS->MeshElements( shape );
3375       if ( !faceSM ) return;
3376
3377       const TopoDS_Face&      face = TopoDS::Face( shape );
3378       Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3379
3380       TopExp_Explorer edgeIt( face, TopAbs_EDGE );
3381       for ( ; edgeIt.More(); edgeIt.Next() ) // loop on EDGEs of a FACE
3382       {
3383         // check if the EDGE needs checking
3384         const TopoDS_Edge& edge = TopoDS::Edge( edgeIt.Current() );
3385         if ( BRep_Tool::Degenerated( edge ) )
3386           continue;
3387         if ( theHelper.IsRealSeam( edge ) &&
3388              edge.Orientation() == TopAbs_REVERSED )
3389           continue;
3390
3391         SMESHDS_SubMesh* edgeSM = meshDS->MeshElements( edge );
3392         if ( !edgeSM ) continue;
3393
3394         double f,l;
3395         Handle(Geom2d_Curve) pcurve  = BRep_Tool::CurveOnSurface( edge, face, f, l );
3396         BRepAdaptor_Curve    curve3D( edge );
3397         switch ( curve3D.GetType() ) {
3398         case GeomAbs_Line: continue;
3399         case GeomAbs_Circle:
3400         case GeomAbs_Ellipse:
3401         case GeomAbs_Hyperbola:
3402         case GeomAbs_Parabola:
3403           try
3404           {
3405             gp_Vec D1, D2, Du1, Dv1; gp_Pnt p;
3406             curve3D.D2( 0.5 * ( f + l ), p, D1, D2 );
3407             gp_Pnt2d uv = pcurve->Value( 0.5 * ( f + l ) );
3408             surface->D1( uv.X(), uv.Y(), p, Du1, Dv1 );
3409             gp_Vec fNorm = Du1 ^ Dv1;
3410             if ( fNorm.IsParallel( D2, M_PI * 25./180. ))
3411               continue; // face is normal to the curve3D
3412
3413             gp_Vec curvNorm = fNorm ^ D1;
3414             if ( edge.Orientation() == TopAbs_REVERSED ) curvNorm.Reverse();
3415             if ( curvNorm * D2 > 0 )
3416               continue; // convex edge
3417           }
3418           catch ( Standard_Failure )
3419           {
3420             continue;
3421           }
3422         }
3423         // get nodes shared by faces that may be distorted
3424         SMDS_NodeIteratorPtr nodeIt;
3425         if ( edgeSM->NbNodes() > 0 ) {
3426           nodeIt = edgeSM->GetNodes();
3427         }
3428         else {
3429           SMESHDS_SubMesh* vertexSM = meshDS->MeshElements( theHelper.IthVertex( 0, edge ));
3430           if ( !vertexSM )
3431             vertexSM = meshDS->MeshElements( theHelper.IthVertex( 1, edge ));
3432           if ( !vertexSM ) continue;
3433           nodeIt = vertexSM->GetNodes();
3434         }
3435
3436         // find suspicious faces
3437         TIDSortedElemSet checkedFaces;
3438         vector< const SMDS_MeshNode* > nOnEdge( 2 );
3439         const SMDS_MeshNode*           nOnFace;
3440         while ( nodeIt->more() )
3441         {
3442           const SMDS_MeshNode* n      = nodeIt->next();
3443           SMDS_ElemIteratorPtr faceIt = n->GetInverseElementIterator( SMDSAbs_Face );
3444           while ( faceIt->more() )
3445           {
3446             const SMDS_MeshElement* f = faceIt->next();
3447             if ( !faceSM->Contains( f ) ||
3448                  f->NbNodes() != 6      || // check quadratic triangles only
3449                  !checkedFaces.insert( f ).second )
3450               continue;
3451
3452             // get nodes on EDGE and on FACE of a suspicious face
3453             nOnEdge.clear(); nOnFace = 0;
3454             SMDS_MeshElement::iterator triNode = f->begin_nodes();
3455             for ( int nbN = 0; nbN < 3; ++triNode, ++nbN )
3456             {
3457               n = *triNode;
3458               if ( n->GetPosition()->GetDim() == 2 )
3459                 nOnFace = n;
3460               else
3461                 nOnEdge.push_back( n );
3462             }
3463
3464             // check if nOnFace is inside the FACE
3465             if ( nOnFace && nOnEdge.size() == 2 )
3466             {
3467               theHelper.AddTLinks( static_cast< const SMDS_MeshFace* > ( f ));
3468               if ( !SMESH_Algo::FaceNormal( f, faceNorm, /*normalized=*/false ))
3469                 continue;
3470               gp_XYZ edgeDir  = SMESH_TNodeXYZ( nOnEdge[0] ) - SMESH_TNodeXYZ( nOnEdge[1] );
3471               gp_XYZ edgeNorm = faceNorm ^ edgeDir;
3472               n = theHelper.GetMediumNode( nOnEdge[0], nOnEdge[1], true );
3473               gp_XYZ pN0     = SMESH_TNodeXYZ( nOnEdge[0] );
3474               gp_XYZ pMedium = SMESH_TNodeXYZ( n );                   // on-edge node location
3475               gp_XYZ pFaceN  = SMESH_TNodeXYZ( nOnFace );             // on-face node location
3476               double hMedium = edgeNorm * gp_Vec( pN0, pMedium ).XYZ();
3477               double hFace   = edgeNorm * gp_Vec( pN0, pFaceN ).XYZ();
3478               if ( Abs( hMedium ) > Abs( hFace * 0.6 ))
3479               {
3480                 // nOnFace is out of FACE, move a medium on-edge node to the middle
3481                 gp_XYZ pMid3D = 0.5 * ( pN0 + SMESH_TNodeXYZ( nOnEdge[1] ));
3482                 meshDS->MoveNode( n, pMid3D.X(), pMid3D.Y(), pMid3D.Z() );
3483                 MSG( "move OUT of face " << n );
3484                 theError->myBadElements.push_back( f );
3485               }
3486             }
3487           }
3488         }
3489       }
3490       if ( !theError->myBadElements.empty() )
3491         theError->myName = EDITERR_NO_MEDIUM_ON_GEOM;
3492       return;
3493
3494     } // 2D ==============================================================================
3495
3496     if ( shape.ShapeType() == TopAbs_SOLID ) // 3D
3497     {
3498       if ( theHelper.GetMesh()->NbTetras  ( ORDER_QUADRATIC ) < 1 &&
3499            theHelper.GetMesh()->NbPyramids( ORDER_QUADRATIC ) < 1 ) return;
3500
3501       SMESHDS_SubMesh* solidSM = meshDS->MeshElements( shape );
3502       if ( !solidSM ) return;
3503
3504       // check if the SOLID is bound by concave FACEs
3505       vector< TopoDS_Face > concaveFaces;
3506       TopExp_Explorer faceIt( shape, TopAbs_FACE );
3507       for ( ; faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
3508       {
3509         const TopoDS_Face&  face = TopoDS::Face( faceIt.Current() );
3510         if ( !meshDS->MeshElements( face )) continue;
3511
3512         BRepAdaptor_Surface surface( face );
3513         switch ( surface.GetType() ) {
3514         case GeomAbs_Plane: continue;
3515         case GeomAbs_Cylinder:
3516         case GeomAbs_Cone:
3517         case GeomAbs_Sphere:
3518           try
3519           {
3520             double u = 0.5 * ( surface.FirstUParameter() + surface.LastUParameter() );
3521             double v = 0.5 * ( surface.FirstVParameter() + surface.LastVParameter() );
3522             gp_Vec Du1, Dv1, Du2, Dv2, Duv2; gp_Pnt p;
3523             surface.D2( u,v, p, Du1, Dv1, Du2, Dv2, Duv2 );
3524             gp_Vec fNorm = Du1 ^ Dv1;
3525             if ( face.Orientation() == TopAbs_REVERSED ) fNorm.Reverse();
3526             bool concaveU = ( fNorm * Du2 > 1e-100 );
3527             bool concaveV = ( fNorm * Dv2 > 1e-100 );
3528             if ( concaveU || concaveV )
3529               concaveFaces.push_back( face );
3530           }
3531           catch ( Standard_Failure )
3532           {
3533             concaveFaces.push_back( face );
3534           }
3535         }
3536       }
3537       if ( concaveFaces.empty() )
3538         return;
3539
3540       // fix 2D mesh on the SOLID
3541       for ( faceIt.ReInit(); faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
3542       {
3543         SMESH_MesherHelper faceHelper( *theHelper.GetMesh() );
3544         faceHelper.SetSubShape( faceIt.Current() );
3545         force3DOutOfBoundary( faceHelper, theError );
3546       }
3547
3548       // get an iterator over faces on concaveFaces
3549       vector< SMDS_ElemIteratorPtr > faceIterVec( concaveFaces.size() );
3550       for ( size_t i = 0; i < concaveFaces.size(); ++i )
3551         faceIterVec[i] = meshDS->MeshElements( concaveFaces[i] )->GetElements();
3552       typedef SMDS_IteratorOnIterators
3553         < const SMDS_MeshElement*, vector< SMDS_ElemIteratorPtr > > TIterOnIter;
3554       SMDS_ElemIteratorPtr faceIter( new TIterOnIter( faceIterVec ));
3555
3556       // a seacher to check if a volume is close to a concave face
3557       std::auto_ptr< SMESH_ElementSearcher > faceSearcher
3558         ( SMESH_MeshEditor( theHelper.GetMesh() ).GetElementSearcher( faceIter ));
3559
3560       // classifier
3561       //BRepClass3d_SolidClassifier solidClassifier( shape );
3562
3563       TIDSortedElemSet checkedVols, movedNodes;
3564       for ( faceIt.ReInit(); faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
3565       {
3566         const TopoDS_Shape& face = faceIt.Current();
3567         SMESHDS_SubMesh*  faceSM = meshDS->MeshElements( face );
3568         if ( !faceSM ) continue;
3569
3570         // get nodes shared by volumes (tet and pyra) on the FACE that may be distorted
3571         SMDS_NodeIteratorPtr nodeIt;
3572         if ( faceSM->NbNodes() > 0 ) {
3573           nodeIt = faceSM->GetNodes();
3574         }
3575         else {
3576           TopExp_Explorer vertex( face, TopAbs_VERTEX );
3577           SMESHDS_SubMesh* vertexSM = meshDS->MeshElements( vertex.Current() );
3578           if ( !vertexSM ) continue;
3579           nodeIt = vertexSM->GetNodes();
3580         }
3581
3582         // find suspicious volumes adjacent to the FACE
3583         vector< const SMDS_MeshNode* >    nOnFace( 4 );
3584         const SMDS_MeshNode*              nInSolid;
3585         //vector< const SMDS_MeshElement* > intersectedFaces;
3586         while ( nodeIt->more() )
3587         {
3588           const SMDS_MeshNode* n     = nodeIt->next();
3589           SMDS_ElemIteratorPtr volIt = n->GetInverseElementIterator( SMDSAbs_Volume );
3590           while ( volIt->more() )
3591           {
3592             const SMDS_MeshElement* vol = volIt->next();
3593             int nbN = vol->NbCornerNodes();
3594             if ( ( nbN != 4 && nbN != 5 )  ||
3595                  !solidSM->Contains( vol ) ||
3596                  !checkedVols.insert( vol ).second )
3597               continue;
3598
3599             // get nodes on FACE and in SOLID of a suspicious volume
3600             nOnFace.clear(); nInSolid = 0;
3601             SMDS_MeshElement::iterator volNode = vol->begin_nodes();
3602             for ( int nb = nbN; nb > 0; ++volNode, --nb )
3603             {
3604               n = *volNode;
3605               if ( n->GetPosition()->GetDim() == 3 )
3606                 nInSolid = n;
3607               else
3608                 nOnFace.push_back( n );
3609             }
3610             if ( !nInSolid || nOnFace.size() != nbN - 1 )
3611               continue;
3612
3613             // get size of the vol
3614             SMESH_TNodeXYZ pInSolid( nInSolid ), pOnFace0( nOnFace[0] );
3615             double volLength = pInSolid.SquareDistance( nOnFace[0] );
3616             for ( size_t i = 1; i < nOnFace.size(); ++i )
3617             {
3618               volLength = Max( volLength, pOnFace0.SquareDistance( nOnFace[i] ));
3619             }
3620
3621             // check if vol is close to concaveFaces
3622             const SMDS_MeshElement* closeFace =
3623               faceSearcher->FindClosestTo( pInSolid, SMDSAbs_Face );
3624             if ( !closeFace ||
3625                  pInSolid.SquareDistance( closeFace->GetNode(0) ) > 4 * volLength )
3626               continue;
3627
3628             // check if vol is distorted, i.e. a medium node is much closer
3629             // to nInSolid than the link middle
3630             bool isDistorted = false;
3631             SMDS_FaceOfNodes onFaceTria( nOnFace[0], nOnFace[1], nOnFace[2] );
3632             if ( !SMESH_Algo::FaceNormal( &onFaceTria, faceNorm, /*normalized=*/false ))
3633               continue;
3634             theHelper.AddTLinks( static_cast< const SMDS_MeshVolume* > ( vol ));
3635             vector< pair< SMESH_TLink, const SMDS_MeshNode* > > links;
3636             for ( size_t i = 0; i < nOnFace.size(); ++i ) // loop on links between nOnFace
3637               for ( size_t j = i+1; j < nOnFace.size(); ++j )
3638               {
3639                 SMESH_TLink link( nOnFace[i], nOnFace[j] );
3640                 TLinkNodeMap::const_iterator linkIt =
3641                   theHelper.GetTLinkNodeMap().find( link );
3642                 if ( linkIt != theHelper.GetTLinkNodeMap().end() )
3643                 {
3644                   links.push_back( make_pair( linkIt->first, linkIt->second  ));
3645                   if ( !isDistorted ) {
3646                     // compare projections of nInSolid and nMedium to face normal
3647                     gp_Pnt pMedium = SMESH_TNodeXYZ( linkIt->second );
3648                     double hMedium = faceNorm * gp_Vec( pOnFace0, pMedium ).XYZ();
3649                     double hVol    = faceNorm * gp_Vec( pOnFace0, pInSolid ).XYZ();
3650                     isDistorted = ( Abs( hMedium ) > Abs( hVol * 0.5 ));
3651                   }
3652                 }
3653               }
3654             // move medium nodes to link middle
3655             if ( isDistorted )
3656             {
3657               for ( size_t i = 0; i < links.size(); ++i )
3658               {
3659                 const SMDS_MeshNode* nMedium = links[i].second;
3660                 if ( movedNodes.insert( nMedium ).second )
3661                 {
3662                   gp_Pnt pMid3D = 0.5 * ( SMESH_TNodeXYZ( links[i].first.node1() ) +
3663                                           SMESH_TNodeXYZ( links[i].first.node2() ));
3664                   meshDS->MoveNode( nMedium, pMid3D.X(), pMid3D.Y(), pMid3D.Z() );
3665                   MSG( "move OUT of solid " << nMedium );
3666                 }
3667               }
3668               theError->myBadElements.push_back( vol );
3669             }
3670           } // loop on volumes sharing a node on FACE
3671         } // loop on nodes on FACE
3672       }  // loop on FACEs of a SOLID
3673
3674       if ( !theError->myBadElements.empty() )
3675         theError->myName = EDITERR_NO_MEDIUM_ON_GEOM;
3676     } // 3D case
3677   }
3678
3679 } //namespace
3680
3681 //=======================================================================
3682 /*!
3683  * \brief Move medium nodes of faces and volumes to fix distorted elements
3684  * \param error - container of fixed distorted elements
3685  * \param volumeOnly - to fix nodes on faces or not, if the shape is solid
3686  * 
3687  * Issue 0020307: EDF 992 SMESH : Linea/Quadratic with Medium Node on Geometry
3688  */
3689 //=======================================================================
3690
3691 void SMESH_MesherHelper::FixQuadraticElements(SMESH_ComputeErrorPtr& compError,
3692                                               bool                   volumeOnly)
3693 {
3694   // setenv NO_FixQuadraticElements to know if FixQuadraticElements() is guilty of bad conversion
3695   if ( getenv("NO_FixQuadraticElements") )
3696     return;
3697
3698   // 0. Apply algorithm to SOLIDs or FACEs
3699   // ----------------------------------------------
3700   if ( myShape.IsNull() ) {
3701     if ( !myMesh->HasShapeToMesh() ) return;
3702     SetSubShape( myMesh->GetShapeToMesh() );
3703
3704 #ifdef _DEBUG_
3705     int nbSolids = 0;
3706     TopTools_IndexedMapOfShape solids;
3707     TopExp::MapShapes(myShape,TopAbs_SOLID,solids);
3708     nbSolids = solids.Extent();
3709 #endif
3710     TopTools_MapOfShape faces; // faces not in solid or in not meshed solid
3711     for ( TopExp_Explorer f(myShape,TopAbs_FACE,TopAbs_SOLID); f.More(); f.Next() ) {
3712       faces.Add( f.Current() ); // not in solid
3713     }
3714     for ( TopExp_Explorer s(myShape,TopAbs_SOLID); s.More(); s.Next() ) {
3715       if ( myMesh->GetSubMesh( s.Current() )->IsEmpty() ) { // get faces of solid
3716         for ( TopExp_Explorer f( s.Current(), TopAbs_FACE); f.More(); f.Next() )
3717           faces.Add( f.Current() ); // in not meshed solid
3718       }
3719       else { // fix nodes in the solid and its faces
3720 #ifdef _DEBUG_
3721         MSG("FIX SOLID " << nbSolids-- << " #" << GetMeshDS()->ShapeToIndex(s.Current()));
3722 #endif
3723         SMESH_MesherHelper h(*myMesh);
3724         h.SetSubShape( s.Current() );
3725         h.ToFixNodeParameters(true);
3726         h.FixQuadraticElements( compError, false );
3727       }
3728     }
3729     // fix nodes on geom faces
3730 #ifdef _DEBUG_
3731     int nbfaces = faces.Extent(); /*avoid "unused varianbles": */ nbfaces++, nbfaces--; 
3732 #endif
3733     for ( TopTools_MapIteratorOfMapOfShape fIt( faces ); fIt.More(); fIt.Next() ) {
3734       MSG("FIX FACE " << nbfaces-- << " #" << GetMeshDS()->ShapeToIndex(fIt.Key()));
3735       SMESH_MesherHelper h(*myMesh);
3736       h.SetSubShape( fIt.Key() );
3737       h.ToFixNodeParameters(true);
3738       h.FixQuadraticElements( compError, true);
3739     }
3740     //perf_print_all_meters(1);
3741     if ( compError && compError->myName == EDITERR_NO_MEDIUM_ON_GEOM )
3742       compError->myComment = "during conversion to quadratic, "
3743         "some medium nodes were not placed on geometry to avoid distorting elements";
3744     return;
3745   }
3746
3747   // 1. Find out type of elements and get iterator on them
3748   // ---------------------------------------------------
3749
3750   SMDS_ElemIteratorPtr elemIt;
3751   SMDSAbs_ElementType elemType = SMDSAbs_All;
3752
3753   SMESH_subMesh* submesh = myMesh->GetSubMeshContaining( myShapeID );
3754   if ( !submesh )
3755     return;
3756   if ( SMESHDS_SubMesh* smDS = submesh->GetSubMeshDS() ) {
3757     elemIt = smDS->GetElements();
3758     if ( elemIt->more() ) {
3759       elemType = elemIt->next()->GetType();
3760       elemIt = smDS->GetElements();
3761     }
3762   }
3763   if ( !elemIt || !elemIt->more() || elemType < SMDSAbs_Face )
3764     return;
3765
3766   // 2. Fill in auxiliary data structures
3767   // ----------------------------------
3768
3769   set< QLink > links;
3770   set< QFace > faces;
3771   set< QLink >::iterator pLink;
3772   set< QFace >::iterator pFace;
3773
3774   bool isCurved = false;
3775   //bool hasRectFaces = false;
3776   //set<int> nbElemNodeSet;
3777   SMDS_VolumeTool volTool;
3778
3779   TIDSortedNodeSet apexOfPyramid;
3780   const int apexIndex = 4;
3781
3782   // Issue 0020982
3783   // Move medium nodes to the link middle for elements whose corner nodes
3784   // are out of geometrical boundary to fix distorted elements.
3785   force3DOutOfBoundary( *this, compError );
3786
3787   if ( elemType == SMDSAbs_Volume )
3788   {
3789     while ( elemIt->more() ) // loop on volumes
3790     {
3791       const SMDS_MeshElement* vol = elemIt->next();
3792       if ( !vol->IsQuadratic() || !volTool.Set( vol ))
3793         return;
3794       double volMinSize2 = -1.;
3795       for ( int iF = 0; iF < volTool.NbFaces(); ++iF ) // loop on faces of volume
3796       {
3797         int nbN = volTool.NbFaceNodes( iF );
3798         //nbElemNodeSet.insert( nbN );
3799         const SMDS_MeshNode** faceNodes = volTool.GetFaceNodes( iF );
3800         vector< const QLink* > faceLinks( nbN/2 );
3801         for ( int iN = 0; iN < nbN; iN += 2 ) // loop on links of a face
3802         {
3803           // store QLink
3804           QLink link( faceNodes[iN], faceNodes[iN+2], faceNodes[iN+1] );
3805           pLink = links.insert( link ).first;
3806           faceLinks[ iN/2 ] = & *pLink;
3807
3808           if ( link.MediumPos() == SMDS_TOP_3DSPACE )
3809           {
3810             if ( !link.IsStraight() )
3811               return; // already fixed
3812           }
3813           else if ( !isCurved )
3814           {
3815             if ( volMinSize2 < 0 ) volMinSize2 = volTool.MinLinearSize2();
3816             isCurved = !isStraightLink( volMinSize2, link._nodeMove.SquareMagnitude() );
3817           }
3818         }
3819         // store QFace
3820         pFace = faces.insert( QFace( faceLinks )).first;
3821         if ( pFace->NbVolumes() == 0 )
3822           pFace->AddSelfToLinks();
3823         pFace->SetVolume( vol );
3824 //         hasRectFaces = hasRectFaces ||
3825 //           ( volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_HEXA ||
3826 //             volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_PENTA );
3827 #ifdef _DEBUG_
3828         if ( nbN == 6 )
3829           pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],faceNodes[4]);
3830         else
3831           pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],
3832                                                faceNodes[4],faceNodes[6] );
3833 #endif
3834       }
3835       // collect pyramid apexes for further correction
3836       if ( vol->NbCornerNodes() == 5 )
3837         apexOfPyramid.insert( vol->GetNode( apexIndex ));
3838     }
3839     set< QLink >::iterator pLink = links.begin();
3840     for ( ; pLink != links.end(); ++pLink )
3841       pLink->SetContinuesFaces();
3842   }
3843   else
3844   {
3845     while ( elemIt->more() ) // loop on faces
3846     {
3847       const SMDS_MeshElement* face = elemIt->next();
3848       if ( !face->IsQuadratic() )
3849         continue;
3850       //nbElemNodeSet.insert( face->NbNodes() );
3851       int nbN = face->NbNodes()/2;
3852       vector< const QLink* > faceLinks( nbN );
3853       for ( int iN = 0; iN < nbN; ++iN ) // loop on links of a face
3854       {
3855         // store QLink
3856         QLink link( face->GetNode(iN), face->GetNode((iN+1)%nbN), face->GetNode(iN+nbN) );
3857         pLink = links.insert( link ).first;
3858         faceLinks[ iN ] = & *pLink;
3859         if ( !isCurved &&
3860              link.node1()->GetPosition()->GetTypeOfPosition() < 2 &&
3861              link.node2()->GetPosition()->GetTypeOfPosition() < 2 )
3862           isCurved = !link.IsStraight();
3863       }
3864       // store QFace
3865       pFace = faces.insert( QFace( faceLinks )).first;
3866       pFace->AddSelfToLinks();
3867       //hasRectFaces = ( hasRectFaces || nbN == 4 );
3868     }
3869   }
3870   if ( !isCurved )
3871     return; // no curved edges of faces
3872
3873   // 3. Compute displacement of medium nodes
3874   // ---------------------------------------
3875
3876   // two loops on QFaces: the first is to treat boundary links, the second is for internal ones
3877   TopLoc_Location loc;
3878   // not treat boundary of volumic submesh
3879   int isInside = ( elemType == SMDSAbs_Volume && volumeOnly ) ? 1 : 0;
3880   for ( ; isInside < 2; ++isInside ) {
3881     MSG( "--------------- LOOP (inside=" << isInside << ") ------------------");
3882     SMDS_TypeOfPosition pos = isInside ? SMDS_TOP_3DSPACE : SMDS_TOP_FACE;
3883     SMDS_TypeOfPosition bndPos = isInside ? SMDS_TOP_FACE : SMDS_TOP_EDGE;
3884
3885     for ( pFace = faces.begin(); pFace != faces.end(); ++pFace ) {
3886       if ( bool(isInside) == pFace->IsBoundary() )
3887         continue;
3888       for ( int dir = 0; dir < 2; ++dir ) // 2 directions of propagation from the quadrangle
3889       {
3890         MSG( "CHAIN");
3891         // make chain of links connected via continues faces
3892         int error = ERR_OK;
3893         TChain rawChain;
3894         if ( !pFace->GetLinkChain( dir, rawChain, pos, error) && error ==ERR_UNKNOWN ) continue;
3895         rawChain.reverse();
3896         if ( !pFace->GetLinkChain( dir+2, rawChain, pos, error ) && error ==ERR_UNKNOWN ) continue;
3897
3898         vector< TChain > chains;
3899         if ( error == ERR_OK ) { // chain contains continues rectangles
3900           chains.resize(1);
3901           chains[0].splice( chains[0].begin(), rawChain );
3902         }
3903         else if ( error == ERR_TRI ) {  // chain contains continues triangles
3904           TSplitTriaResult res = splitTrianglesIntoChains( rawChain, chains, pos );
3905           if ( res != _OK ) { // not quadrangles split into triangles
3906             fixTriaNearBoundary( rawChain, *this );
3907             break;
3908           }
3909         }
3910         else if ( error == ERR_PRISM ) { // quadrangle side faces of prisms
3911           fixPrism( rawChain );
3912           break;
3913         }
3914         else {
3915           continue;
3916         }
3917         for ( int iC = 0; iC < chains.size(); ++iC )
3918         {
3919           TChain& chain = chains[iC];
3920           if ( chain.empty() ) continue;
3921           if ( chain.front().IsStraight() && chain.back().IsStraight() ) {
3922             MSG("3D straight - ignore");
3923             continue;
3924           }
3925           if ( chain.front()->MediumPos() > bndPos ||
3926                chain.back() ->MediumPos() > bndPos ) {
3927             MSG("Internal chain - ignore");
3928             continue;
3929           }
3930           // mesure chain length and compute link position along the chain
3931           double chainLen = 0;
3932           vector< double > linkPos;
3933           MSGBEG( "Link medium nodes: ");
3934           TChain::iterator link0 = chain.begin(), link1 = chain.begin(), link2;
3935           for ( ++link1; link1 != chain.end(); ++link1, ++link0 ) {
3936             MSGBEG( (*link0)->_mediumNode->GetID() << "-" <<(*link1)->_mediumNode->GetID()<<" ");
3937             double len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
3938             while ( len < numeric_limits<double>::min() ) { // remove degenerated link
3939               link1 = chain.erase( link1 );
3940               if ( link1 == chain.end() )
3941                 break;
3942               len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
3943             }
3944             chainLen += len;
3945             linkPos.push_back( chainLen );
3946           }
3947           MSG("");
3948           if ( linkPos.size() < 2 )
3949             continue;
3950
3951           gp_Vec move0 = chain.front()->_nodeMove;
3952           gp_Vec move1 = chain.back ()->_nodeMove;
3953
3954           TopoDS_Face face;
3955           bool checkUV = true;
3956           if ( !isInside )
3957           {
3958             // compute node displacement of end links of chain in parametric space of face
3959             TChainLink& linkOnFace = *(++chain.begin());
3960             const SMDS_MeshNode* nodeOnFace = linkOnFace->_mediumNode;
3961             TopoDS_Shape f = GetSubShapeByNode( nodeOnFace, GetMeshDS() );
3962             if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE )
3963             {
3964               face = TopoDS::Face( f );
3965               Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
3966               bool isStraight[2];
3967               for ( int is1 = 0; is1 < 2; ++is1 ) // move0 or move1
3968               {
3969                 TChainLink& link = is1 ? chain.back() : chain.front();
3970                 gp_XY uvm = GetNodeUV( face, link->_mediumNode, nodeOnFace, &checkUV);
3971                 gp_XY uv1 = GetNodeUV( face, link->node1(), nodeOnFace, &checkUV);
3972                 gp_XY uv2 = GetNodeUV( face, link->node2(), nodeOnFace, &checkUV);
3973                 gp_XY uv12 = GetMiddleUV( surf, uv1, uv2);
3974                 // uvMove = uvm - uv12
3975                 gp_XY uvMove = applyIn2D(surf, uvm, uv12, gp_XY_Subtracted, /*inPeriod=*/false);
3976                 ( is1 ? move1 : move0 ).SetCoord( uvMove.X(), uvMove.Y(), 0 );
3977                 if ( !is1 ) // correct nodeOnFace for move1 (issue 0020919)
3978                   nodeOnFace = (*(++chain.rbegin()))->_mediumNode;
3979                 isStraight[is1] = isStraightLink( (uv2-uv1).SquareModulus(),
3980                                                   10 * uvMove.SquareModulus());
3981               }
3982               if ( isStraight[0] && isStraight[1] ) {
3983                 MSG("2D straight - ignore");
3984                 continue; // straight - no need to move nodes of internal links
3985               }
3986
3987               // check if a chain is already fixed
3988               gp_XY uvm = GetNodeUV( face, linkOnFace->_mediumNode, 0, &checkUV);
3989               gp_XY uv1 = GetNodeUV( face, linkOnFace->node1(), nodeOnFace, &checkUV);
3990               gp_XY uv2 = GetNodeUV( face, linkOnFace->node2(), nodeOnFace, &checkUV);
3991               gp_XY uv12 = GetMiddleUV( surf, uv1, uv2);
3992               if (( uvm - uv12 ).SquareModulus() > 1e-10 )
3993               {
3994                 MSG("Already fixed - ignore");
3995                 continue;
3996               }
3997             }
3998           }
3999           gp_Trsf trsf;
4000           if ( isInside || face.IsNull() )
4001           {
4002             // compute node displacement of end links in their local coord systems
4003             {
4004               TChainLink& ln0 = chain.front(), ln1 = *(++chain.begin());
4005               trsf.SetTransformation( gp_Ax3( gp::Origin(), ln0.Normal(),
4006                                               gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
4007               move0.Transform(trsf);
4008             }
4009             {
4010               TChainLink& ln0 = *(++chain.rbegin()), ln1 = chain.back();
4011               trsf.SetTransformation( gp_Ax3( gp::Origin(), ln1.Normal(),
4012                                               gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
4013               move1.Transform(trsf);
4014             }
4015           }
4016           // compute displacement of medium nodes
4017           link2 = chain.begin();
4018           link0 = link2++;
4019           link1 = link2++;
4020           for ( int i = 0; link2 != chain.end(); ++link0, ++link1, ++link2, ++i )
4021           {
4022             double r = linkPos[i] / chainLen;
4023             // displacement in local coord system
4024             gp_Vec move = (1. - r) * move0 + r * move1;
4025             if ( isInside || face.IsNull()) {
4026               // transform to global
4027               gp_Vec x01( (*link0)->MiddlePnt(), (*link1)->MiddlePnt() );
4028               gp_Vec x12( (*link1)->MiddlePnt(), (*link2)->MiddlePnt() );
4029               gp_Vec x = x01.Normalized() + x12.Normalized();
4030               trsf.SetTransformation( gp_Ax3( gp::Origin(), link1->Normal(), x), gp_Ax3() );
4031               move.Transform(trsf);
4032             }
4033             else {
4034               // compute 3D displacement by 2D one
4035               Handle(Geom_Surface) s = BRep_Tool::Surface(face,loc);
4036               gp_XY oldUV   = GetNodeUV( face, (*link1)->_mediumNode, 0, &checkUV);
4037               gp_XY newUV   = applyIn2D( s, oldUV, gp_XY( move.X(),move.Y()), gp_XY_Added);
4038               gp_Pnt newPnt = s->Value( newUV.X(), newUV.Y());
4039               move = gp_Vec( XYZ((*link1)->_mediumNode), newPnt.Transformed(loc) );
4040 #ifdef _DEBUG_
4041               if ( (XYZ((*link1)->node1()) - XYZ((*link1)->node2())).SquareModulus() <
4042                    move.SquareMagnitude())
4043               {
4044                 gp_XY uv0 = GetNodeUV( face, (*link0)->_mediumNode, 0, &checkUV);
4045                 gp_XY uv2 = GetNodeUV( face, (*link2)->_mediumNode, 0, &checkUV);
4046                 MSG( "TOO LONG MOVE \t" <<
4047                      "uv0: "<<uv0.X()<<", "<<uv0.Y()<<" \t" <<
4048                      "uv2: "<<uv2.X()<<", "<<uv2.Y()<<" \t" <<
4049                      "uvOld: "<<oldUV.X()<<", "<<oldUV.Y()<<" \t" <<
4050                      "newUV: "<<newUV.X()<<", "<<newUV.Y()<<" \t");
4051               }
4052 #endif
4053             }
4054             (*link1)->Move( move );
4055             MSG( "Move " << (*link1)->_mediumNode->GetID() << " following "
4056                  << chain.front()->_mediumNode->GetID() <<"-"
4057                  << chain.back ()->_mediumNode->GetID() <<
4058                  " by " << move.Magnitude());
4059           }
4060         } // loop on chains of links
4061       } // loop on 2 directions of propagation from quadrangle
4062     } // loop on faces
4063   } // fix faces and/or volumes
4064
4065   // 4. Move nodes
4066   // -------------
4067
4068   for ( pLink = links.begin(); pLink != links.end(); ++pLink ) {
4069     if ( pLink->IsMoved() ) {
4070       gp_Pnt p = pLink->MiddlePnt() + pLink->Move();
4071       GetMeshDS()->MoveNode( pLink->_mediumNode, p.X(), p.Y(), p.Z());
4072     }
4073   }
4074
4075   // Issue 0020982
4076   // Move the apex of pyramid together with the most curved link.
4077   // TIDSortedNodeSet::iterator apexIt = apexOfPyramid.begin();
4078   // for ( ; apexIt != apexOfPyramid.end(); ++apexIt )
4079   // {
4080   //   SMESH_TNodeXYZ apex = *apexIt;
4081
4082   //   gp_Vec maxMove( 0,0,0 );
4083   //   double maxMoveSize2 = 0;
4084
4085   //   // shift of node index to get medium nodes between the base nodes
4086   //   const int base2MediumShift = 5;
4087
4088   //   // find maximal movement of medium node
4089   //   SMDS_ElemIteratorPtr volIt = apex._node->GetInverseElementIterator( SMDSAbs_Volume );
4090   //   vector< const SMDS_MeshElement* > pyramids;
4091   //   while ( volIt->more() )
4092   //   {
4093   //     const SMDS_MeshElement* pyram = volIt->next();
4094   //     if ( pyram->GetEntityType() != SMDSEntity_Quad_Pyramid ) continue;
4095   //     pyramids.push_back( pyram );
4096
4097   //     for ( int iBase = 0; iBase < apexIndex; ++iBase )
4098   //     {
4099   //       SMESH_TNodeXYZ medium = pyram->GetNode( iBase + base2MediumShift );
4100   //       if ( medium._node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE )
4101   //       {
4102   //         SMESH_TNodeXYZ n1 = pyram->GetNode( iBase );
4103   //         SMESH_TNodeXYZ n2 = pyram->GetNode( ( iBase+1 ) % 4 );
4104   //         gp_Pnt middle = 0.5 * ( n1 + n2 );
4105   //         gp_Vec move( middle, medium );
4106   //         double moveSize2 = move.SquareMagnitude();
4107   //         if ( moveSize2 > maxMoveSize2 )
4108   //           maxMove = move, maxMoveSize2 = moveSize2;
4109   //       }
4110   //     }
4111   //   }
4112
4113   //   // move the apex
4114   //   if ( maxMoveSize2 > 1e-20 )
4115   //   {
4116   //     apex += maxMove.XYZ();
4117   //     GetMeshDS()->MoveNode( apex._node, apex.X(), apex.Y(), apex.Z());
4118
4119   //     // move medium nodes neighboring the apex to the middle
4120   //     const int base2MediumShift_2 = 9;
4121   //     for ( unsigned i = 0; i < pyramids.size(); ++i )
4122   //       for ( int iBase = 0; iBase < apexIndex; ++iBase )
4123   //       {
4124   //         SMESH_TNodeXYZ         base = pyramids[i]->GetNode( iBase );
4125   //         const SMDS_MeshNode* medium = pyramids[i]->GetNode( iBase + base2MediumShift_2 );
4126   //         gp_XYZ middle = 0.5 * ( apex + base );
4127   //         GetMeshDS()->MoveNode( medium, middle.X(), middle.Y(), middle.Z());
4128   //       }
4129   //   }
4130   // }
4131 }
4132