Salome HOME
0021231: EDF 1838 SMESH: Pattern mapping on a quadratic element
[modules/smesh.git] / src / SMESH / SMESH_MesherHelper.cxx
1 //  Copyright (C) 2007-2010  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_FacePosition.hxx" 
30 #include "SMDS_EdgePosition.hxx"
31 #include "SMDS_VolumeTool.hxx"
32 #include "SMESH_subMesh.hxx"
33 #include "SMESH_ProxyMesh.hxx"
34
35 #include <BRepAdaptor_Surface.hxx>
36 #include <BRepTools.hxx>
37 #include <BRepTools_WireExplorer.hxx>
38 #include <BRep_Tool.hxx>
39 #include <Geom2d_Curve.hxx>
40 #include <GeomAPI_ProjectPointOnCurve.hxx>
41 #include <GeomAPI_ProjectPointOnSurf.hxx>
42 #include <Geom_Curve.hxx>
43 #include <Geom_Surface.hxx>
44 #include <ShapeAnalysis.hxx>
45 #include <TopExp.hxx>
46 #include <TopExp_Explorer.hxx>
47 #include <TopTools_ListIteratorOfListOfShape.hxx>
48 #include <TopTools_MapIteratorOfMapOfShape.hxx>
49 #include <TopTools_MapOfShape.hxx>
50 #include <TopoDS.hxx>
51 #include <gp_Ax3.hxx>
52 #include <gp_Pnt2d.hxx>
53 #include <gp_Trsf.hxx>
54
55 #include <Standard_Failure.hxx>
56 #include <Standard_ErrorHandler.hxx>
57
58 #include <utilities.h>
59
60 #include <limits>
61
62 using namespace std;
63
64 #define RETURN_BAD_RESULT(msg) { MESSAGE(msg); return false; }
65
66 namespace {
67
68   gp_XYZ XYZ(const SMDS_MeshNode* n) { return gp_XYZ(n->X(), n->Y(), n->Z()); }
69
70   enum { U_periodic = 1, V_periodic = 2 };
71 }
72
73 //================================================================================
74 /*!
75  * \brief Constructor
76  */
77 //================================================================================
78
79 SMESH_MesherHelper::SMESH_MesherHelper(SMESH_Mesh& theMesh)
80   : myParIndex(0), myMesh(&theMesh), myShapeID(0), myCreateQuadratic(false)
81 {
82   myPar1[0] = myPar2[0] = myPar1[1] = myPar2[1] = 0;
83   mySetElemOnShape = ( ! myMesh->HasShapeToMesh() );
84 }
85
86 //=======================================================================
87 //function : ~SMESH_MesherHelper
88 //purpose  : 
89 //=======================================================================
90
91 SMESH_MesherHelper::~SMESH_MesherHelper()
92 {
93   {
94     TID2ProjectorOnSurf::iterator i_proj = myFace2Projector.begin();
95     for ( ; i_proj != myFace2Projector.end(); ++i_proj )
96       delete i_proj->second;
97   }
98   {
99     TID2ProjectorOnCurve::iterator i_proj = myEdge2Projector.begin();
100     for ( ; i_proj != myEdge2Projector.end(); ++i_proj )
101       delete i_proj->second;
102   }
103 }
104
105 //=======================================================================
106 //function : IsQuadraticSubMesh
107 //purpose  : Check submesh for given shape: if all elements on this shape 
108 //           are quadratic, quadratic elements will be created.
109 //           Also fill myTLinkNodeMap
110 //=======================================================================
111
112 bool SMESH_MesherHelper::IsQuadraticSubMesh(const TopoDS_Shape& aSh)
113 {
114   SMESHDS_Mesh* meshDS = GetMeshDS();
115   // we can create quadratic elements only if all elements
116   // created on subshapes of given shape are quadratic
117   // also we have to fill myTLinkNodeMap
118   myCreateQuadratic = true;
119   mySeamShapeIds.clear();
120   myDegenShapeIds.clear();
121   TopAbs_ShapeEnum subType( aSh.ShapeType()==TopAbs_FACE ? TopAbs_EDGE : TopAbs_FACE );
122   SMDSAbs_ElementType elemType( subType==TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
123
124   int nbOldLinks = myTLinkNodeMap.size();
125
126   TopExp_Explorer exp( aSh, subType );
127   for (; exp.More() && myCreateQuadratic; exp.Next()) {
128     if ( SMESHDS_SubMesh * subMesh = meshDS->MeshElements( exp.Current() )) {
129       if ( SMDS_ElemIteratorPtr it = subMesh->GetElements() ) {
130         while(it->more()) {
131           const SMDS_MeshElement* e = it->next();
132           if ( e->GetType() != elemType || !e->IsQuadratic() ) {
133             myCreateQuadratic = false;
134             break;
135           }
136           else {
137             // fill TLinkNodeMap
138             switch ( e->NbNodes() ) {
139             case 3:
140               AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(2)); break;
141             case 6:
142               AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(3));
143               AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(4));
144               AddTLinkNode(e->GetNode(2),e->GetNode(0),e->GetNode(5)); break;
145             case 8:
146               AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(4));
147               AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(5));
148               AddTLinkNode(e->GetNode(2),e->GetNode(3),e->GetNode(6));
149               AddTLinkNode(e->GetNode(3),e->GetNode(0),e->GetNode(7));
150               break;
151             default:
152               myCreateQuadratic = false;
153               break;
154             }
155           }
156         }
157       }
158     }
159   }
160
161   if ( nbOldLinks == myTLinkNodeMap.size() )
162     myCreateQuadratic = false;
163
164   if(!myCreateQuadratic) {
165     myTLinkNodeMap.clear();
166   }
167   SetSubShape( aSh );
168
169   return myCreateQuadratic;
170 }
171
172 //=======================================================================
173 //function : SetSubShape
174 //purpose  : Set geomerty to make elements on
175 //=======================================================================
176
177 void SMESH_MesherHelper::SetSubShape(const int aShID)
178 {
179   if ( aShID == myShapeID )
180     return;
181   if ( aShID > 1 )
182     SetSubShape( GetMeshDS()->IndexToShape( aShID ));
183   else
184     SetSubShape( TopoDS_Shape() );
185 }
186
187 //=======================================================================
188 //function : SetSubShape
189 //purpose  : Set geomerty to create elements on
190 //=======================================================================
191
192 void SMESH_MesherHelper::SetSubShape(const TopoDS_Shape& aSh)
193 {
194   if ( myShape.IsSame( aSh ))
195     return;
196
197   myShape = aSh;
198   mySeamShapeIds.clear();
199   myDegenShapeIds.clear();
200
201   if ( myShape.IsNull() ) {
202     myShapeID  = 0;
203     return;
204   }
205   SMESHDS_Mesh* meshDS = GetMeshDS();
206   myShapeID = meshDS->ShapeToIndex(aSh);
207   myParIndex = 0;
208
209   // treatment of periodic faces
210   for ( TopExp_Explorer eF( aSh, TopAbs_FACE ); eF.More(); eF.Next() )
211   {
212     const TopoDS_Face& face = TopoDS::Face( eF.Current() );
213     BRepAdaptor_Surface surface( face );
214     if ( surface.IsUPeriodic() || surface.IsVPeriodic() )
215     {
216       for (TopExp_Explorer exp( face, TopAbs_EDGE ); exp.More(); exp.Next())
217       {
218         // look for a seam edge
219         const TopoDS_Edge& edge = TopoDS::Edge( exp.Current() );
220         if ( BRep_Tool::IsClosed( edge, face )) {
221           // initialize myPar1, myPar2 and myParIndex
222           gp_Pnt2d uv1, uv2;
223           BRep_Tool::UVPoints( edge, face, uv1, uv2 );
224           if ( Abs( uv1.Coord(1) - uv2.Coord(1) ) < Abs( uv1.Coord(2) - uv2.Coord(2) ))
225           {
226             myParIndex |= U_periodic;
227             myPar1[0] = surface.FirstUParameter();
228             myPar2[0] = surface.LastUParameter();
229           }
230           else {
231             myParIndex |= V_periodic;
232             myPar1[1] = surface.FirstVParameter();
233             myPar2[1] = surface.LastVParameter();
234           }
235           // store seam shape indices, negative if shape encounters twice
236           int edgeID = meshDS->ShapeToIndex( edge );
237           mySeamShapeIds.insert( IsSeamShape( edgeID ) ? -edgeID : edgeID );
238           for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() ) {
239             int vertexID = meshDS->ShapeToIndex( v.Current() );
240             mySeamShapeIds.insert( IsSeamShape( vertexID ) ? -vertexID : vertexID );
241           }
242         }
243
244         // look for a degenerated edge
245         if ( BRep_Tool::Degenerated( edge )) {
246           myDegenShapeIds.insert( meshDS->ShapeToIndex( edge ));
247           for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() )
248             myDegenShapeIds.insert( meshDS->ShapeToIndex( v.Current() ));
249         }
250       }
251     }
252   }
253 }
254
255 //=======================================================================
256 //function : GetNodeUVneedInFaceNode
257 //purpose  : Check if inFaceNode argument is necessary for call GetNodeUV(F,..)
258 //           Return true if the face is periodic.
259 //           If F is Null, answer about subshape set through IsQuadraticSubMesh() or
260 //           * SetSubShape()
261 //=======================================================================
262
263 bool SMESH_MesherHelper::GetNodeUVneedInFaceNode(const TopoDS_Face& F) const
264 {
265   if ( F.IsNull() ) return !mySeamShapeIds.empty();
266
267   if ( !F.IsNull() && !myShape.IsNull() && myShape.IsSame( F ))
268     return !mySeamShapeIds.empty();
269
270   TopLoc_Location loc;
271   Handle(Geom_Surface) aSurface = BRep_Tool::Surface( F,loc );
272   if ( !aSurface.IsNull() )
273     return ( aSurface->IsUPeriodic() || aSurface->IsVPeriodic() );
274
275   return false;
276 }
277
278 //=======================================================================
279 //function : IsMedium
280 //purpose  : 
281 //=======================================================================
282
283 bool SMESH_MesherHelper::IsMedium(const SMDS_MeshNode*      node,
284                                   const SMDSAbs_ElementType typeToCheck)
285 {
286   return SMESH_MeshEditor::IsMedium( node, typeToCheck );
287 }
288
289 //=======================================================================
290 //function : GetSubShapeByNode
291 //purpose  : Return support shape of a node
292 //=======================================================================
293
294 TopoDS_Shape SMESH_MesherHelper::GetSubShapeByNode(const SMDS_MeshNode* node,
295                                                    const SMESHDS_Mesh*  meshDS)
296 {
297   int shapeID = node->getshapeId();
298   if ( 0 < shapeID && shapeID <= meshDS->MaxShapeIndex() )
299     return meshDS->IndexToShape( shapeID );
300   else
301     return TopoDS_Shape();
302 }
303
304
305 //=======================================================================
306 //function : AddTLinkNode
307 //purpose  : add a link in my data structure
308 //=======================================================================
309
310 void SMESH_MesherHelper::AddTLinkNode(const SMDS_MeshNode* n1,
311                                       const SMDS_MeshNode* n2,
312                                       const SMDS_MeshNode* n12)
313 {
314   // add new record to map
315   SMESH_TLink link( n1, n2 );
316   myTLinkNodeMap.insert( make_pair(link,n12));
317 }
318
319 //================================================================================
320 /*!
321  * \brief Add quadratic links of edge to own data structure
322  */
323 //================================================================================
324
325 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshEdge* edge)
326 {
327   if ( edge->IsQuadratic() )
328     AddTLinkNode(edge->GetNode(0), edge->GetNode(1), edge->GetNode(2));
329 }
330
331 //================================================================================
332 /*!
333  * \brief Add quadratic links of face to own data structure
334  */
335 //================================================================================
336
337 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshFace* face)
338 {
339   if ( face->IsQuadratic() )
340   {
341     const int nbLinks = face->NbCornerNodes();
342     for ( int i = 0; i < nbLinks; ++i )
343     {
344       const SMDS_MeshNode* n1  = face->GetNode( i );
345       const SMDS_MeshNode* n2  = face->GetNode(( i + 1 ) % nbLinks );
346       const SMDS_MeshNode* n12 = face->GetNode( i + nbLinks );
347       AddTLinkNode( n1, n2, n12 );
348     }
349   }
350 }
351
352 //================================================================================
353 /*!
354  * \brief Add quadratic links of volume to own data structure
355  */
356 //================================================================================
357
358 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshVolume* volume)
359 {
360   if ( volume->IsQuadratic() )
361   {
362     SMDS_VolumeTool vTool( volume );
363     const SMDS_MeshNode** nodes = vTool.GetNodes();
364     set<int> addedLinks;
365     for ( int iF = 1; iF < vTool.NbFaces(); ++iF )
366     {
367       const int nbN = vTool.NbFaceNodes( iF );
368       const int* iNodes = vTool.GetFaceNodesIndices( iF );
369       for ( int i = 0; i < nbN; )
370       {
371         int iN1  = iNodes[i++];
372         int iN12 = iNodes[i++];
373         int iN2  = iNodes[i++];
374         if ( iN1 > iN2 ) std::swap( iN1, iN2 );
375         int linkID = iN1 * vTool.NbNodes() + iN2;
376         pair< set<int>::iterator, bool > it_isNew = addedLinks.insert( linkID );
377         if ( it_isNew.second )
378           AddTLinkNode( nodes[iN1], nodes[iN2], nodes[iN12] );
379         else
380           addedLinks.erase( it_isNew.first ); // each link encounters only twice
381       }
382     }
383   }
384 }
385
386 //================================================================================
387 /*!
388  * \brief Return true if position of nodes on the shape hasn't yet been checked or
389  * the positions proved to be invalid
390  */
391 //================================================================================
392
393 bool SMESH_MesherHelper::toCheckPosOnShape(int shapeID ) const
394 {
395   map< int,bool >::const_iterator id_ok = myNodePosShapesValidity.find( shapeID );
396   return ( id_ok == myNodePosShapesValidity.end() || !id_ok->second );
397 }
398
399 //================================================================================
400 /*!
401  * \brief Set validity of positions of nodes on the shape.
402  * Once set, validity is not changed
403  */
404 //================================================================================
405
406 void SMESH_MesherHelper::setPosOnShapeValidity(int shapeID, bool ok ) const
407 {
408   ((SMESH_MesherHelper*)this)->myNodePosShapesValidity.insert( make_pair( shapeID, ok));
409 }
410
411 //=======================================================================
412 //function : GetUVOnSeam
413 //purpose  : Select UV on either of 2 pcurves of a seam edge, closest to the given UV
414 //=======================================================================
415
416 gp_Pnt2d SMESH_MesherHelper::GetUVOnSeam( const gp_Pnt2d& uv1, const gp_Pnt2d& uv2 ) const
417 {
418   gp_Pnt2d result = uv1;
419   for ( int i = U_periodic; i <= V_periodic ; ++i )
420   {
421     if ( myParIndex & i )
422     {
423       double p1 = uv1.Coord( i );
424       double dp1 = Abs( p1-myPar1[i-1]), dp2 = Abs( p1-myPar2[i-1]);
425       if ( myParIndex == i ||
426            dp1 < ( myPar2[i-1] - myPar2[i-1] ) / 100. ||
427            dp2 < ( myPar2[i-1] - myPar2[i-1] ) / 100. )
428       {
429         double p2 = uv2.Coord( i );
430         double p1Alt = ( dp1 < dp2 ) ? myPar2[i-1] : myPar1[i-1];
431         if ( Abs( p2 - p1 ) > Abs( p2 - p1Alt ))
432           result.SetCoord( i, p1Alt );
433       }
434     }
435   }
436   return result;
437 }
438
439 //=======================================================================
440 //function : GetNodeUV
441 //purpose  : Return node UV on face
442 //=======================================================================
443
444 gp_XY SMESH_MesherHelper::GetNodeUV(const TopoDS_Face&   F,
445                                     const SMDS_MeshNode* n,
446                                     const SMDS_MeshNode* n2,
447                                     bool*                check) const
448 {
449   gp_Pnt2d uv( Precision::Infinite(), Precision::Infinite() );
450   const SMDS_PositionPtr Pos = n->GetPosition();
451   bool uvOK = false;
452   if(Pos->GetTypeOfPosition()==SMDS_TOP_FACE)
453   {
454     // node has position on face
455     const SMDS_FacePosition* fpos =
456       static_cast<const SMDS_FacePosition*>(n->GetPosition());
457     uv.SetCoord(fpos->GetUParameter(),fpos->GetVParameter());
458     if ( check )
459       uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ));
460   }
461   else if(Pos->GetTypeOfPosition()==SMDS_TOP_EDGE)
462   {
463     // node has position on edge => it is needed to find
464     // corresponding edge from face, get pcurve for this
465     // edge and retrieve value from this pcurve
466     const SMDS_EdgePosition* epos =
467       static_cast<const SMDS_EdgePosition*>(n->GetPosition());
468     int edgeID = n->getshapeId();
469     TopoDS_Edge E = TopoDS::Edge(GetMeshDS()->IndexToShape(edgeID));
470     double f, l, u = epos->GetUParameter();
471     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, F, f, l);
472     bool validU = ( f < u && u < l );
473     if ( validU )
474       uv = C2d->Value( u );
475     else
476       uv.SetCoord( Precision::Infinite(),0.);
477     if ( check || !validU )
478       uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ),/*force=*/ !validU );
479
480     // for a node on a seam edge select one of UVs on 2 pcurves
481     if ( n2 && IsSeamShape( edgeID ) )
482     {
483       uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0, check ));
484     }
485     else
486     { // adjust uv to period
487       TopLoc_Location loc;
488       Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
489       Standard_Boolean isUPeriodic = S->IsUPeriodic();
490       Standard_Boolean isVPeriodic = S->IsVPeriodic();
491       if ( isUPeriodic || isVPeriodic ) {
492         Standard_Real UF,UL,VF,VL;
493         S->Bounds(UF,UL,VF,VL);
494         if(isUPeriodic)
495           uv.SetX( uv.X() + ShapeAnalysis::AdjustToPeriod(uv.X(),UF,UL));
496         if(isVPeriodic)
497           uv.SetY( uv.Y() + ShapeAnalysis::AdjustToPeriod(uv.Y(),VF,VL));
498       }
499     }
500   }
501   else if(Pos->GetTypeOfPosition()==SMDS_TOP_VERTEX)
502   {
503     if ( int vertexID = n->getshapeId() ) {
504       const TopoDS_Vertex& V = TopoDS::Vertex(GetMeshDS()->IndexToShape(vertexID));
505       try {
506         uv = BRep_Tool::Parameters( V, F );
507         uvOK = true;
508       }
509       catch (Standard_Failure& exc) {
510       }
511       if ( !uvOK ) {
512         for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() )
513           uvOK = ( V == vert.Current() );
514         if ( !uvOK ) {
515 #ifdef _DEBUG_
516           MESSAGE ( "SMESH_MesherHelper::GetNodeUV(); Vertex " << vertexID
517                << " not in face " << GetMeshDS()->ShapeToIndex( F ) );
518 #endif
519           // get UV of a vertex closest to the node
520           double dist = 1e100;
521           gp_Pnt pn = XYZ( n );
522           for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() ) {
523             TopoDS_Vertex curV = TopoDS::Vertex( vert.Current() );
524             gp_Pnt p = BRep_Tool::Pnt( curV );
525             double curDist = p.SquareDistance( pn );
526             if ( curDist < dist ) {
527               dist = curDist;
528               uv = BRep_Tool::Parameters( curV, F );
529               uvOK = ( dist < DBL_MIN );
530             }
531           }
532         }
533         else {
534           uvOK = false;
535           TopTools_ListIteratorOfListOfShape it( myMesh->GetAncestors( V ));
536           for ( ; it.More(); it.Next() ) {
537             if ( it.Value().ShapeType() == TopAbs_EDGE ) {
538               const TopoDS_Edge & edge = TopoDS::Edge( it.Value() );
539               double f,l;
540               Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(edge, F, f, l);
541               if ( !C2d.IsNull() ) {
542                 double u = ( V == TopExp::FirstVertex( edge ) ) ?  f : l;
543                 uv = C2d->Value( u );
544                 uvOK = true;
545                 break;
546               }
547             }
548           }
549         }
550       }
551       if ( n2 && IsSeamShape( vertexID ) )
552         uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
553     }
554   }
555   else
556   {
557     uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ));
558   }
559
560   if ( check )
561     *check = uvOK;
562
563   return uv.XY();
564 }
565
566 //=======================================================================
567 //function : CheckNodeUV
568 //purpose  : Check and fix node UV on a face
569 //=======================================================================
570
571 bool SMESH_MesherHelper::CheckNodeUV(const TopoDS_Face&   F,
572                                      const SMDS_MeshNode* n,
573                                      gp_XY&               uv,
574                                      const double         tol,
575                                      const bool           force,
576                                      double               distXYZ[4]) const
577 {
578   int shapeID = n->getshapeId();
579   bool infinit = ( Precision::IsInfinite( uv.X() ) || Precision::IsInfinite( uv.Y() ));
580   if ( force || toCheckPosOnShape( shapeID ) || infinit )
581   {
582     // check that uv is correct
583     TopLoc_Location loc;
584     Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
585     gp_Pnt nodePnt = XYZ( n ), surfPnt(0,0,0);
586     double dist = 0;
587     if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
588     if ( infinit ||
589          (dist = nodePnt.Distance( surfPnt = surface->Value( uv.X(), uv.Y() ))) > tol )
590     {
591       setPosOnShapeValidity( shapeID, false );
592       if ( !infinit && distXYZ ) {
593         surfPnt.Transform( loc );
594         distXYZ[0] = dist;
595         distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
596       }
597       // uv incorrect, project the node to surface
598       GeomAPI_ProjectPointOnSurf& projector = GetProjector( F, loc, tol );
599       projector.Perform( nodePnt );
600       if ( !projector.IsDone() || projector.NbPoints() < 1 )
601       {
602         MESSAGE( "SMESH_MesherHelper::CheckNodeUV() failed to project" );
603         return false;
604       }
605       Quantity_Parameter U,V;
606       projector.LowerDistanceParameters(U,V);
607       uv.SetCoord( U,V );
608       surfPnt = surface->Value( U, V );
609       dist = nodePnt.Distance( surfPnt );
610       if ( distXYZ ) {
611         surfPnt.Transform( loc );
612         distXYZ[0] = dist;
613         distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
614       }
615       if ( dist > tol )
616       {
617         MESSAGE( "SMESH_MesherHelper::CheckNodeUV(), invalid projection" );
618         return false;
619       }
620       // store the fixed UV on the face
621       if ( myShape.IsSame(F) && shapeID == myShapeID )
622         const_cast<SMDS_MeshNode*>(n)->SetPosition
623           ( SMDS_PositionPtr( new SMDS_FacePosition( U, V )));
624     }
625     else if ( uv.Modulus() > numeric_limits<double>::min() )
626     {
627       setPosOnShapeValidity( shapeID, true );
628     }
629   }
630   return true;
631 }
632
633 //=======================================================================
634 //function : GetProjector
635 //purpose  : Return projector intitialized by given face without location, which is returned
636 //=======================================================================
637
638 GeomAPI_ProjectPointOnSurf& SMESH_MesherHelper::GetProjector(const TopoDS_Face& F,
639                                                              TopLoc_Location&   loc,
640                                                              double             tol ) const
641 {
642   Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
643   int faceID = GetMeshDS()->ShapeToIndex( F );
644   TID2ProjectorOnSurf& i2proj = const_cast< TID2ProjectorOnSurf&>( myFace2Projector );
645   TID2ProjectorOnSurf::iterator i_proj = i2proj.find( faceID );
646   if ( i_proj == i2proj.end() )
647   {
648     if ( tol == 0 ) tol = BRep_Tool::Tolerance( F );
649     double U1, U2, V1, V2;
650     surface->Bounds(U1, U2, V1, V2);
651     GeomAPI_ProjectPointOnSurf* proj = new GeomAPI_ProjectPointOnSurf();
652     proj->Init( surface, U1, U2, V1, V2, tol );
653     i_proj = i2proj.insert( make_pair( faceID, proj )).first;
654   }
655   return *( i_proj->second );
656 }
657
658 namespace
659 {
660   gp_XY AverageUV(const gp_XY& uv1, const gp_XY& uv2) { return ( uv1 + uv2 ) / 2.; }
661   gp_XY_FunPtr(Added); // define gp_XY_Added pointer to function calling gp_XY::Added(gp_XY)
662   gp_XY_FunPtr(Subtracted); 
663 }
664
665 //=======================================================================
666 //function : applyIn2D
667 //purpose  : Perform given operation on two 2d points in parameric space of given surface.
668 //           It takes into account period of the surface. Use gp_XY_FunPtr macro
669 //           to easily define pointer to function of gp_XY class.
670 //=======================================================================
671
672 gp_XY SMESH_MesherHelper::applyIn2D(const Handle(Geom_Surface)& surface,
673                                     const gp_XY&                uv1,
674                                     const gp_XY&                uv2,
675                                     xyFunPtr                    fun,
676                                     const bool                  resultInPeriod)
677 {
678   Standard_Boolean isUPeriodic = surface.IsNull() ? false : surface->IsUPeriodic();
679   Standard_Boolean isVPeriodic = surface.IsNull() ? false : surface->IsVPeriodic();
680   if ( !isUPeriodic && !isVPeriodic )
681     return fun(uv1,uv2);
682
683   // move uv2 not far than half-period from uv1
684   double u2 = 
685     uv2.X()+(isUPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.X(),uv1.X(),surface->UPeriod()) :0);
686   double v2 = 
687     uv2.Y()+(isVPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.Y(),uv1.Y(),surface->VPeriod()) :0);
688
689   // execute operation
690   gp_XY res = fun( uv1, gp_XY(u2,v2) );
691
692   // move result within period
693   if ( resultInPeriod )
694   {
695     Standard_Real UF,UL,VF,VL;
696     surface->Bounds(UF,UL,VF,VL);
697     if ( isUPeriodic )
698       res.SetX( res.X() + ShapeAnalysis::AdjustToPeriod(res.X(),UF,UL));
699     if ( isVPeriodic )
700       res.SetY( res.Y() + ShapeAnalysis::AdjustToPeriod(res.Y(),VF,VL));
701   }
702
703   return res;
704 }
705 //=======================================================================
706 //function : GetMiddleUV
707 //purpose  : Return middle UV taking in account surface period
708 //=======================================================================
709
710 gp_XY SMESH_MesherHelper::GetMiddleUV(const Handle(Geom_Surface)& surface,
711                                       const gp_XY&                p1,
712                                       const gp_XY&                p2)
713 {
714   return applyIn2D( surface, p1, p2, & AverageUV );
715 }
716
717 //=======================================================================
718 //function : GetNodeU
719 //purpose  : Return node U on edge
720 //=======================================================================
721
722 double SMESH_MesherHelper::GetNodeU(const TopoDS_Edge&   E,
723                                     const SMDS_MeshNode* n,
724                                     const SMDS_MeshNode* inEdgeNode,
725                                     bool*                check)
726 {
727   double param = 0;
728   const SMDS_PositionPtr pos = n->GetPosition();
729   if ( pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
730   {
731     const SMDS_EdgePosition* epos = static_cast<const SMDS_EdgePosition*>( pos );
732     param =  epos->GetUParameter();
733   }
734   else if( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX )
735   {
736     if ( inEdgeNode && TopExp::FirstVertex( E ).IsSame( TopExp::LastVertex( E ))) // issue 0020128
737     {
738       Standard_Real f,l;
739       BRep_Tool::Range( E, f,l );
740       double uInEdge = GetNodeU( E, inEdgeNode );
741       param = ( fabs( uInEdge - f ) < fabs( l - uInEdge )) ? f : l;
742     }
743     else
744     {
745       SMESHDS_Mesh * meshDS = GetMeshDS();
746       int vertexID = n->getshapeId();
747       const TopoDS_Vertex& V = TopoDS::Vertex(meshDS->IndexToShape(vertexID));
748       param =  BRep_Tool::Parameter( V, E );
749     }
750   }
751   if ( check )
752   {
753     double tol = BRep_Tool::Tolerance( E );
754     double f,l;  BRep_Tool::Range( E, f,l );
755     bool force = ( param < f-tol || param > l+tol );
756     if ( !force && pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
757       force = ( GetMeshDS()->ShapeToIndex( E ) != n->getshapeId() );
758
759     *check = CheckNodeU( E, n, param, 2*tol, force );
760   }
761   return param;
762 }
763
764 //=======================================================================
765 //function : CheckNodeU
766 //purpose  : Check and fix node U on an edge
767 //           Return false if U is bad and could not be fixed
768 //=======================================================================
769
770 bool SMESH_MesherHelper::CheckNodeU(const TopoDS_Edge&   E,
771                                     const SMDS_MeshNode* n,
772                                     double&              u,
773                                     const double         tol,
774                                     const bool           force,
775                                     double               distXYZ[4]) const
776 {
777   int shapeID = n->getshapeId();
778   if ( force || toCheckPosOnShape( shapeID ))
779   {
780     TopLoc_Location loc; double f,l;
781     Handle(Geom_Curve) curve = BRep_Tool::Curve( E,loc,f,l );
782     if ( curve.IsNull() ) // degenerated edge
783     {
784       if ( u+tol < f || u-tol > l )
785       {
786         double r = Max( 0.5, 1 - tol*n->GetID()); // to get a unique u on edge
787         u =  f*r + l*(1-r);
788       }
789     }
790     else
791     {
792       gp_Pnt nodePnt = SMESH_TNodeXYZ( n );
793       if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
794       gp_Pnt curvPnt = curve->Value( u );
795       double dist = nodePnt.Distance( curvPnt );
796       if ( distXYZ ) {
797         curvPnt.Transform( loc );
798         distXYZ[0] = dist;
799         distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
800       }
801       if ( dist > tol )
802       {
803         setPosOnShapeValidity( shapeID, false );
804         // u incorrect, project the node to the curve
805         int edgeID = GetMeshDS()->ShapeToIndex( E );
806         TID2ProjectorOnCurve& i2proj = const_cast< TID2ProjectorOnCurve&>( myEdge2Projector );
807         TID2ProjectorOnCurve::iterator i_proj =
808           i2proj.insert( make_pair( edgeID, (GeomAPI_ProjectPointOnCurve*) 0 )).first;
809         if ( !i_proj->second  )
810         {
811           i_proj->second = new GeomAPI_ProjectPointOnCurve();
812           i_proj->second->Init( curve, f, l );
813         }
814         GeomAPI_ProjectPointOnCurve* projector = i_proj->second;
815         projector->Perform( nodePnt );
816         if ( projector->NbPoints() < 1 )
817         {
818           MESSAGE( "SMESH_MesherHelper::CheckNodeU() failed to project" );
819           return false;
820         }
821         Quantity_Parameter U = projector->LowerDistanceParameter();
822         u = double( U );
823         curvPnt = curve->Value( u );
824         dist = nodePnt.Distance( curvPnt );
825         if ( distXYZ ) {
826           curvPnt.Transform( loc );
827           distXYZ[0] = dist;
828           distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
829         }
830         if ( dist > tol )
831         {
832           MESSAGE( "SMESH_MesherHelper::CheckNodeU(), invalid projection" );
833           MESSAGE("distance " << dist << " " << tol );
834           return false;
835         }
836         // store the fixed U on the edge
837         if ( myShape.IsSame(E) && shapeID == myShapeID )
838           const_cast<SMDS_MeshNode*>(n)->SetPosition
839             ( SMDS_PositionPtr( new SMDS_EdgePosition( U )));
840       }
841       else if ( fabs( u ) > numeric_limits<double>::min() )
842       {
843         setPosOnShapeValidity( shapeID, true );
844       }
845       if (( u < f-tol || u > l+tol ) && force )
846       {
847         // node is on vertex but is set on periodic but trimmed edge (issue 0020890)
848         try
849         {
850           // do not use IsPeriodic() as Geom_TrimmedCurve::IsPeriodic () returns false
851           double period = curve->Period();
852           u = ( u < f ) ? u + period : u - period;
853         }
854         catch (Standard_Failure& exc)
855         {
856           return false;
857         }
858       }
859     }
860   }
861   return true;
862 }
863
864 //=======================================================================
865 //function : GetMediumNode
866 //purpose  : Return existing or create new medium nodes between given ones
867 //=======================================================================
868
869 const SMDS_MeshNode* SMESH_MesherHelper::GetMediumNode(const SMDS_MeshNode* n1,
870                                                        const SMDS_MeshNode* n2,
871                                                        bool                 force3d)
872 {
873   // Find existing node
874
875   SMESH_TLink link(n1,n2);
876   ItTLinkNode itLN = myTLinkNodeMap.find( link );
877   if ( itLN != myTLinkNodeMap.end() ) {
878     return (*itLN).second;
879   }
880
881   // Create medium node
882
883   SMDS_MeshNode* n12;
884   SMESHDS_Mesh* meshDS = GetMeshDS();
885
886   if ( IsSeamShape( n1->getshapeId() ))
887     // to get a correct UV of a node on seam, the second node must have checked UV
888     std::swap( n1, n2 );
889
890   // get type of shape for the new medium node
891   int faceID = -1, edgeID = -1;
892   const SMDS_PositionPtr Pos1 = n1->GetPosition();
893   const SMDS_PositionPtr Pos2 = n2->GetPosition();
894
895   TopoDS_Edge E; double u [2];
896   TopoDS_Face F; gp_XY  uv[2];
897   bool uvOK[2] = { false, false };
898
899   if( myShape.IsNull() )
900   {
901     if( Pos1->GetTypeOfPosition()==SMDS_TOP_FACE ) {
902       faceID = n1->getshapeId();
903     }
904     else if( Pos2->GetTypeOfPosition()==SMDS_TOP_FACE ) {
905       faceID = n2->getshapeId();
906     }
907
908     if( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE ) {
909       edgeID = n1->getshapeId();
910     }
911     if( Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE ) {
912       edgeID = n2->getshapeId();
913     }
914   }
915   // get positions of the given nodes on shapes
916   TopAbs_ShapeEnum shapeType = myShape.IsNull() ? TopAbs_SHAPE : myShape.ShapeType();
917   if ( faceID>0 || shapeType == TopAbs_FACE)
918   {
919     if( myShape.IsNull() )
920       F = TopoDS::Face(meshDS->IndexToShape(faceID));
921     else {
922       F = TopoDS::Face(myShape);
923       faceID = myShapeID;
924     }
925     uv[0] = GetNodeUV(F,n1,n2, force3d ? 0 : &uvOK[0]);
926     uv[1] = GetNodeUV(F,n2,n1, force3d ? 0 : &uvOK[1]);
927   }
928   else if (edgeID>0 || shapeType == TopAbs_EDGE)
929   {
930     if ( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE &&
931          Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE &&
932          n1->getshapeId() != n2->getshapeId() ) // issue 0021006
933     return getMediumNodeOnComposedWire(n1,n2,force3d);
934
935     if( myShape.IsNull() )
936       E = TopoDS::Edge(meshDS->IndexToShape(edgeID));
937     else {
938       E = TopoDS::Edge(myShape);
939       edgeID = myShapeID;
940     }
941     u[0] = GetNodeU(E,n1,n2, force3d ? 0 : &uvOK[0]);
942     u[1] = GetNodeU(E,n2,n1, force3d ? 0 : &uvOK[1]);
943   }
944   if(!force3d)
945   {
946     // we try to create medium node using UV parameters of
947     // nodes, else - medium between corresponding 3d points
948     if( ! F.IsNull() )
949     {
950       if ( uvOK[0] && uvOK[1] )
951       {
952         if ( IsDegenShape( n1->getshapeId() )) {
953           if ( myParIndex & U_periodic ) uv[0].SetCoord( 1, uv[1].Coord( 1 ));
954           else                           uv[0].SetCoord( 2, uv[1].Coord( 2 ));
955         }
956         else if ( IsDegenShape( n2->getshapeId() )) {
957           if ( myParIndex & U_periodic ) uv[1].SetCoord( 1, uv[0].Coord( 1 ));
958           else                           uv[1].SetCoord( 2, uv[0].Coord( 2 ));
959         }
960
961         TopLoc_Location loc;
962         Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
963         gp_XY UV = GetMiddleUV( S, uv[0], uv[1] );
964         gp_Pnt P = S->Value( UV.X(), UV.Y() ).Transformed(loc);
965         n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
966         meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y());
967         myTLinkNodeMap.insert(make_pair(link,n12));
968         return n12;
969       }
970     }
971     else if ( !E.IsNull() )
972     {
973       double f,l;
974       Handle(Geom_Curve) C = BRep_Tool::Curve(E, f, l);
975       if(!C.IsNull())
976       {
977         Standard_Boolean isPeriodic = C->IsPeriodic();
978         double U;
979         if(isPeriodic) {
980           Standard_Real Period = C->Period();
981           Standard_Real p = u[1]+ShapeAnalysis::AdjustByPeriod(u[1],u[0],Period);
982           Standard_Real pmid = (u[0]+p)/2.;
983           U = pmid+ShapeAnalysis::AdjustToPeriod(pmid,C->FirstParameter(),C->LastParameter());
984         }
985         else
986           U = (u[0]+u[1])/2.;
987
988         gp_Pnt P = C->Value( U );
989         n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
990         meshDS->SetNodeOnEdge(n12, edgeID, U);
991         myTLinkNodeMap.insert(make_pair(link,n12));
992         return n12;
993       }
994     }
995   }
996
997   // 3d variant
998   double x = ( n1->X() + n2->X() )/2.;
999   double y = ( n1->Y() + n2->Y() )/2.;
1000   double z = ( n1->Z() + n2->Z() )/2.;
1001   n12 = meshDS->AddNode(x,y,z);
1002
1003   if ( !F.IsNull() )
1004   {
1005     gp_XY UV = ( uv[0] + uv[1] ) / 2.;
1006     CheckNodeUV( F, n12, UV, 2*BRep_Tool::Tolerance( F ), /*force=*/true);
1007     meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y() );
1008   }
1009   else if ( !E.IsNull() )
1010   {
1011     double U = ( u[0] + u[1] ) / 2.;
1012     CheckNodeU( E, n12, U, 2*BRep_Tool::Tolerance( E ), /*force=*/true);
1013     meshDS->SetNodeOnEdge(n12, edgeID, U);
1014   }
1015   else if ( myShapeID > 0 )
1016   {
1017     meshDS->SetNodeInVolume(n12, myShapeID);
1018   }
1019
1020   myTLinkNodeMap.insert( make_pair( link, n12 ));
1021   return n12;
1022 }
1023
1024 //================================================================================
1025 /*!
1026  * \brief Makes a medium node if nodes reside different edges
1027  */
1028 //================================================================================
1029
1030 const SMDS_MeshNode* SMESH_MesherHelper::getMediumNodeOnComposedWire(const SMDS_MeshNode* n1,
1031                                                                      const SMDS_MeshNode* n2,
1032                                                                      bool                 force3d)
1033 {
1034   gp_Pnt middle = 0.5 * XYZ(n1) + 0.5 * XYZ(n2);
1035   SMDS_MeshNode* n12 = AddNode( middle.X(), middle.Y(), middle.Z() );
1036
1037   // To find position on edge and 3D position for n12,
1038   // project <middle> to 2 edges and select projection most close to <middle>
1039
1040   double u = 0, distMiddleProj = Precision::Infinite(), distXYZ[4];
1041   int iOkEdge = 0;
1042   TopoDS_Edge edges[2];
1043   for ( int is2nd = 0; is2nd < 2; ++is2nd )
1044   {
1045     // get an edge
1046     const SMDS_MeshNode* n = is2nd ? n2 : n1;
1047     TopoDS_Shape shape = GetSubShapeByNode( n, GetMeshDS() );
1048     if ( shape.IsNull() || shape.ShapeType() != TopAbs_EDGE )
1049       continue;
1050
1051     // project to get U of projection and distance from middle to projection
1052     TopoDS_Edge edge = edges[ is2nd ] = TopoDS::Edge( shape );
1053     double node2MiddleDist = middle.Distance( XYZ(n) );
1054     double foundU = GetNodeU( edge, n );
1055     CheckNodeU( edge, n12, foundU, 2*BRep_Tool::Tolerance(edge), /*force=*/true, distXYZ );
1056     if ( distXYZ[0] < node2MiddleDist )
1057     {
1058       distMiddleProj = distXYZ[0];
1059       u = foundU;
1060       iOkEdge = is2nd;
1061     }
1062   }
1063   if ( Precision::IsInfinite( distMiddleProj ))
1064   {
1065     // both projections failed; set n12 on the edge of n1 with U of a common vertex
1066     TopoDS_Vertex vCommon;
1067     if ( TopExp::CommonVertex( edges[0], edges[1], vCommon ))
1068       u = BRep_Tool::Parameter( vCommon, edges[0] );
1069     else
1070     {
1071       double f,l, u0 = GetNodeU( edges[0], n1 );
1072       BRep_Tool::Range( edges[0],f,l );
1073       u = ( fabs(u0-f) < fabs(u0-l) ) ? f : l;
1074     }
1075     iOkEdge = 0;
1076     distMiddleProj = 0;
1077   }
1078
1079   // move n12 to position of a successfull projection
1080   double tol = BRep_Tool::Tolerance(edges[ iOkEdge ]);
1081   if ( !force3d && distMiddleProj > 2*tol )
1082   {
1083     TopLoc_Location loc; double f,l;
1084     Handle(Geom_Curve) curve = BRep_Tool::Curve( edges[iOkEdge],loc,f,l );
1085     gp_Pnt p = curve->Value( u );
1086     GetMeshDS()->MoveNode( n12, p.X(), p.Y(), p.Z() );
1087   }
1088
1089   GetMeshDS()->SetNodeOnEdge(n12, edges[iOkEdge], u);
1090
1091   myTLinkNodeMap.insert( make_pair( SMESH_TLink(n1,n2), n12 ));
1092
1093   return n12;
1094 }
1095
1096 //=======================================================================
1097 //function : AddNode
1098 //purpose  : Creates a node
1099 //=======================================================================
1100
1101 SMDS_MeshNode* SMESH_MesherHelper::AddNode(double x, double y, double z, int ID)
1102 {
1103   SMESHDS_Mesh * meshDS = GetMeshDS();
1104   SMDS_MeshNode* node = 0;
1105   if ( ID )
1106     node = meshDS->AddNodeWithID( x, y, z, ID );
1107   else
1108     node = meshDS->AddNode( x, y, z );
1109   if ( mySetElemOnShape && myShapeID > 0 ) {
1110     switch ( myShape.ShapeType() ) {
1111     case TopAbs_SOLID:  meshDS->SetNodeInVolume( node, myShapeID); break;
1112     case TopAbs_SHELL:  meshDS->SetNodeInVolume( node, myShapeID); break;
1113     case TopAbs_FACE:   meshDS->SetNodeOnFace(   node, myShapeID); break;
1114     case TopAbs_EDGE:   meshDS->SetNodeOnEdge(   node, myShapeID); break;
1115     case TopAbs_VERTEX: meshDS->SetNodeOnVertex( node, myShapeID); break;
1116     default: ;
1117     }
1118   }
1119   return node;
1120 }
1121
1122 //=======================================================================
1123 //function : AddEdge
1124 //purpose  : Creates quadratic or linear edge
1125 //=======================================================================
1126
1127 SMDS_MeshEdge* SMESH_MesherHelper::AddEdge(const SMDS_MeshNode* n1,
1128                                            const SMDS_MeshNode* n2,
1129                                            const int            id,
1130                                            const bool           force3d)
1131 {
1132   SMESHDS_Mesh * meshDS = GetMeshDS();
1133   
1134   SMDS_MeshEdge* edge = 0;
1135   if (myCreateQuadratic) {
1136     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1137     if(id)
1138       edge = meshDS->AddEdgeWithID(n1, n2, n12, id);
1139     else
1140       edge = meshDS->AddEdge(n1, n2, n12);
1141   }
1142   else {
1143     if(id)
1144       edge = meshDS->AddEdgeWithID(n1, n2, id);
1145     else
1146       edge = meshDS->AddEdge(n1, n2);
1147   }
1148
1149   if ( mySetElemOnShape && myShapeID > 0 )
1150     meshDS->SetMeshElementOnShape( edge, myShapeID );
1151
1152   return edge;
1153 }
1154
1155 //=======================================================================
1156 //function : AddFace
1157 //purpose  : Creates quadratic or linear triangle
1158 //=======================================================================
1159
1160 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1161                                            const SMDS_MeshNode* n2,
1162                                            const SMDS_MeshNode* n3,
1163                                            const int id,
1164                                            const bool force3d)
1165 {
1166   SMESHDS_Mesh * meshDS = GetMeshDS();
1167   SMDS_MeshFace* elem = 0;
1168
1169   if( n1==n2 || n2==n3 || n3==n1 )
1170     return elem;
1171
1172   if(!myCreateQuadratic) {
1173     if(id)
1174       elem = meshDS->AddFaceWithID(n1, n2, n3, id);
1175     else
1176       elem = meshDS->AddFace(n1, n2, n3);
1177   }
1178   else {
1179     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1180     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1181     const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1182
1183     if(id)
1184       elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, id);
1185     else
1186       elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31);
1187   }
1188   if ( mySetElemOnShape && myShapeID > 0 )
1189     meshDS->SetMeshElementOnShape( elem, myShapeID );
1190
1191   return elem;
1192 }
1193
1194 //=======================================================================
1195 //function : AddFace
1196 //purpose  : Creates quadratic or linear quadrangle
1197 //=======================================================================
1198
1199 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1200                                            const SMDS_MeshNode* n2,
1201                                            const SMDS_MeshNode* n3,
1202                                            const SMDS_MeshNode* n4,
1203                                            const int            id,
1204                                            const bool           force3d)
1205 {
1206   SMESHDS_Mesh * meshDS = GetMeshDS();
1207   SMDS_MeshFace* elem = 0;
1208
1209   if( n1==n2 ) {
1210     return AddFace(n1,n3,n4,id,force3d);
1211   }
1212   if( n1==n3 ) {
1213     return AddFace(n1,n2,n4,id,force3d);
1214   }
1215   if( n1==n4 ) {
1216     return AddFace(n1,n2,n3,id,force3d);
1217   }
1218   if( n2==n3 ) {
1219     return AddFace(n1,n2,n4,id,force3d);
1220   }
1221   if( n2==n4 ) {
1222     return AddFace(n1,n2,n3,id,force3d);
1223   }
1224   if( n3==n4 ) {
1225     return AddFace(n1,n2,n3,id,force3d);
1226   }
1227
1228   if(!myCreateQuadratic) {
1229     if(id)
1230       elem = meshDS->AddFaceWithID(n1, n2, n3, n4, id);
1231     else
1232       elem = meshDS->AddFace(n1, n2, n3, n4);
1233   }
1234   else {
1235     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1236     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1237     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1238     const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1239
1240     if(id)
1241       elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, id);
1242     else
1243       elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41);
1244   }
1245   if ( mySetElemOnShape && myShapeID > 0 )
1246     meshDS->SetMeshElementOnShape( elem, myShapeID );
1247
1248   return elem;
1249 }
1250
1251 //=======================================================================
1252 //function : AddPolygonalFace
1253 //purpose  : Creates polygon, with additional nodes in quadratic mesh
1254 //=======================================================================
1255
1256 SMDS_MeshFace* SMESH_MesherHelper::AddPolygonalFace (const vector<const SMDS_MeshNode*>& nodes,
1257                                                      const int                           id,
1258                                                      const bool                          force3d)
1259 {
1260   SMESHDS_Mesh * meshDS = GetMeshDS();
1261   SMDS_MeshFace* elem = 0;
1262
1263   if(!myCreateQuadratic) {
1264     if(id)
1265       elem = meshDS->AddPolygonalFaceWithID(nodes, id);
1266     else
1267       elem = meshDS->AddPolygonalFace(nodes);
1268   }
1269   else {
1270     vector<const SMDS_MeshNode*> newNodes;
1271     for ( int i = 0; i < nodes.size(); ++i )
1272     {
1273       const SMDS_MeshNode* n1 = nodes[i];
1274       const SMDS_MeshNode* n2 = nodes[(i+1)/nodes.size()];
1275       const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1276       newNodes.push_back( n1 );
1277       newNodes.push_back( n12 );
1278     }
1279     if(id)
1280       elem = meshDS->AddPolygonalFaceWithID(newNodes, id);
1281     else
1282       elem = meshDS->AddPolygonalFace(newNodes);
1283   }
1284   if ( mySetElemOnShape && myShapeID > 0 )
1285     meshDS->SetMeshElementOnShape( elem, myShapeID );
1286
1287   return elem;
1288 }
1289
1290 //=======================================================================
1291 //function : AddVolume
1292 //purpose  : Creates quadratic or linear prism
1293 //=======================================================================
1294
1295 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1296                                                const SMDS_MeshNode* n2,
1297                                                const SMDS_MeshNode* n3,
1298                                                const SMDS_MeshNode* n4,
1299                                                const SMDS_MeshNode* n5,
1300                                                const SMDS_MeshNode* n6,
1301                                                const int id,
1302                                                const bool force3d)
1303 {
1304   SMESHDS_Mesh * meshDS = GetMeshDS();
1305   SMDS_MeshVolume* elem = 0;
1306   if(!myCreateQuadratic) {
1307     if(id)
1308       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, id);
1309     else
1310       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6);
1311   }
1312   else {
1313     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1314     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1315     const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1316
1317     const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1318     const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1319     const SMDS_MeshNode* n64 = GetMediumNode(n6,n4,force3d);
1320
1321     const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1322     const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1323     const SMDS_MeshNode* n36 = GetMediumNode(n3,n6,force3d);
1324
1325     if(id)
1326       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, 
1327                                      n12, n23, n31, n45, n56, n64, n14, n25, n36, id);
1328     else
1329       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6,
1330                                n12, n23, n31, n45, n56, n64, n14, n25, n36);
1331   }
1332   if ( mySetElemOnShape && myShapeID > 0 )
1333     meshDS->SetMeshElementOnShape( elem, myShapeID );
1334
1335   return elem;
1336 }
1337
1338 //=======================================================================
1339 //function : AddVolume
1340 //purpose  : Creates quadratic or linear tetrahedron
1341 //=======================================================================
1342
1343 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1344                                                const SMDS_MeshNode* n2,
1345                                                const SMDS_MeshNode* n3,
1346                                                const SMDS_MeshNode* n4,
1347                                                const int id, 
1348                                                const bool force3d)
1349 {
1350   SMESHDS_Mesh * meshDS = GetMeshDS();
1351   SMDS_MeshVolume* elem = 0;
1352   if(!myCreateQuadratic) {
1353     if(id)
1354       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, id);
1355     else
1356       elem = meshDS->AddVolume(n1, n2, n3, n4);
1357   }
1358   else {
1359     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1360     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1361     const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1362
1363     const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1364     const SMDS_MeshNode* n24 = GetMediumNode(n2,n4,force3d);
1365     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1366
1367     if(id)
1368       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34, id);
1369     else
1370       elem = meshDS->AddVolume(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34);
1371   }
1372   if ( mySetElemOnShape && myShapeID > 0 )
1373     meshDS->SetMeshElementOnShape( elem, myShapeID );
1374
1375   return elem;
1376 }
1377
1378 //=======================================================================
1379 //function : AddVolume
1380 //purpose  : Creates quadratic or linear pyramid
1381 //=======================================================================
1382
1383 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1384                                                const SMDS_MeshNode* n2,
1385                                                const SMDS_MeshNode* n3,
1386                                                const SMDS_MeshNode* n4,
1387                                                const SMDS_MeshNode* n5,
1388                                                const int id, 
1389                                                const bool force3d)
1390 {
1391   SMDS_MeshVolume* elem = 0;
1392   if(!myCreateQuadratic) {
1393     if(id)
1394       elem = GetMeshDS()->AddVolumeWithID(n1, n2, n3, n4, n5, id);
1395     else
1396       elem = GetMeshDS()->AddVolume(n1, n2, n3, n4, n5);
1397   }
1398   else {
1399     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1400     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1401     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1402     const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1403
1404     const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1405     const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1406     const SMDS_MeshNode* n35 = GetMediumNode(n3,n5,force3d);
1407     const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1408
1409     if(id)
1410       elem = GetMeshDS()->AddVolumeWithID ( n1,  n2,  n3,  n4,  n5,
1411                                             n12, n23, n34, n41,
1412                                             n15, n25, n35, n45,
1413                                             id);
1414     else
1415       elem = GetMeshDS()->AddVolume( n1,  n2,  n3,  n4,  n5,
1416                                      n12, n23, n34, n41,
1417                                      n15, n25, n35, n45);
1418   }
1419   if ( mySetElemOnShape && myShapeID > 0 )
1420     GetMeshDS()->SetMeshElementOnShape( elem, myShapeID );
1421
1422   return elem;
1423 }
1424
1425 //=======================================================================
1426 //function : AddVolume
1427 //purpose  : Creates quadratic or linear hexahedron
1428 //=======================================================================
1429
1430 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1431                                                const SMDS_MeshNode* n2,
1432                                                const SMDS_MeshNode* n3,
1433                                                const SMDS_MeshNode* n4,
1434                                                const SMDS_MeshNode* n5,
1435                                                const SMDS_MeshNode* n6,
1436                                                const SMDS_MeshNode* n7,
1437                                                const SMDS_MeshNode* n8,
1438                                                const int id,
1439                                                const bool force3d)
1440 {
1441   SMESHDS_Mesh * meshDS = GetMeshDS();
1442   SMDS_MeshVolume* elem = 0;
1443   if(!myCreateQuadratic) {
1444     if(id)
1445       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8, id);
1446     else
1447       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8);
1448   }
1449   else {
1450     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1451     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1452     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1453     const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1454
1455     const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1456     const SMDS_MeshNode* n67 = GetMediumNode(n6,n7,force3d);
1457     const SMDS_MeshNode* n78 = GetMediumNode(n7,n8,force3d);
1458     const SMDS_MeshNode* n85 = GetMediumNode(n8,n5,force3d);
1459
1460     const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1461     const SMDS_MeshNode* n26 = GetMediumNode(n2,n6,force3d);
1462     const SMDS_MeshNode* n37 = GetMediumNode(n3,n7,force3d);
1463     const SMDS_MeshNode* n48 = GetMediumNode(n4,n8,force3d);
1464
1465     if(id)
1466       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
1467                                      n12, n23, n34, n41, n56, n67,
1468                                      n78, n85, n15, n26, n37, n48, id);
1469     else
1470       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
1471                                n12, n23, n34, n41, n56, n67,
1472                                n78, n85, n15, n26, n37, n48);
1473   }
1474   if ( mySetElemOnShape && myShapeID > 0 )
1475     meshDS->SetMeshElementOnShape( elem, myShapeID );
1476
1477   return elem;
1478 }
1479
1480 //=======================================================================
1481 //function : AddPolyhedralVolume
1482 //purpose  : Creates polyhedron. In quadratic mesh, adds medium nodes
1483 //=======================================================================
1484
1485 SMDS_MeshVolume*
1486 SMESH_MesherHelper::AddPolyhedralVolume (const std::vector<const SMDS_MeshNode*>& nodes,
1487                                          const std::vector<int>&                  quantities,
1488                                          const int                                id,
1489                                          const bool                               force3d)
1490 {
1491   SMESHDS_Mesh * meshDS = GetMeshDS();
1492   SMDS_MeshVolume* elem = 0;
1493   if(!myCreateQuadratic)
1494   {
1495     if(id)
1496       elem = meshDS->AddPolyhedralVolumeWithID(nodes, quantities, id);
1497     else
1498       elem = meshDS->AddPolyhedralVolume(nodes, quantities);
1499   }
1500   else
1501   {
1502     vector<const SMDS_MeshNode*> newNodes;
1503     vector<int> newQuantities;
1504     for ( int iFace=0, iN=0; iFace < quantities.size(); ++iFace)
1505     {
1506       int nbNodesInFace = quantities[iFace];
1507       newQuantities.push_back(0);
1508       for ( int i = 0; i < nbNodesInFace; ++i )
1509       {
1510         const SMDS_MeshNode* n1 = nodes[ iN + i ];
1511         newNodes.push_back( n1 );
1512         newQuantities.back()++;
1513         
1514         const SMDS_MeshNode* n2 = nodes[ iN + ( i+1==nbNodesInFace ? 0 : i+1 )];
1515 //         if ( n1->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE &&
1516 //              n2->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE )
1517         {
1518           const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1519           newNodes.push_back( n12 );
1520           newQuantities.back()++;
1521         }
1522       }
1523       iN += nbNodesInFace;
1524     }
1525     if(id)
1526       elem = meshDS->AddPolyhedralVolumeWithID( newNodes, newQuantities, id );
1527     else
1528       elem = meshDS->AddPolyhedralVolume( newNodes, newQuantities );
1529   }
1530   if ( mySetElemOnShape && myShapeID > 0 )
1531     meshDS->SetMeshElementOnShape( elem, myShapeID );
1532
1533   return elem;
1534 }
1535
1536 //=======================================================================
1537 //function : LoadNodeColumns
1538 //purpose  : Load nodes bound to face into a map of node columns
1539 //=======================================================================
1540
1541 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
1542                                          const TopoDS_Face& theFace,
1543                                          const TopoDS_Edge& theBaseEdge,
1544                                          SMESHDS_Mesh*      theMesh,
1545                                          SMESH_ProxyMesh*   theProxyMesh)
1546 {
1547   const SMESHDS_SubMesh* faceSubMesh = 0;
1548   if ( theProxyMesh )
1549   {
1550     faceSubMesh = theProxyMesh->GetSubMesh( theFace );
1551     if ( !faceSubMesh ||
1552          faceSubMesh->NbElements() == 0 ||
1553          theProxyMesh->IsTemporary( faceSubMesh->GetElements()->next() ))
1554     {
1555       // can use a proxy sub-mesh with not temporary elements only
1556       faceSubMesh = 0;
1557       theProxyMesh = 0;
1558     }
1559   }
1560   if ( !faceSubMesh )
1561     faceSubMesh = theMesh->MeshElements( theFace );
1562   if ( !faceSubMesh || faceSubMesh->NbElements() == 0 )
1563     return false;
1564
1565   // get nodes on theBaseEdge sorted by param on edge and initialize theParam2ColumnMap with them
1566
1567   map< double, const SMDS_MeshNode*> sortedBaseNodes;
1568   if ( !SMESH_Algo::GetSortedNodesOnEdge( theMesh, theBaseEdge,/*noMedium=*/true, sortedBaseNodes)
1569        || sortedBaseNodes.size() < 2 )
1570     return false;
1571
1572   int nbRows = faceSubMesh->NbElements() / ( sortedBaseNodes.size()-1 ) + 1;
1573   map< double, const SMDS_MeshNode*>::iterator u_n = sortedBaseNodes.begin();
1574   double f = u_n->first, range = sortedBaseNodes.rbegin()->first - f;
1575   for ( ; u_n != sortedBaseNodes.end(); u_n++ )
1576   {
1577     double par = ( u_n->first - f ) / range;
1578     vector<const SMDS_MeshNode*>& nCol = theParam2ColumnMap[ par ];
1579     nCol.resize( nbRows );
1580     nCol[0] = u_n->second;
1581   }
1582   TParam2ColumnMap::iterator par_nVec_2, par_nVec_1 = theParam2ColumnMap.begin();
1583   if ( theProxyMesh )
1584   {
1585     for ( ; par_nVec_1 != theParam2ColumnMap.end(); ++par_nVec_1 )
1586     {
1587       const SMDS_MeshNode* & n = par_nVec_1->second[0];
1588       n = theProxyMesh->GetProxyNode( n );
1589     }
1590   }
1591
1592   // fill theParam2ColumnMap column by column by passing from nodes on
1593   // theBaseEdge up via mesh faces on theFace
1594
1595   par_nVec_2 = theParam2ColumnMap.begin();
1596   par_nVec_1 = par_nVec_2++;
1597   TIDSortedElemSet emptySet, avoidSet;
1598   for ( ; par_nVec_2 != theParam2ColumnMap.end(); ++par_nVec_1, ++par_nVec_2 )
1599   {
1600     vector<const SMDS_MeshNode*>& nCol1 = par_nVec_1->second;
1601     vector<const SMDS_MeshNode*>& nCol2 = par_nVec_2->second;
1602
1603     int i1, i2, iRow = 0;
1604     const SMDS_MeshNode *n1 = nCol1[0], *n2 = nCol2[0];
1605     // find face sharing node n1 and n2 and belonging to faceSubMesh
1606     while ( const SMDS_MeshElement* face =
1607             SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, avoidSet, &i1, &i2))
1608     {
1609       if ( faceSubMesh->Contains( face ))
1610       {
1611         int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
1612         if ( nbNodes != 4 )
1613           return false;
1614         n1 = face->GetNode( (i2+2) % 4 ); // opposite corner of quadrangle face
1615         n2 = face->GetNode( (i1+2) % 4 );
1616         if ( ++iRow >= nbRows )
1617           return false;
1618         nCol1[ iRow ] = n1;
1619         nCol2[ iRow ] = n2;
1620         avoidSet.clear();
1621       }
1622       avoidSet.insert( face );
1623     }
1624     if ( iRow + 1 < nbRows ) // compact if necessary
1625       nCol1.resize( iRow + 1 ), nCol2.resize( iRow + 1 );
1626   }
1627   return theParam2ColumnMap.size() > 1 && theParam2ColumnMap.begin()->second.size() > 1;
1628 }
1629
1630 //=======================================================================
1631 //function : NbAncestors
1632 //purpose  : Return number of unique ancestors of the shape
1633 //=======================================================================
1634
1635 int SMESH_MesherHelper::NbAncestors(const TopoDS_Shape& shape,
1636                                     const SMESH_Mesh&   mesh,
1637                                     TopAbs_ShapeEnum    ancestorType/*=TopAbs_SHAPE*/)
1638 {
1639   TopTools_MapOfShape ancestors;
1640   TopTools_ListIteratorOfListOfShape ansIt( mesh.GetAncestors(shape) );
1641   for ( ; ansIt.More(); ansIt.Next() ) {
1642     if ( ancestorType == TopAbs_SHAPE || ansIt.Value().ShapeType() == ancestorType )
1643       ancestors.Add( ansIt.Value() );
1644   }
1645   return ancestors.Extent();
1646 }
1647
1648 //=======================================================================
1649 //function : GetSubShapeOri
1650 //purpose  : Return orientation of sub-shape in the main shape
1651 //=======================================================================
1652
1653 TopAbs_Orientation SMESH_MesherHelper::GetSubShapeOri(const TopoDS_Shape& shape,
1654                                                       const TopoDS_Shape& subShape)
1655 {
1656   TopAbs_Orientation ori = TopAbs_Orientation(-1);
1657   if ( !shape.IsNull() && !subShape.IsNull() )
1658   {
1659     TopExp_Explorer e( shape, subShape.ShapeType() );
1660     if ( shape.Orientation() >= TopAbs_INTERNAL ) // TopAbs_INTERNAL or TopAbs_EXTERNAL
1661       e.Init( shape.Oriented(TopAbs_FORWARD), subShape.ShapeType() );
1662     for ( ; e.More(); e.Next())
1663       if ( subShape.IsSame( e.Current() ))
1664         break;
1665     if ( e.More() )
1666       ori = e.Current().Orientation();
1667   }
1668   return ori;
1669 }
1670
1671 //=======================================================================
1672 //function : IsSubShape
1673 //purpose  : 
1674 //=======================================================================
1675
1676 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape,
1677                                      const TopoDS_Shape& mainShape )
1678 {
1679   if ( !shape.IsNull() && !mainShape.IsNull() )
1680   {
1681     for ( TopExp_Explorer exp( mainShape, shape.ShapeType());
1682           exp.More();
1683           exp.Next() )
1684       if ( shape.IsSame( exp.Current() ))
1685         return true;
1686   }
1687   SCRUTE((shape.IsNull()));
1688   SCRUTE((mainShape.IsNull()));
1689   return false;
1690 }
1691
1692 //=======================================================================
1693 //function : IsSubShape
1694 //purpose  : 
1695 //=======================================================================
1696
1697 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape, SMESH_Mesh* aMesh )
1698 {
1699   if ( shape.IsNull() || !aMesh )
1700     return false;
1701   return
1702     aMesh->GetMeshDS()->ShapeToIndex( shape ) ||
1703     // PAL16202
1704     (shape.ShapeType() == TopAbs_COMPOUND && aMesh->GetMeshDS()->IsGroupOfSubShapes( shape ));
1705 }
1706
1707 //================================================================================
1708 /*!
1709  * \brief Return maximal tolerance of shape
1710  */
1711 //================================================================================
1712
1713 double SMESH_MesherHelper::MaxTolerance( const TopoDS_Shape& shape )
1714 {
1715   double tol = Precision::Confusion();
1716   TopExp_Explorer exp;
1717   for ( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next() )
1718     tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Face( exp.Current())));
1719   for ( exp.Init( shape, TopAbs_EDGE ); exp.More(); exp.Next() )
1720     tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Edge( exp.Current())));
1721   for ( exp.Init( shape, TopAbs_VERTEX ); exp.More(); exp.Next() )
1722     tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Vertex( exp.Current())));
1723
1724   return tol;
1725 }
1726
1727 //================================================================================
1728 /*!
1729  * \brief Check if the first and last vertices of an edge are the same
1730  * \param anEdge - the edge to check
1731  * \retval bool - true if same
1732  */
1733 //================================================================================
1734
1735 bool SMESH_MesherHelper::IsClosedEdge( const TopoDS_Edge& anEdge )
1736 {
1737   if ( anEdge.Orientation() >= TopAbs_INTERNAL )
1738     return IsClosedEdge( TopoDS::Edge( anEdge.Oriented( TopAbs_FORWARD )));
1739   return TopExp::FirstVertex( anEdge ).IsSame( TopExp::LastVertex( anEdge ));
1740 }
1741
1742 //=======================================================================
1743 //function : IsQuadraticMesh
1744 //purpose  : Check mesh without geometry for: if all elements on this shape are quadratic,
1745 //           quadratic elements will be created.
1746 //           Used then generated 3D mesh without geometry.
1747 //=======================================================================
1748
1749 SMESH_MesherHelper:: MType SMESH_MesherHelper::IsQuadraticMesh()
1750 {
1751   int NbAllEdgsAndFaces=0;
1752   int NbQuadFacesAndEdgs=0;
1753   int NbFacesAndEdges=0;
1754   //All faces and edges
1755   NbAllEdgsAndFaces = myMesh->NbEdges() + myMesh->NbFaces();
1756   
1757   //Quadratic faces and edges
1758   NbQuadFacesAndEdgs = myMesh->NbEdges(ORDER_QUADRATIC) + myMesh->NbFaces(ORDER_QUADRATIC);
1759
1760   //Linear faces and edges
1761   NbFacesAndEdges = myMesh->NbEdges(ORDER_LINEAR) + myMesh->NbFaces(ORDER_LINEAR);
1762   
1763   if (NbAllEdgsAndFaces == NbQuadFacesAndEdgs) {
1764     //Quadratic mesh
1765     return SMESH_MesherHelper::QUADRATIC;
1766   }
1767   else if (NbAllEdgsAndFaces == NbFacesAndEdges) {
1768     //Linear mesh
1769     return SMESH_MesherHelper::LINEAR;
1770   }
1771   else
1772     //Mesh with both type of elements
1773     return SMESH_MesherHelper::COMP;
1774 }
1775
1776 //=======================================================================
1777 //function : GetOtherParam
1778 //purpose  : Return an alternative parameter for a node on seam
1779 //=======================================================================
1780
1781 double SMESH_MesherHelper::GetOtherParam(const double param) const
1782 {
1783   int i = myParIndex & U_periodic ? 0 : 1;
1784   return fabs(param-myPar1[i]) < fabs(param-myPar2[i]) ? myPar2[i] : myPar1[i];
1785 }
1786
1787 //#include <Perf_Meter.hxx>
1788
1789 //=======================================================================
1790 namespace { // Structures used by FixQuadraticElements()
1791 //=======================================================================
1792
1793 #define __DMP__(txt) \
1794   //cout << txt
1795 #define MSG(txt) __DMP__(txt<<endl)
1796 #define MSGBEG(txt) __DMP__(txt)
1797
1798   //const double straightTol2 = 1e-33; // to detect straing links
1799   bool isStraightLink(double linkLen2, double middleNodeMove2)
1800   {
1801     // straight if <node move> < 1/15 * <link length>
1802     return middleNodeMove2 < 1/15./15. * linkLen2;
1803   }
1804
1805   struct QFace;
1806   // ---------------------------------------
1807   /*!
1808    * \brief Quadratic link knowing its faces
1809    */
1810   struct QLink: public SMESH_TLink
1811   {
1812     const SMDS_MeshNode*          _mediumNode;
1813     mutable vector<const QFace* > _faces;
1814     mutable gp_Vec                _nodeMove;
1815     mutable int                   _nbMoves;
1816
1817     QLink(const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshNode* nm):
1818       SMESH_TLink( n1,n2 ), _mediumNode(nm), _nodeMove(0,0,0), _nbMoves(0) {
1819       _faces.reserve(4);
1820       //if ( MediumPos() != SMDS_TOP_3DSPACE )
1821         _nodeMove = MediumPnt() - MiddlePnt();
1822     }
1823     void SetContinuesFaces() const;
1824     const QFace* GetContinuesFace( const QFace* face ) const;
1825     bool OnBoundary() const;
1826     gp_XYZ MiddlePnt() const { return ( XYZ( node1() ) + XYZ( node2() )) / 2.; }
1827     gp_XYZ MediumPnt() const { return XYZ( _mediumNode ); }
1828
1829     SMDS_TypeOfPosition MediumPos() const
1830     { return _mediumNode->GetPosition()->GetTypeOfPosition(); }
1831     SMDS_TypeOfPosition EndPos(bool isSecond) const
1832     { return (isSecond ? node2() : node1())->GetPosition()->GetTypeOfPosition(); }
1833     const SMDS_MeshNode* EndPosNode(SMDS_TypeOfPosition pos) const
1834     { return EndPos(0) == pos ? node1() : EndPos(1) == pos ? node2() : 0; }
1835
1836     void Move(const gp_Vec& move, bool sum=false) const
1837     { _nodeMove += move; _nbMoves += sum ? (_nbMoves==0) : 1; }
1838     gp_XYZ Move() const { return _nodeMove.XYZ() / _nbMoves; }
1839     bool IsMoved() const { return (_nbMoves > 0 && !IsStraight()); }
1840     bool IsStraight() const
1841     { return isStraightLink( (XYZ(node1())-XYZ(node2())).SquareModulus(),
1842                              _nodeMove.SquareMagnitude());
1843     }
1844     bool operator<(const QLink& other) const {
1845       return (node1()->GetID() == other.node1()->GetID() ?
1846               node2()->GetID() < other.node2()->GetID() :
1847               node1()->GetID() < other.node1()->GetID());
1848     }
1849 //     struct PtrComparator {
1850 //       bool operator() (const QLink* l1, const QLink* l2 ) const { return *l1 < *l2; }
1851 //     };
1852   };
1853   // ---------------------------------------------------------
1854   /*!
1855    * \brief Link in the chain of links; it connects two faces
1856    */
1857   struct TChainLink
1858   {
1859     const QLink*         _qlink;
1860     mutable const QFace* _qfaces[2];
1861
1862     TChainLink(const QLink* qlink=0):_qlink(qlink) {
1863       _qfaces[0] = _qfaces[1] = 0;
1864     }
1865     void SetFace(const QFace* face) const { int iF = _qfaces[0] ? 1 : 0; _qfaces[iF]=face; }
1866
1867     bool IsBoundary() const { return !_qfaces[1]; }
1868
1869     void RemoveFace( const QFace* face ) const
1870     { _qfaces[(face == _qfaces[1])] = 0; if (!_qfaces[0]) std::swap(_qfaces[0],_qfaces[1]); }
1871
1872     const QFace* NextFace( const QFace* f ) const
1873     { return _qfaces[0]==f ? _qfaces[1] : _qfaces[0]; }
1874
1875     const SMDS_MeshNode* NextNode( const SMDS_MeshNode* n ) const
1876     { return n == _qlink->node1() ? _qlink->node2() : _qlink->node1(); }
1877
1878     bool operator<(const TChainLink& other) const { return *_qlink < *other._qlink; }
1879
1880     operator bool() const { return (_qlink); }
1881
1882     const QLink* operator->() const { return _qlink; }
1883
1884     gp_Vec Normal() const;
1885   };
1886   // --------------------------------------------------------------------
1887   typedef list< TChainLink > TChain;
1888   typedef set < TChainLink > TLinkSet;
1889   typedef TLinkSet::const_iterator TLinkInSet;
1890
1891   const int theFirstStep = 5;
1892
1893   enum { ERR_OK, ERR_TRI, ERR_PRISM, ERR_UNKNOWN }; // errors of QFace::GetLinkChain()
1894   // --------------------------------------------------------------------
1895   /*!
1896    * \brief Face shared by two volumes and bound by QLinks
1897    */
1898   struct QFace: public TIDSortedNodeSet
1899   {
1900     mutable const SMDS_MeshElement* _volumes[2];
1901     mutable vector< const QLink* >  _sides;
1902     mutable bool                    _sideIsAdded[4]; // added in chain of links
1903     gp_Vec                          _normal;
1904 #ifdef _DEBUG_
1905     mutable const SMDS_MeshElement* _face;
1906 #endif
1907
1908     QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face=0 );
1909
1910     void SetVolume(const SMDS_MeshElement* v) const { _volumes[ _volumes[0] ? 1 : 0 ] = v; }
1911
1912     int NbVolumes() const { return !_volumes[0] ? 0 : !_volumes[1] ? 1 : 2; }
1913
1914     void AddSelfToLinks() const {
1915       for ( int i = 0; i < _sides.size(); ++i )
1916         _sides[i]->_faces.push_back( this );
1917     }
1918     int LinkIndex( const QLink* side ) const {
1919       for (int i=0; i<_sides.size(); ++i ) if ( _sides[i] == side ) return i;
1920       return -1;
1921     }
1922     bool GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& err) const;
1923
1924     bool GetLinkChain( TChainLink& link, TChain& chain, SMDS_TypeOfPosition pos, int& err) const
1925     {
1926       int i = LinkIndex( link._qlink );
1927       if ( i < 0 ) return true;
1928       _sideIsAdded[i] = true;
1929       link.SetFace( this );
1930       // continue from opposite link
1931       return GetLinkChain( (i+2)%_sides.size(), chain, pos, err );
1932     }
1933     bool IsBoundary() const { return !_volumes[1]; }
1934
1935     bool Contains( const SMDS_MeshNode* node ) const { return count(node); }
1936
1937     bool IsSpoiled(const QLink* bentLink ) const;
1938
1939     TLinkInSet GetBoundaryLink( const TLinkSet&      links,
1940                                 const TChainLink&    avoidLink,
1941                                 TLinkInSet *         notBoundaryLink = 0,
1942                                 const SMDS_MeshNode* nodeToContain = 0,
1943                                 bool *               isAdjacentUsed = 0,
1944                                 int                  nbRecursionsLeft = -1) const;
1945
1946     TLinkInSet GetLinkByNode( const TLinkSet&      links,
1947                               const TChainLink&    avoidLink,
1948                               const SMDS_MeshNode* nodeToContain) const;
1949
1950     const SMDS_MeshNode* GetNodeInFace() const {
1951       for ( int iL = 0; iL < _sides.size(); ++iL )
1952         if ( _sides[iL]->MediumPos() == SMDS_TOP_FACE ) return _sides[iL]->_mediumNode;
1953       return 0;
1954     }
1955
1956     gp_Vec LinkNorm(const int i, SMESH_MesherHelper* theFaceHelper=0) const;
1957
1958     double MoveByBoundary( const TChainLink&   theLink,
1959                            const gp_Vec&       theRefVec,
1960                            const TLinkSet&     theLinks,
1961                            SMESH_MesherHelper* theFaceHelper=0,
1962                            const double        thePrevLen=0,
1963                            const int           theStep=theFirstStep,
1964                            gp_Vec*             theLinkNorm=0,
1965                            double              theSign=1.0) const;
1966   };
1967
1968   //================================================================================
1969   /*!
1970    * \brief Dump QLink and QFace
1971    */
1972   ostream& operator << (ostream& out, const QLink& l)
1973   {
1974     out <<"QLink nodes: "
1975         << l.node1()->GetID() << " - "
1976         << l._mediumNode->GetID() << " - "
1977         << l.node2()->GetID() << endl;
1978     return out;
1979   }
1980   ostream& operator << (ostream& out, const QFace& f)
1981   {
1982     out <<"QFace nodes: "/*<< &f << "  "*/;
1983     for ( TIDSortedNodeSet::const_iterator n = f.begin(); n != f.end(); ++n )
1984       out << (*n)->GetID() << " ";
1985     out << " \tvolumes: "
1986         << (f._volumes[0] ? f._volumes[0]->GetID() : 0) << " "
1987         << (f._volumes[1] ? f._volumes[1]->GetID() : 0);
1988     out << "  \tNormal: "<< f._normal.X() <<", "<<f._normal.Y() <<", "<<f._normal.Z() << endl;
1989     return out;
1990   }
1991
1992   //================================================================================
1993   /*!
1994    * \brief Construct QFace from QLinks 
1995    */
1996   //================================================================================
1997
1998   QFace::QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face )
1999   {
2000     _volumes[0] = _volumes[1] = 0;
2001     _sides = links;
2002     _sideIsAdded[0]=_sideIsAdded[1]=_sideIsAdded[2]=_sideIsAdded[3]=false;
2003     _normal.SetCoord(0,0,0);
2004     for ( int i = 1; i < _sides.size(); ++i ) {
2005       const QLink *l1 = _sides[i-1], *l2 = _sides[i];
2006       insert( l1->node1() ); insert( l1->node2() );
2007       // compute normal
2008       gp_Vec v1( XYZ( l1->node2()), XYZ( l1->node1()));
2009       gp_Vec v2( XYZ( l2->node1()), XYZ( l2->node2()));
2010       if ( l1->node1() != l2->node1() && l1->node2() != l2->node2() )
2011         v1.Reverse(); 
2012       _normal += v1 ^ v2;
2013     }
2014     double normSqSize = _normal.SquareMagnitude();
2015     if ( normSqSize > numeric_limits<double>::min() )
2016       _normal /= sqrt( normSqSize );
2017     else
2018       _normal.SetCoord(1e-33,0,0);
2019
2020 #ifdef _DEBUG_
2021     _face = face;
2022 #endif
2023   }
2024   //================================================================================
2025   /*!
2026    * \brief Make up a chain of links
2027    *  \param iSide - link to add first
2028    *  \param chain - chain to fill in
2029    *  \param pos   - postion of medium nodes the links should have
2030    *  \param error - out, specifies what is wrong
2031    *  \retval bool - false if valid chain can't be built; "valid" means that links
2032    *                 of the chain belongs to rectangles bounding hexahedrons
2033    */
2034   //================================================================================
2035
2036   bool QFace::GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& error) const
2037   {
2038     if ( iSide >= _sides.size() ) // wrong argument iSide
2039       return false;
2040     if ( _sideIsAdded[ iSide ]) // already in chain
2041       return true;
2042
2043     if ( _sides.size() != 4 ) { // triangle - visit all my continous faces
2044       MSGBEG( *this );
2045       TLinkSet links;
2046       list< const QFace* > faces( 1, this );
2047       while ( !faces.empty() ) {
2048         const QFace* face = faces.front();
2049         for ( int i = 0; i < face->_sides.size(); ++i ) {
2050           if ( !face->_sideIsAdded[i] && face->_sides[i] ) {
2051             face->_sideIsAdded[i] = true;
2052             // find a face side in the chain
2053             TLinkInSet chLink = links.insert( TChainLink(face->_sides[i])).first;
2054 //             TChain::iterator chLink = chain.begin();
2055 //             for ( ; chLink != chain.end(); ++chLink )
2056 //               if ( chLink->_qlink == face->_sides[i] )
2057 //                 break;
2058 //             if ( chLink == chain.end() )
2059 //               chLink = chain.insert( chain.begin(), TChainLink(face->_sides[i]));
2060             // add a face to a chained link and put a continues face in the queue
2061             chLink->SetFace( face );
2062             if ( face->_sides[i]->MediumPos() >= pos )
2063               if ( const QFace* contFace = face->_sides[i]->GetContinuesFace( face ))
2064                 faces.push_back( contFace );
2065           }
2066         }
2067         faces.pop_front();
2068       }
2069       if ( error < ERR_TRI )
2070         error = ERR_TRI;
2071       chain.insert( chain.end(), links.begin(),links.end() );
2072       return false;
2073     }
2074     _sideIsAdded[iSide] = true; // not to add this link to chain again
2075     const QLink* link = _sides[iSide];
2076     if ( !link)
2077       return true;
2078
2079     // add link into chain
2080     TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(link));
2081     chLink->SetFace( this );
2082     MSGBEG( *this );
2083
2084     // propagate from quadrangle to neighbour faces
2085     if ( link->MediumPos() >= pos ) {
2086       int nbLinkFaces = link->_faces.size();
2087       if ( nbLinkFaces == 4 || (nbLinkFaces < 4 && link->OnBoundary())) {
2088         // hexahedral mesh or boundary quadrangles - goto a continous face
2089         if ( const QFace* f = link->GetContinuesFace( this ))
2090           return f->GetLinkChain( *chLink, chain, pos, error );
2091       }
2092       else {
2093         TChainLink chLink(link); // side face of prismatic mesh - visit all faces of iSide
2094         for ( int i = 0; i < nbLinkFaces; ++i )
2095           if ( link->_faces[i] )
2096             link->_faces[i]->GetLinkChain( chLink, chain, pos, error );
2097         if ( error < ERR_PRISM )
2098           error = ERR_PRISM;
2099         return false;
2100       }
2101     }
2102     return true;
2103   }
2104
2105   //================================================================================
2106   /*!
2107    * \brief Return a boundary link of the triangle face
2108    *  \param links - set of all links
2109    *  \param avoidLink - link not to return
2110    *  \param notBoundaryLink - out, neither the returned link nor avoidLink
2111    *  \param nodeToContain - node the returned link must contain; if provided, search
2112    *                         also performed on adjacent faces
2113    *  \param isAdjacentUsed - returns true if link is found in adjacent faces
2114    *  \param nbRecursionsLeft - to limit recursion
2115    */
2116   //================================================================================
2117
2118   TLinkInSet QFace::GetBoundaryLink( const TLinkSet&      links,
2119                                      const TChainLink&    avoidLink,
2120                                      TLinkInSet *         notBoundaryLink,
2121                                      const SMDS_MeshNode* nodeToContain,
2122                                      bool *               isAdjacentUsed,
2123                                      int                  nbRecursionsLeft) const
2124   {
2125     TLinkInSet linksEnd = links.end(), boundaryLink = linksEnd;
2126
2127     typedef list< pair< const QFace*, TLinkInSet > > TFaceLinkList;
2128     TFaceLinkList adjacentFaces;
2129
2130     for ( int iL = 0; iL < _sides.size(); ++iL )
2131     {
2132       if ( avoidLink._qlink == _sides[iL] )
2133         continue;
2134       TLinkInSet link = links.find( _sides[iL] );
2135       if ( link == linksEnd ) continue;
2136       if ( (*link)->MediumPos() > SMDS_TOP_FACE )
2137         continue; // We work on faces here, don't go inside a solid
2138
2139       // check link
2140       if ( link->IsBoundary() ) {
2141         if ( !nodeToContain ||
2142              (*link)->node1() == nodeToContain ||
2143              (*link)->node2() == nodeToContain )
2144         {
2145           boundaryLink = link;
2146           if ( !notBoundaryLink ) break;
2147         }
2148       }
2149       else if ( notBoundaryLink ) {
2150         *notBoundaryLink = link;
2151         if ( boundaryLink != linksEnd ) break;
2152       }
2153
2154       if ( boundaryLink == linksEnd && nodeToContain ) // collect adjacent faces
2155         if ( const QFace* adj = link->NextFace( this ))
2156           if ( adj->Contains( nodeToContain ))
2157             adjacentFaces.push_back( make_pair( adj, link ));
2158     }
2159
2160     if ( isAdjacentUsed ) *isAdjacentUsed = false;
2161     if ( boundaryLink == linksEnd && nodeToContain && nbRecursionsLeft) // check adjacent faces
2162     {
2163       if ( nbRecursionsLeft < 0 )
2164         nbRecursionsLeft = nodeToContain->NbInverseElements();
2165       TFaceLinkList::iterator adj = adjacentFaces.begin();
2166       for ( ; boundaryLink == linksEnd && adj != adjacentFaces.end(); ++adj )
2167         boundaryLink = adj->first->GetBoundaryLink( links, *(adj->second), 0, nodeToContain,
2168                                                     isAdjacentUsed, nbRecursionsLeft-1);
2169       if ( isAdjacentUsed ) *isAdjacentUsed = true;
2170     }
2171     return boundaryLink;
2172   }
2173   //================================================================================
2174   /*!
2175    * \brief Return a link ending at the given node but not avoidLink
2176    */
2177   //================================================================================
2178
2179   TLinkInSet QFace::GetLinkByNode( const TLinkSet&      links,
2180                                    const TChainLink&    avoidLink,
2181                                    const SMDS_MeshNode* nodeToContain) const
2182   {
2183     for ( int i = 0; i < _sides.size(); ++i )
2184       if ( avoidLink._qlink != _sides[i] &&
2185            (_sides[i]->node1() == nodeToContain || _sides[i]->node2() == nodeToContain ))
2186         return links.find( _sides[ i ]);
2187     return links.end();
2188   }
2189
2190   //================================================================================
2191   /*!
2192    * \brief Return normal to the i-th side pointing outside the face
2193    */
2194   //================================================================================
2195
2196   gp_Vec QFace::LinkNorm(const int i, SMESH_MesherHelper* /*uvHelper*/) const
2197   {
2198     gp_Vec norm, vecOut;
2199 //     if ( uvHelper ) {
2200 //       TopoDS_Face face = TopoDS::Face( uvHelper->GetSubShape());
2201 //       const SMDS_MeshNode* inFaceNode = uvHelper->GetNodeUVneedInFaceNode() ? GetNodeInFace() : 0;
2202 //       gp_XY uv1 = uvHelper->GetNodeUV( face, _sides[i]->node1(), inFaceNode );
2203 //       gp_XY uv2 = uvHelper->GetNodeUV( face, _sides[i]->node2(), inFaceNode );
2204 //       norm.SetCoord( uv1.Y() - uv2.Y(), uv2.X() - uv1.X(), 0 );
2205
2206 //       const QLink* otherLink = _sides[(i + 1) % _sides.size()];
2207 //       const SMDS_MeshNode* otherNode =
2208 //         otherLink->node1() == _sides[i]->node1() ? otherLink->node2() : otherLink->node1();
2209 //       gp_XY pIn = uvHelper->GetNodeUV( face, otherNode, inFaceNode );
2210 //       vecOut.SetCoord( uv1.X() - pIn.X(), uv1.Y() - pIn.Y(), 0 );
2211 //     }
2212 //     else {
2213       norm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
2214       gp_XYZ pIn = ( XYZ( _sides[0]->node1() ) +
2215                      XYZ( _sides[0]->node2() ) +
2216                      XYZ( _sides[1]->node1() )) / 3.;
2217       vecOut.SetXYZ( _sides[i]->MiddlePnt() - pIn );
2218       //}
2219     if ( norm * vecOut < 0 )
2220       norm.Reverse();
2221     double mag2 = norm.SquareMagnitude();
2222     if ( mag2 > numeric_limits<double>::min() )
2223       norm /= sqrt( mag2 );
2224     return norm;
2225   }
2226   //================================================================================
2227   /*!
2228    * \brief Move medium node of theLink according to its distance from boundary
2229    *  \param theLink - link to fix
2230    *  \param theRefVec - movement of boundary
2231    *  \param theLinks - all adjacent links of continous triangles
2232    *  \param theFaceHelper - helper is not used so far
2233    *  \param thePrevLen - distance from the boundary
2234    *  \param theStep - number of steps till movement propagation limit
2235    *  \param theLinkNorm - out normal to theLink
2236    *  \param theSign - 1 or -1 depending on movement of boundary
2237    *  \retval double - distance from boundary to propagation limit or other boundary
2238    */
2239   //================================================================================
2240
2241   double QFace::MoveByBoundary( const TChainLink&   theLink,
2242                                 const gp_Vec&       theRefVec,
2243                                 const TLinkSet&     theLinks,
2244                                 SMESH_MesherHelper* theFaceHelper,
2245                                 const double        thePrevLen,
2246                                 const int           theStep,
2247                                 gp_Vec*             theLinkNorm,
2248                                 double              theSign) const
2249   {
2250     if ( !theStep )
2251       return thePrevLen; // propagation limit reached
2252
2253     int iL; // index of theLink
2254     for ( iL = 0; iL < _sides.size(); ++iL )
2255       if ( theLink._qlink == _sides[ iL ])
2256         break;
2257
2258     MSG(string(theStep,'.')<<" Ref( "<<theRefVec.X()<<","<<theRefVec.Y()<<","<<theRefVec.Z()<<" )"
2259         <<" thePrevLen " << thePrevLen);
2260     MSG(string(theStep,'.')<<" "<<*theLink._qlink);
2261
2262     gp_Vec linkNorm = -LinkNorm( iL/*, theFaceHelper*/ ); // normal to theLink
2263     double refProj = theRefVec * linkNorm; // project movement vector to normal of theLink
2264     if ( theStep == theFirstStep )
2265       theSign = refProj < 0. ? -1. : 1.;
2266     else if ( theSign * refProj < 0.4 * theRefVec.Magnitude())
2267       return thePrevLen; // to propagate movement forward only, not in side dir or backward
2268
2269     int iL1 = (iL + 1) % 3, iL2 = (iL + 2) % 3; // indices of the two other links of triangle
2270     TLinkInSet link1 = theLinks.find( _sides[iL1] );
2271     TLinkInSet link2 = theLinks.find( _sides[iL2] );
2272     if ( link1 == theLinks.end() || link2 == theLinks.end() )
2273       return thePrevLen;
2274     const QFace* f1 = link1->NextFace( this ); // adjacent faces
2275     const QFace* f2 = link2->NextFace( this );
2276
2277     // propagate to adjacent faces till limit step or boundary
2278     double len1 = thePrevLen + (theLink->MiddlePnt() - _sides[iL1]->MiddlePnt()).Modulus();
2279     double len2 = thePrevLen + (theLink->MiddlePnt() - _sides[iL2]->MiddlePnt()).Modulus();
2280     gp_Vec linkDir1(0,0,0); // initialize to avoid valgrind error ("Conditional jump...")
2281     gp_Vec linkDir2(0,0,0);
2282     try {
2283       OCC_CATCH_SIGNALS;
2284       if ( f1 )
2285         len1 = f1->MoveByBoundary
2286           ( *link1, theRefVec, theLinks, theFaceHelper, len1, theStep-1, &linkDir1, theSign);
2287       else
2288         linkDir1 = LinkNorm( iL1/*, theFaceHelper*/ );
2289     } catch (...) {
2290       MSG( " --------------- EXCEPTION");
2291       return thePrevLen;
2292     }
2293     try {
2294       OCC_CATCH_SIGNALS;
2295       if ( f2 )
2296         len2 = f2->MoveByBoundary
2297           ( *link2, theRefVec, theLinks, theFaceHelper, len2, theStep-1, &linkDir2, theSign);
2298       else
2299         linkDir2 = LinkNorm( iL2/*, theFaceHelper*/ );
2300     } catch (...) {
2301       MSG( " --------------- EXCEPTION");
2302       return thePrevLen;
2303     }
2304
2305     double fullLen = 0;
2306     if ( theStep != theFirstStep )
2307     {
2308       // choose chain length by direction of propagation most codirected with theRefVec
2309       bool choose1 = ( theRefVec * linkDir1 * theSign > theRefVec * linkDir2 * theSign );
2310       fullLen = choose1 ? len1 : len2;
2311       double r = thePrevLen / fullLen;
2312
2313       gp_Vec move = linkNorm * refProj * ( 1 - r );
2314       theLink->Move( move, true );
2315
2316       MSG(string(theStep,'.')<<" Move "<< theLink->_mediumNode->GetID()<<
2317           " by " << refProj * ( 1 - r ) << " following " <<
2318           (choose1 ? *link1->_qlink : *link2->_qlink));
2319
2320       if ( theLinkNorm ) *theLinkNorm = linkNorm;
2321     }
2322     return fullLen;
2323   }
2324
2325   //================================================================================
2326   /*!
2327    * \brief Checks if the face is distorted due to bentLink
2328    */
2329   //================================================================================
2330
2331   bool QFace::IsSpoiled(const QLink* bentLink ) const
2332   {
2333     // code is valid for convex faces only
2334     gp_XYZ gc(0,0,0);
2335     for ( TIDSortedNodeSet::const_iterator n = begin(); n!=end(); ++n)
2336       gc += XYZ( *n ) / size();
2337     for (unsigned i = 0; i < _sides.size(); ++i )
2338     {
2339       if ( _sides[i] == bentLink ) continue;
2340       gp_Vec linkNorm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
2341       gp_Vec vecOut( gc, _sides[i]->MiddlePnt() );
2342       if ( linkNorm * vecOut < 0 )
2343         linkNorm.Reverse();
2344       double mag2 = linkNorm.SquareMagnitude();
2345       if ( mag2 > numeric_limits<double>::min() )
2346         linkNorm /= sqrt( mag2 );
2347       gp_Vec vecBent    ( _sides[i]->MiddlePnt(), bentLink->MediumPnt());
2348       gp_Vec vecStraight( _sides[i]->MiddlePnt(), bentLink->MiddlePnt());
2349       if ( vecBent * linkNorm > -0.1*vecStraight.Magnitude() )
2350         return true;
2351     }
2352     return false;
2353     
2354   }
2355
2356   //================================================================================
2357   /*!
2358    * \brief Find pairs of continues faces 
2359    */
2360   //================================================================================
2361
2362   void QLink::SetContinuesFaces() const
2363   {
2364     //       x0         x - QLink, [-|] - QFace, v - volume
2365     //   v0  |   v1   
2366     //       |          Between _faces of link x2 two vertical faces are continues
2367     // x1----x2-----x3  and two horizontal faces are continues. We set vertical faces
2368     //       |          to _faces[0] and _faces[1] and horizontal faces to
2369     //   v2  |   v3     _faces[2] and _faces[3] (or vise versa).
2370     //       x4
2371
2372     if ( _faces.empty() )
2373       return;
2374     int iFaceCont = -1;
2375     for ( int iF = 1; iFaceCont < 0 && iF < _faces.size(); ++iF )
2376     {
2377       // look for a face bounding none of volumes bound by _faces[0]
2378       bool sameVol = false;
2379       int nbVol = _faces[iF]->NbVolumes();
2380       for ( int iV = 0; !sameVol && iV < nbVol; ++iV )
2381         sameVol = ( _faces[iF]->_volumes[iV] == _faces[0]->_volumes[0] ||
2382                     _faces[iF]->_volumes[iV] == _faces[0]->_volumes[1]);
2383       if ( !sameVol )
2384         iFaceCont = iF;
2385     }
2386     if ( iFaceCont > 0 ) // continues faces found, set one by the other
2387     {
2388       if ( iFaceCont != 1 )
2389         std::swap( _faces[1], _faces[iFaceCont] );
2390     }
2391     else if ( _faces.size() > 1 ) // not found, set NULL by the first face
2392     {
2393       _faces.insert( ++_faces.begin(), 0 );
2394     }
2395   }
2396   //================================================================================
2397   /*!
2398    * \brief Return a face continues to the given one
2399    */
2400   //================================================================================
2401
2402   const QFace* QLink::GetContinuesFace( const QFace* face ) const
2403   {
2404     for ( int i = 0; i < _faces.size(); ++i ) {
2405       if ( _faces[i] == face ) {
2406         int iF = i < 2 ? 1-i : 5-i;
2407         return iF < _faces.size() ? _faces[iF] : 0;
2408       }
2409     }
2410     return 0;
2411   }
2412   //================================================================================
2413   /*!
2414    * \brief True if link is on mesh boundary
2415    */
2416   //================================================================================
2417
2418   bool QLink::OnBoundary() const
2419   {
2420     for ( int i = 0; i < _faces.size(); ++i )
2421       if (_faces[i] && _faces[i]->IsBoundary()) return true;
2422     return false;
2423   }
2424   //================================================================================
2425   /*!
2426    * \brief Return normal of link of the chain
2427    */
2428   //================================================================================
2429
2430   gp_Vec TChainLink::Normal() const {
2431     gp_Vec norm;
2432     if (_qfaces[0]) norm  = _qfaces[0]->_normal;
2433     if (_qfaces[1]) norm += _qfaces[1]->_normal;
2434     return norm;
2435   }
2436   //================================================================================
2437   /*!
2438    * \brief Move medium nodes of vertical links of pentahedrons adjacent by side faces
2439    */
2440   //================================================================================
2441
2442   void fixPrism( TChain& allLinks )
2443   {
2444     // separate boundary links from internal ones
2445     typedef set<const QLink*/*, QLink::PtrComparator*/> QLinkSet;
2446     QLinkSet interLinks, bndLinks1, bndLink2;
2447
2448     bool isCurved = false;
2449     for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
2450       if ( (*lnk)->OnBoundary() )
2451         bndLinks1.insert( lnk->_qlink );
2452       else
2453         interLinks.insert( lnk->_qlink );
2454       isCurved = isCurved || !(*lnk)->IsStraight();
2455     }
2456     if ( !isCurved )
2457       return; // no need to move
2458
2459     QLinkSet *curBndLinks = &bndLinks1, *newBndLinks = &bndLink2;
2460
2461     while ( !interLinks.empty() && !curBndLinks->empty() )
2462     {
2463       // propagate movement from boundary links to connected internal links
2464       QLinkSet::iterator bnd = curBndLinks->begin(), bndEnd = curBndLinks->end();
2465       for ( ; bnd != bndEnd; ++bnd )
2466       {
2467         const QLink* bndLink = *bnd;
2468         for ( int i = 0; i < bndLink->_faces.size(); ++i ) // loop on faces of bndLink
2469         {
2470           const QFace* face = bndLink->_faces[i]; // quadrange lateral face of a prism
2471           if ( !face ) continue;
2472           // find and move internal link opposite to bndLink within the face
2473           int interInd = ( face->LinkIndex( bndLink ) + 2 ) % face->_sides.size();
2474           const QLink* interLink = face->_sides[ interInd ];
2475           QLinkSet::iterator pInterLink = interLinks.find( interLink );
2476           if ( pInterLink == interLinks.end() ) continue; // not internal link
2477           interLink->Move( bndLink->_nodeMove );
2478           // treated internal links become new boundary ones
2479           interLinks. erase( pInterLink );
2480           newBndLinks->insert( interLink );
2481         }
2482       }
2483       curBndLinks->clear();
2484       std::swap( curBndLinks, newBndLinks );
2485     }
2486   }
2487
2488   //================================================================================
2489   /*!
2490    * \brief Fix links of continues triangles near curved boundary
2491    */
2492   //================================================================================
2493
2494   void fixTriaNearBoundary( TChain & allLinks, SMESH_MesherHelper& /*helper*/)
2495   {
2496     if ( allLinks.empty() ) return;
2497
2498     TLinkSet linkSet( allLinks.begin(), allLinks.end());
2499     TLinkInSet linkIt = linkSet.begin(), linksEnd = linkSet.end();
2500
2501     for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt)
2502     {
2503       if ( linkIt->IsBoundary() && !(*linkIt)->IsStraight() && linkIt->_qfaces[0])
2504       {
2505         // move iff a boundary link is bent towards inside of a face (issue 0021084)
2506         const QFace* face = linkIt->_qfaces[0];
2507         gp_XYZ pIn = ( face->_sides[0]->MiddlePnt() +
2508                        face->_sides[1]->MiddlePnt() +
2509                        face->_sides[2]->MiddlePnt() ) / 3.;
2510         gp_XYZ insideDir( pIn - (*linkIt)->MiddlePnt());
2511         bool linkBentInside = ((*linkIt)->_nodeMove.Dot( insideDir ) > 0 );
2512         //if ( face->IsSpoiled( linkIt->_qlink ))
2513         if ( linkBentInside )
2514           face->MoveByBoundary( *linkIt, (*linkIt)->_nodeMove, linkSet );
2515       }
2516     }
2517   }
2518
2519   //================================================================================
2520   /*!
2521    * \brief Detect rectangular structure of links and build chains from them
2522    */
2523   //================================================================================
2524
2525   enum TSplitTriaResult {
2526     _OK, _NO_CORNERS, _FEW_ROWS, _MANY_ROWS, _NO_SIDELINK, _BAD_MIDQUAD, _NOT_RECT,
2527     _NO_MIDQUAD, _NO_UPTRIA, _BAD_SET_SIZE, _BAD_CORNER, _BAD_START, _NO_BOTLINK, _TWISTED_CHAIN };
2528
2529   TSplitTriaResult splitTrianglesIntoChains( TChain &            allLinks,
2530                                              vector< TChain> &   resultChains,
2531                                              SMDS_TypeOfPosition pos )
2532   {
2533     // put links in the set and evalute number of result chains by number of boundary links
2534     TLinkSet linkSet;
2535     int nbBndLinks = 0;
2536     for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
2537       linkSet.insert( *lnk );
2538       nbBndLinks += lnk->IsBoundary();
2539     }
2540     resultChains.clear();
2541     resultChains.reserve( nbBndLinks / 2 );
2542
2543     TLinkInSet linkIt, linksEnd = linkSet.end();
2544
2545     // find a boundary link with corner node; corner node has position pos-2
2546     // i.e. SMDS_TOP_VERTEX for links on faces and SMDS_TOP_EDGE for
2547     // links in volume
2548     SMDS_TypeOfPosition cornerPos = SMDS_TypeOfPosition(pos-2);
2549     const SMDS_MeshNode* corner = 0;
2550     for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt )
2551       if ( linkIt->IsBoundary() && (corner = (*linkIt)->EndPosNode(cornerPos)))
2552         break;
2553     if ( !corner)
2554       return _NO_CORNERS;
2555
2556     TLinkInSet           startLink = linkIt;
2557     const SMDS_MeshNode* startCorner = corner;
2558     vector< TChain* >    rowChains;
2559     int iCol = 0;
2560
2561     while ( startLink != linksEnd) // loop on columns
2562     {
2563       // We suppose we have a rectangular structure like shown here. We have found a
2564       //               corner of the rectangle (startCorner) and a boundary link sharing  
2565       //    |/  |/  |  the startCorner (startLink). We are going to loop on rows of the   
2566       //  --o---o---o  structure making several chains at once. One chain (columnChain)   
2567       //    |\  |  /|  starts at startLink and continues upward (we look at the structure 
2568       //  \ | \ | / |  from such point that startLink is on the bottom of the structure). 
2569       //   \|  \|/  |  While going upward we also fill horizontal chains (rowChains) we   
2570       //  --o---o---o  encounter.                                                         
2571       //   /|\  |\  |
2572       //  / | \ | \ |  startCorner
2573       //    |  \|  \|,'
2574       //  --o---o---o
2575       //          `.startLink
2576
2577       if ( resultChains.size() == nbBndLinks / 2 )
2578         return _NOT_RECT;
2579       resultChains.push_back( TChain() );
2580       TChain& columnChain = resultChains.back();
2581
2582       TLinkInSet botLink = startLink; // current horizontal link to go up from
2583       corner = startCorner; // current corner the botLink ends at
2584       int iRow = 0;
2585       while ( botLink != linksEnd ) // loop on rows
2586       {
2587         // add botLink to the columnChain
2588         columnChain.push_back( *botLink );
2589
2590         const QFace* botTria = botLink->_qfaces[0]; // bottom triangle bound by botLink
2591         if ( !botTria )
2592         { // the column ends
2593           if ( botLink == startLink )
2594             return _TWISTED_CHAIN; // issue 0020951
2595           linkSet.erase( botLink );
2596           if ( iRow != rowChains.size() )
2597             return _FEW_ROWS; // different nb of rows in columns
2598           break;
2599         }
2600         // find the link dividing the quadrangle (midQuadLink) and vertical boundary
2601         // link ending at <corner> (sideLink); there are two cases:
2602         // 1) midQuadLink does not end at <corner>, then we easily find it by botTria,
2603         //   since midQuadLink is not at boundary while sideLink is.
2604         // 2) midQuadLink ends at <corner>
2605         bool isCase2;
2606         TLinkInSet midQuadLink = linksEnd;
2607         TLinkInSet sideLink = botTria->GetBoundaryLink( linkSet, *botLink, &midQuadLink,
2608                                                         corner, &isCase2 );
2609         if ( isCase2 ) { // find midQuadLink among links of botTria
2610           midQuadLink = botTria->GetLinkByNode( linkSet, *botLink, corner );
2611           if ( midQuadLink->IsBoundary() )
2612             return _BAD_MIDQUAD;
2613         }
2614         if ( sideLink == linksEnd || midQuadLink == linksEnd || sideLink == midQuadLink )
2615           return sideLink == linksEnd ? _NO_SIDELINK : _NO_MIDQUAD;
2616
2617         // fill chains
2618         columnChain.push_back( *midQuadLink );
2619         if ( iRow >= rowChains.size() ) {
2620           if ( iCol > 0 )
2621             return _MANY_ROWS; // different nb of rows in columns
2622           if ( resultChains.size() == nbBndLinks / 2 )
2623             return _NOT_RECT;
2624           resultChains.push_back( TChain() );
2625           rowChains.push_back( & resultChains.back() );
2626         }
2627         rowChains[iRow]->push_back( *sideLink );
2628         rowChains[iRow]->push_back( *midQuadLink );
2629
2630         const QFace* upTria = midQuadLink->NextFace( botTria ); // upper tria of the rectangle
2631         if ( !upTria)
2632           return _NO_UPTRIA;
2633         if ( iRow == 0 ) {
2634           // prepare startCorner and startLink for the next column
2635           startCorner = startLink->NextNode( startCorner );
2636           if (isCase2)
2637             startLink = botTria->GetBoundaryLink( linkSet, *botLink, 0, startCorner );
2638           else
2639             startLink = upTria->GetBoundaryLink( linkSet, *midQuadLink, 0, startCorner );
2640           // check if no more columns remains
2641           if ( startLink != linksEnd ) {
2642             const SMDS_MeshNode* botNode = startLink->NextNode( startCorner );
2643             if ( (isCase2 ? botTria : upTria)->Contains( botNode ))
2644               startLink = linksEnd; // startLink bounds upTria or botTria
2645             else if ( startLink == botLink || startLink == midQuadLink || startLink == sideLink )
2646               return _BAD_START;
2647           }
2648         }
2649         // find bottom link and corner for the next row
2650         corner = sideLink->NextNode( corner );
2651         // next bottom link ends at the new corner
2652         linkSet.erase( botLink );
2653         botLink = upTria->GetLinkByNode( linkSet, (isCase2 ? *sideLink : *midQuadLink), corner );
2654         if ( botLink == linksEnd || botLink == midQuadLink || botLink == sideLink)
2655           return _NO_BOTLINK;
2656         if ( midQuadLink == startLink || sideLink == startLink )
2657           return _TWISTED_CHAIN; // issue 0020951
2658         linkSet.erase( midQuadLink );
2659         linkSet.erase( sideLink );
2660
2661         // make faces neighboring the found ones be boundary
2662         if ( startLink != linksEnd ) {
2663           const QFace* tria = isCase2 ? botTria : upTria;
2664           for ( int iL = 0; iL < 3; ++iL ) {
2665             linkIt = linkSet.find( tria->_sides[iL] );
2666             if ( linkIt != linksEnd )
2667               linkIt->RemoveFace( tria );
2668           }
2669         }
2670         if ( botLink->_qfaces[0] == upTria || botLink->_qfaces[1] == upTria )
2671           botLink->RemoveFace( upTria ); // make next botTria first in vector
2672
2673         iRow++;
2674       } // loop on rows
2675
2676       iCol++;
2677     }
2678     // In the linkSet, there must remain the last links of rowChains; add them
2679     if ( linkSet.size() != rowChains.size() )
2680       return _BAD_SET_SIZE;
2681     for ( int iRow = 0; iRow < rowChains.size(); ++iRow ) {
2682       // find the link (startLink) ending at startCorner
2683       corner = 0;
2684       for ( startLink = linkSet.begin(); startLink != linksEnd; ++startLink ) {
2685         if ( (*startLink)->node1() == startCorner ) {
2686           corner = (*startLink)->node2(); break;
2687         }
2688         else if ( (*startLink)->node2() == startCorner) {
2689           corner = (*startLink)->node1(); break;
2690         }
2691       }
2692       if ( startLink == linksEnd )
2693         return _BAD_CORNER;
2694       rowChains[ iRow ]->push_back( *startLink );
2695       linkSet.erase( startLink );
2696       startCorner = corner;
2697     }
2698
2699     return _OK;
2700   }
2701 } //namespace
2702
2703 //=======================================================================
2704 /*!
2705  * \brief Move medium nodes of faces and volumes to fix distorted elements
2706  * \param volumeOnly - to fix nodes on faces or not, if the shape is solid
2707  * 
2708  * Issue 0020307: EDF 992 SMESH : Linea/Quadratic with Medium Node on Geometry
2709  */
2710 //=======================================================================
2711
2712 void SMESH_MesherHelper::FixQuadraticElements(bool volumeOnly)
2713 {
2714   // 0. Apply algorithm to solids or geom faces
2715   // ----------------------------------------------
2716   if ( myShape.IsNull() ) {
2717     if ( !myMesh->HasShapeToMesh() ) return;
2718     SetSubShape( myMesh->GetShapeToMesh() );
2719
2720 #ifdef _DEBUG_
2721     int nbSolids = 0;
2722     TopTools_IndexedMapOfShape solids;
2723     TopExp::MapShapes(myShape,TopAbs_SOLID,solids);
2724     nbSolids = solids.Extent();
2725 #endif
2726     TopTools_MapOfShape faces; // faces not in solid or in not meshed solid
2727     for ( TopExp_Explorer f(myShape,TopAbs_FACE,TopAbs_SOLID); f.More(); f.Next() ) {
2728       faces.Add( f.Current() ); // not in solid
2729     }
2730     for ( TopExp_Explorer s(myShape,TopAbs_SOLID); s.More(); s.Next() ) {
2731       if ( myMesh->GetSubMesh( s.Current() )->IsEmpty() ) { // get faces of solid
2732         for ( TopExp_Explorer f( s.Current(), TopAbs_FACE); f.More(); f.Next() )
2733           faces.Add( f.Current() ); // in not meshed solid
2734       }
2735       else { // fix nodes in the solid and its faces
2736         MSG("FIX SOLID " << nbSolids-- << " #" << GetMeshDS()->ShapeToIndex(s.Current()));
2737         SMESH_MesherHelper h(*myMesh);
2738         h.SetSubShape( s.Current() );
2739         h.FixQuadraticElements(false);
2740       }
2741     }
2742     // fix nodes on geom faces
2743 #ifdef _DEBUG_
2744     //int nbfaces = faces.Extent();
2745 #endif
2746     for ( TopTools_MapIteratorOfMapOfShape fIt( faces ); fIt.More(); fIt.Next() ) {
2747       MSG("FIX FACE " << nbfaces-- << " #" << GetMeshDS()->ShapeToIndex(fIt.Key()));
2748       SMESH_MesherHelper h(*myMesh);
2749       h.SetSubShape( fIt.Key() );
2750       h.FixQuadraticElements(true);
2751     }
2752     //perf_print_all_meters(1);
2753     return;
2754   }
2755
2756   // 1. Find out type of elements and get iterator on them
2757   // ---------------------------------------------------
2758
2759   SMDS_ElemIteratorPtr elemIt;
2760   SMDSAbs_ElementType elemType = SMDSAbs_All;
2761
2762   SMESH_subMesh* submesh = myMesh->GetSubMeshContaining( myShapeID );
2763   if ( !submesh )
2764     return;
2765   if ( SMESHDS_SubMesh* smDS = submesh->GetSubMeshDS() ) {
2766     elemIt = smDS->GetElements();
2767     if ( elemIt->more() ) {
2768       elemType = elemIt->next()->GetType();
2769       elemIt = smDS->GetElements();
2770     }
2771   }
2772   if ( !elemIt || !elemIt->more() || elemType < SMDSAbs_Face )
2773     return;
2774
2775   // 2. Fill in auxiliary data structures
2776   // ----------------------------------
2777
2778   set< QLink > links;
2779   set< QFace > faces;
2780   set< QLink >::iterator pLink;
2781   set< QFace >::iterator pFace;
2782
2783   bool isCurved = false;
2784   //bool hasRectFaces = false;
2785   //set<int> nbElemNodeSet;
2786
2787   if ( elemType == SMDSAbs_Volume )
2788   {
2789     SMDS_VolumeTool volTool;
2790     while ( elemIt->more() ) // loop on volumes
2791     {
2792       const SMDS_MeshElement* vol = elemIt->next();
2793       if ( !vol->IsQuadratic() || !volTool.Set( vol ))
2794         return; //continue;
2795       for ( int iF = 0; iF < volTool.NbFaces(); ++iF ) // loop on faces of volume
2796       {
2797         int nbN = volTool.NbFaceNodes( iF );
2798         //nbElemNodeSet.insert( nbN );
2799         const SMDS_MeshNode** faceNodes = volTool.GetFaceNodes( iF );
2800         vector< const QLink* > faceLinks( nbN/2 );
2801         for ( int iN = 0; iN < nbN; iN += 2 ) // loop on links of a face
2802         {
2803           // store QLink
2804           QLink link( faceNodes[iN], faceNodes[iN+2], faceNodes[iN+1] );
2805           pLink = links.insert( link ).first;
2806           faceLinks[ iN/2 ] = & *pLink;
2807           if ( !isCurved )
2808             isCurved = !link.IsStraight();
2809           if ( link.MediumPos() == SMDS_TOP_3DSPACE && !link.IsStraight() )
2810             return; // already fixed
2811         }
2812         // store QFace
2813         pFace = faces.insert( QFace( faceLinks )).first;
2814         if ( pFace->NbVolumes() == 0 )
2815           pFace->AddSelfToLinks();
2816         pFace->SetVolume( vol );
2817 //         hasRectFaces = hasRectFaces ||
2818 //           ( volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_HEXA ||
2819 //             volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_PENTA );
2820 #ifdef _DEBUG_
2821         if ( nbN == 6 )
2822           pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],faceNodes[4]);
2823         else
2824           pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],
2825                                                faceNodes[4],faceNodes[6] );
2826 #endif
2827       }
2828     }
2829     set< QLink >::iterator pLink = links.begin();
2830     for ( ; pLink != links.end(); ++pLink )
2831       pLink->SetContinuesFaces();
2832   }
2833   else
2834   {
2835     while ( elemIt->more() ) // loop on faces
2836     {
2837       const SMDS_MeshElement* face = elemIt->next();
2838       if ( !face->IsQuadratic() )
2839         continue;
2840       //nbElemNodeSet.insert( face->NbNodes() );
2841       int nbN = face->NbNodes()/2;
2842       vector< const QLink* > faceLinks( nbN );
2843       for ( int iN = 0; iN < nbN; ++iN ) // loop on links of a face
2844       {
2845         // store QLink
2846         QLink link( face->GetNode(iN), face->GetNode((iN+1)%nbN), face->GetNode(iN+nbN) );
2847         pLink = links.insert( link ).first;
2848         faceLinks[ iN ] = & *pLink;
2849         if ( !isCurved )
2850           isCurved = !link.IsStraight();
2851       }
2852       // store QFace
2853       pFace = faces.insert( QFace( faceLinks )).first;
2854       pFace->AddSelfToLinks();
2855       //hasRectFaces = ( hasRectFaces || nbN == 4 );
2856     }
2857   }
2858   if ( !isCurved )
2859     return; // no curved edges of faces
2860
2861   // 3. Compute displacement of medium nodes
2862   // -------------------------------------
2863
2864   // two loops on faces: the first is to treat boundary links, the second is for internal ones
2865   TopLoc_Location loc;
2866   // not treat boundary of volumic submesh
2867   int isInside = ( elemType == SMDSAbs_Volume && volumeOnly ) ? 1 : 0;
2868   for ( ; isInside < 2; ++isInside ) {
2869     MSG( "--------------- LOOP (inside=" << isInside << ") ------------------");
2870     SMDS_TypeOfPosition pos = isInside ? SMDS_TOP_3DSPACE : SMDS_TOP_FACE;
2871     SMDS_TypeOfPosition bndPos = isInside ? SMDS_TOP_FACE : SMDS_TOP_EDGE;
2872
2873     for ( pFace = faces.begin(); pFace != faces.end(); ++pFace ) {
2874       if ( bool(isInside) == pFace->IsBoundary() )
2875         continue;
2876       for ( int dir = 0; dir < 2; ++dir ) // 2 directions of propagation from quadrangle
2877       {
2878         MSG( "CHAIN");
2879         // make chain of links connected via continues faces
2880         int error = ERR_OK;
2881         TChain rawChain;
2882         if ( !pFace->GetLinkChain( dir, rawChain, pos, error) && error ==ERR_UNKNOWN ) continue;
2883         rawChain.reverse();
2884         if ( !pFace->GetLinkChain( dir+2, rawChain, pos, error ) && error ==ERR_UNKNOWN ) continue;
2885
2886         vector< TChain > chains;
2887         if ( error == ERR_OK ) { // chain contains continues rectangles
2888           chains.resize(1);
2889           chains[0].splice( chains[0].begin(), rawChain );
2890         }
2891         else if ( error == ERR_TRI ) {  // chain contains continues triangles
2892           TSplitTriaResult res = splitTrianglesIntoChains( rawChain, chains, pos );
2893           if ( res != _OK ) { // not quadrangles split into triangles
2894             fixTriaNearBoundary( rawChain, *this );
2895             break;
2896           }
2897         }
2898         else if ( error == ERR_PRISM ) { // quadrangle side faces of prisms
2899           fixPrism( rawChain );
2900           break;
2901         }
2902         else {
2903           continue;
2904         }
2905         for ( int iC = 0; iC < chains.size(); ++iC )
2906         {
2907           TChain& chain = chains[iC];
2908           if ( chain.empty() ) continue;
2909           if ( chain.front()->IsStraight() && chain.back()->IsStraight() ) {
2910             MSG("3D straight - ignore");
2911             continue;
2912           }
2913           if ( chain.front()->MediumPos() > bndPos ||
2914                chain.back()->MediumPos() > bndPos ) {
2915             MSG("Internal chain - ignore");
2916             continue;
2917           }
2918           // mesure chain length and compute link position along the chain
2919           double chainLen = 0;
2920           vector< double > linkPos;
2921           MSGBEG( "Link medium nodes: ");
2922           TChain::iterator link0 = chain.begin(), link1 = chain.begin(), link2;
2923           for ( ++link1; link1 != chain.end(); ++link1, ++link0 ) {
2924             MSGBEG( (*link0)->_mediumNode->GetID() << "-" <<(*link1)->_mediumNode->GetID()<<" ");
2925             double len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
2926             while ( len < numeric_limits<double>::min() ) { // remove degenerated link
2927               link1 = chain.erase( link1 );
2928               if ( link1 == chain.end() )
2929                 break;
2930               len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
2931             }
2932             chainLen += len;
2933             linkPos.push_back( chainLen );
2934           }
2935           MSG("");
2936           if ( linkPos.size() < 2 )
2937             continue;
2938
2939           gp_Vec move0 = chain.front()->_nodeMove;
2940           gp_Vec move1 = chain.back ()->_nodeMove;
2941
2942           TopoDS_Face face;
2943           bool checkUV = true;
2944           if ( !isInside ) {
2945             // compute node displacement of end links in parametric space of face
2946             const SMDS_MeshNode* nodeOnFace = (*(++chain.begin()))->_mediumNode;
2947             TopoDS_Shape f = GetSubShapeByNode( nodeOnFace, GetMeshDS() );
2948             if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE )
2949             {
2950               face = TopoDS::Face( f );
2951               Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
2952               bool isStraight[2];
2953               for ( int is1 = 0; is1 < 2; ++is1 ) // move0 or move1
2954               {
2955                 TChainLink& link = is1 ? chain.back() : chain.front();
2956                 gp_XY uvm = GetNodeUV( face, link->_mediumNode, nodeOnFace, &checkUV);
2957                 gp_XY uv1 = GetNodeUV( face, link->node1(), nodeOnFace, &checkUV);
2958                 gp_XY uv2 = GetNodeUV( face, link->node2(), nodeOnFace, &checkUV);
2959                 gp_XY uv12 = GetMiddleUV( surf, uv1, uv2);
2960                 // uvMove = uvm - uv12
2961                 gp_XY uvMove = applyIn2D(surf, uvm, uv12, gp_XY_Subtracted, /*inPeriod=*/false);
2962                 ( is1 ? move1 : move0 ).SetCoord( uvMove.X(), uvMove.Y(), 0 );
2963                 if ( !is1 ) // correct nodeOnFace for move1 (issue 0020919)
2964                   nodeOnFace = (*(++chain.rbegin()))->_mediumNode;
2965                 isStraight[is1] = isStraightLink( (uv2-uv1).SquareModulus(),uvMove.SquareModulus());
2966               }
2967 //               if ( move0.SquareMagnitude() < straightTol2 &&
2968 //                    move1.SquareMagnitude() < straightTol2 ) {
2969               if ( isStraight[0] && isStraight[1] ) {
2970                 MSG("2D straight - ignore");
2971                 continue; // straight - no need to move nodes of internal links
2972               }
2973             }
2974           }
2975           gp_Trsf trsf;
2976           if ( isInside || face.IsNull() )
2977           {
2978             // compute node displacement of end links in their local coord systems
2979             {
2980               TChainLink& ln0 = chain.front(), ln1 = *(++chain.begin());
2981               trsf.SetTransformation( gp_Ax3( gp::Origin(), ln0.Normal(),
2982                                               gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
2983               move0.Transform(trsf);
2984             }
2985             {
2986               TChainLink& ln0 = *(++chain.rbegin()), ln1 = chain.back();
2987               trsf.SetTransformation( gp_Ax3( gp::Origin(), ln1.Normal(),
2988                                               gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
2989               move1.Transform(trsf);
2990             }
2991           }
2992           // compute displacement of medium nodes
2993           link2 = chain.begin();
2994           link0 = link2++;
2995           link1 = link2++;
2996           for ( int i = 0; link2 != chain.end(); ++link0, ++link1, ++link2, ++i )
2997           {
2998             double r = linkPos[i] / chainLen;
2999             // displacement in local coord system
3000             gp_Vec move = (1. - r) * move0 + r * move1;
3001             if ( isInside || face.IsNull()) {
3002               // transform to global
3003               gp_Vec x01( (*link0)->MiddlePnt(), (*link1)->MiddlePnt() );
3004               gp_Vec x12( (*link1)->MiddlePnt(), (*link2)->MiddlePnt() );
3005               gp_Vec x = x01.Normalized() + x12.Normalized();
3006               trsf.SetTransformation( gp_Ax3( gp::Origin(), link1->Normal(), x), gp_Ax3() );
3007               move.Transform(trsf);
3008             }
3009             else {
3010               // compute 3D displacement by 2D one
3011               Handle(Geom_Surface) s = BRep_Tool::Surface(face,loc);
3012               gp_XY oldUV   = GetNodeUV( face, (*link1)->_mediumNode, 0, &checkUV);
3013               gp_XY newUV   = applyIn2D( s, oldUV, gp_XY( move.X(),move.Y()), gp_XY_Added);
3014               gp_Pnt newPnt = s->Value( newUV.X(), newUV.Y());
3015               move = gp_Vec( XYZ((*link1)->_mediumNode), newPnt.Transformed(loc) );
3016 #ifdef _DEBUG_
3017               if ( (XYZ((*link1)->node1()) - XYZ((*link1)->node2())).SquareModulus() <
3018                    move.SquareMagnitude())
3019               {
3020                 gp_XY uv0 = GetNodeUV( face, (*link0)->_mediumNode, 0, &checkUV);
3021                 gp_XY uv2 = GetNodeUV( face, (*link2)->_mediumNode, 0, &checkUV);
3022                 MSG( "TOO LONG MOVE \t" <<
3023                      "uv0: "<<uv0.X()<<", "<<uv0.Y()<<" \t" <<
3024                      "uv2: "<<uv2.X()<<", "<<uv2.Y()<<" \t" <<
3025                      "uvOld: "<<oldUV.X()<<", "<<oldUV.Y()<<" \t" <<
3026                      "newUV: "<<newUV.X()<<", "<<newUV.Y()<<" \t");
3027               }
3028 #endif
3029             }
3030             (*link1)->Move( move );
3031             MSG( "Move " << (*link1)->_mediumNode->GetID() << " following "
3032                  << chain.front()->_mediumNode->GetID() <<"-"
3033                  << chain.back ()->_mediumNode->GetID() <<
3034                  " by " << move.Magnitude());
3035           }
3036         } // loop on chains of links
3037       } // loop on 2 directions of propagation from quadrangle
3038     } // loop on faces
3039   }
3040
3041   // 4. Move nodes
3042   // -----------
3043
3044   for ( pLink = links.begin(); pLink != links.end(); ++pLink ) {
3045     if ( pLink->IsMoved() ) {
3046       //gp_Pnt p = pLink->MediumPnt() + pLink->Move();
3047       gp_Pnt p = pLink->MiddlePnt() + pLink->Move();
3048       GetMeshDS()->MoveNode( pLink->_mediumNode, p.X(), p.Y(), p.Z());
3049     }
3050   }
3051 }
3052
3053 //=======================================================================
3054 /*!
3055  * \brief Iterator on ancestors of the given type
3056  */
3057 //=======================================================================
3058
3059 struct TAncestorsIterator : public SMDS_Iterator<const TopoDS_Shape*>
3060 {
3061   TopTools_ListIteratorOfListOfShape _ancIter;
3062   TopAbs_ShapeEnum                   _type;
3063   TopTools_MapOfShape                _encountered;
3064   TAncestorsIterator( const TopTools_ListOfShape& ancestors, TopAbs_ShapeEnum type)
3065     : _ancIter( ancestors ), _type( type )
3066   {
3067     if ( _ancIter.More() ) {
3068       if ( _ancIter.Value().ShapeType() != _type ) next();
3069       else _encountered.Add( _ancIter.Value() );
3070     }
3071   }
3072   virtual bool more()
3073   {
3074     return _ancIter.More();
3075   }
3076   virtual const TopoDS_Shape* next()
3077   {
3078     const TopoDS_Shape* s = _ancIter.More() ? & _ancIter.Value() : 0;
3079     if ( _ancIter.More() )
3080       for ( _ancIter.Next();  _ancIter.More(); _ancIter.Next())
3081         if ( _ancIter.Value().ShapeType() == _type && _encountered.Add( _ancIter.Value() ))
3082           break;
3083     return s;
3084   }
3085 };
3086
3087 //=======================================================================
3088 /*!
3089  * \brief Return iterator on ancestors of the given type
3090  */
3091 //=======================================================================
3092
3093 PShapeIteratorPtr SMESH_MesherHelper::GetAncestors(const TopoDS_Shape& shape,
3094                                                    const SMESH_Mesh&   mesh,
3095                                                    TopAbs_ShapeEnum    ancestorType)
3096 {
3097   return PShapeIteratorPtr( new TAncestorsIterator( mesh.GetAncestors(shape), ancestorType));
3098 }