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