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