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