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