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