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