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