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