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