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