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