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