Salome HOME
ed6021089369bdb10565e735407cb2bb8d4492e6
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_Mesher.cxx
1 // Copyright (C) 2007-2021  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 //  NETGENPlugin : C++ implementation
24 // File      : NETGENPlugin_Mesher.cxx
25 // Author    : Michael Sazonov (OCN)
26 // Date      : 31/03/2006
27 // Project   : SALOME
28 //=============================================================================
29
30 #include "NETGENPlugin_Mesher.hxx"
31 #include "NETGENPlugin_Hypothesis_2D.hxx"
32 #include "NETGENPlugin_SimpleHypothesis_3D.hxx"
33
34 #include <SMDS_FaceOfNodes.hxx>
35 #include <SMDS_LinearEdge.hxx>
36 #include <SMDS_MeshElement.hxx>
37 #include <SMDS_MeshNode.hxx>
38 #include <SMESHDS_Mesh.hxx>
39 #include <SMESH_Block.hxx>
40 #include <SMESH_Comment.hxx>
41 #include <SMESH_ComputeError.hxx>
42 #include <SMESH_ControlPnt.hxx>
43 #include <SMESH_File.hxx>
44 #include <SMESH_Gen_i.hxx>
45 #include <SMESH_Mesh.hxx>
46 #include <SMESH_MesherHelper.hxx>
47 #include <SMESH_subMesh.hxx>
48 #include <StdMeshers_QuadToTriaAdaptor.hxx>
49 #include <StdMeshers_ViscousLayers2D.hxx>
50
51 #include <SALOMEDS_Tool.hxx>
52
53 #include <utilities.h>
54
55 #include <BRepAdaptor_Surface.hxx>
56 #include <BRepBuilderAPI_Copy.hxx>
57 #include <BRepLProp_SLProps.hxx>
58 #include <BRepMesh_IncrementalMesh.hxx>
59 #include <BRep_Builder.hxx>
60 #include <BRep_Tool.hxx>
61 #include <Bnd_B3d.hxx>
62 #include <GeomLib_IsPlanarSurface.hxx>
63 #include <NCollection_Map.hxx>
64 #include <Poly_Triangulation.hxx>
65 #include <Standard_ErrorHandler.hxx>
66 #include <Standard_ProgramError.hxx>
67 #include <TColStd_MapOfInteger.hxx>
68 #include <TopExp.hxx>
69 #include <TopExp_Explorer.hxx>
70 #include <TopLoc_Location.hxx>
71 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
72 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
73 #include <TopTools_DataMapOfShapeInteger.hxx>
74 #include <TopTools_DataMapOfShapeShape.hxx>
75 #include <TopTools_MapOfShape.hxx>
76 #include <TopoDS.hxx>
77 #include <TopoDS_Compound.hxx>
78
79 // Netgen include files
80 #ifndef OCCGEOMETRY
81 #define OCCGEOMETRY
82 #endif
83 #include <occgeom.hpp>
84 #include <meshing.hpp>
85 //#include <ngexception.hpp>
86 namespace netgen {
87
88   NETGENPLUGIN_DLL_HEADER
89   extern MeshingParameters mparam;
90
91   NETGENPLUGIN_DLL_HEADER
92   extern volatile multithreadt multithread;
93
94   NETGENPLUGIN_DLL_HEADER
95   extern bool merge_solids;
96
97   // values used for occgeo.facemeshstatus
98   enum EFaceMeshStatus { FACE_NOT_TREATED = 0,
99                          FACE_FAILED = -1,
100                          FACE_MESHED_OK = 1,
101   };
102 }
103
104 #include <vector>
105 #include <limits>
106
107 #ifdef WIN32
108 #include <process.h>
109 #endif
110 using namespace nglib;
111 using namespace std;
112
113 #ifdef _DEBUG_
114 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec.at((index)))
115 #else
116 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec[index])
117 #endif
118
119 #define NGPOINT_COORDS(p) p(0),p(1),p(2)
120
121 #ifdef _DEBUG_
122 // dump elements added to ng mesh
123 //#define DUMP_SEGMENTS
124 //#define DUMP_TRIANGLES
125 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids()
126 #endif
127
128 TopTools_IndexedMapOfShape ShapesWithLocalSize;
129 std::map<int,double> VertexId2LocalSize;
130 std::map<int,double> EdgeId2LocalSize;
131 std::map<int,double> FaceId2LocalSize;
132 std::map<int,double> SolidId2LocalSize;
133
134 std::vector<SMESHUtils::ControlPnt> ControlPoints;
135 std::set<int> ShapesWithControlPoints; // <-- allows calling SetLocalSize() several times w/o recomputing ControlPoints
136
137 namespace
138 {
139   inline void NOOP_Deleter(void *) { ; }
140
141   //=============================================================================
142   /*!
143    *  Link - a pair of integer numbers
144    */
145   //=============================================================================
146   struct Link
147   {
148     int n1, n2;
149     Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
150     Link() : n1(0), n2(0) {}
151     bool Contains( int n ) const { return n == n1 || n == n2; }
152     bool IsConnected( const Link& other ) const
153     {
154       return (( Contains( other.n1 ) || Contains( other.n2 )) && ( this != &other ));
155     }
156     static int HashCode(const Link& aLink, int aLimit)
157     {
158       return ::HashCode(aLink.n1 + aLink.n2, aLimit);
159     }
160
161     static Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
162     {
163       return (( aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ) ||
164               ( aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1 ));
165     }
166   };
167
168   typedef NCollection_Map<Link,Link> TLinkMap;
169
170   //================================================================================
171   /*!
172    * \brief return id of netgen point corresponding to SMDS node
173    */
174   //================================================================================
175   typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
176
177   int ngNodeId( const SMDS_MeshNode* node,
178                 netgen::Mesh&        ngMesh,
179                 TNode2IdMap&         nodeNgIdMap)
180   {
181     int newNgId = ngMesh.GetNP() + 1;
182
183     TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
184
185     if ( node_id->second == newNgId)
186     {
187 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
188       cout << "Ng " << newNgId << " - " << node;
189 #endif
190       netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
191       ngMesh.AddPoint( p );
192     }
193     return node_id->second;
194   }
195
196   //================================================================================
197   /*!
198    * \brief Return computed EDGEs connected to the given one
199    */
200   //================================================================================
201
202   list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge&                 edge,
203                                          const TopoDS_Face&                 face,
204                                          const set< SMESH_subMesh* > &      /*computedSM*/,
205                                          const SMESH_MesherHelper&          helper,
206                                          map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
207   {
208     // get ordered EDGEs
209     list< TopoDS_Edge > edges;
210     list< int > nbEdgesInWire;
211     /*int nbWires =*/ SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire);
212
213     // find <edge> within <edges>
214     list< TopoDS_Edge >::iterator eItFwd = edges.begin();
215     for ( ; eItFwd != edges.end(); ++eItFwd )
216       if ( edge.IsSame( *eItFwd ))
217         break;
218     if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
219
220     if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
221     {
222       // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
223       // so treat each INTERNAL edge separately
224       TopoDS_Edge e = *eItFwd;
225       edges.clear();
226       edges.push_back( e );
227       return edges;
228     }
229
230     // get all computed EDGEs connected to <edge>
231
232     list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
233     TopoDS_Vertex vCommon;
234     TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
235     eAdded.Add( edge );
236
237     // put edges before <edge> to <edges> back
238     while ( edges.begin() != eItFwd )
239       edges.splice( edges.end(), edges, edges.begin() );
240
241     // search forward
242     ePrev = eItFwd;
243     while ( ++eItFwd != edges.end() )
244     {
245       SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
246
247       bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
248       bool computed  = !sm->IsEmpty();
249       bool added     = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
250       bool doubled   = !eAdded.Add( *eItFwd );
251       bool orientOK  = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
252                         ( eItFwd->Orientation() < TopAbs_INTERNAL )    );
253       if ( !connected || !computed || !orientOK || added || doubled )
254       {
255         // stop advancement; move edges from tail to head
256         while ( edges.back() != *ePrev )
257           edges.splice( edges.begin(), edges, --edges.end() );
258         break;
259       }
260       ePrev = eItFwd;
261     }
262     // search backward
263     while ( eItBack != edges.begin() )
264     {
265       ePrev = eItBack;
266       --eItBack;
267       SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
268
269       bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
270       bool computed  = !sm->IsEmpty();
271       bool added     = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
272       bool doubled   = !eAdded.Add( *eItBack );
273       bool orientOK  = (( ePrev  ->Orientation() < TopAbs_INTERNAL ) ==
274                         ( eItBack->Orientation() < TopAbs_INTERNAL )    );
275       if ( !connected || !computed || !orientOK || added || doubled)
276       {
277         // stop advancement
278         edges.erase( edges.begin(), ePrev );
279         break;
280       }
281     }
282     if ( edges.front() != edges.back() )
283     {
284       // assure that the 1st vertex is meshed
285       TopoDS_Edge eLast = edges.back();
286       while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
287               &&
288               edges.front() != eLast )
289         edges.splice( edges.end(), edges, edges.begin() );
290     }
291     return edges;
292   }
293
294   //================================================================================
295   /*!
296    * \brief Make triangulation of a shape precise enough
297    */
298   //================================================================================
299
300   void updateTriangulation( const TopoDS_Shape& shape )
301   {
302     // static set< Poly_Triangulation* > updated;
303
304     // TopLoc_Location loc;
305     // TopExp_Explorer fExp( shape, TopAbs_FACE );
306     // for ( ; fExp.More(); fExp.Next() )
307     // {
308     //   Handle(Poly_Triangulation) triangulation =
309     //     BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
310     //   if ( triangulation.IsNull() ||
311     //        updated.insert( triangulation.operator->() ).second )
312     //   {
313     //     BRepTools::Clean (shape);
314         try {
315           OCC_CATCH_SIGNALS;
316           BRepMesh_IncrementalMesh e(shape, 0.01, true);
317         }
318         catch (Standard_Failure&)
319         {
320         }
321   //       updated.erase( triangulation.operator->() );
322   //       triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
323   //       updated.insert( triangulation.operator->() );
324   //     }
325   //   }
326   }
327   //================================================================================
328   /*!
329    * \brief Returns a medium node either existing in SMESH of created by NETGEN
330    *  \param [in] corner1 - corner node 1
331    *  \param [in] corner2 - corner node 2
332    *  \param [in] defaultMedium - the node created by NETGEN
333    *  \param [in] helper - holder of medium nodes existing in SMESH
334    *  \return const SMDS_MeshNode* - the result node
335    */
336   //================================================================================
337
338   const SMDS_MeshNode* mediumNode( const SMDS_MeshNode*      corner1,
339                                    const SMDS_MeshNode*      corner2,
340                                    const SMDS_MeshNode*      defaultMedium,
341                                    const SMESH_MesherHelper* helper)
342   {
343     if ( helper )
344     {
345       TLinkNodeMap::const_iterator l2n =
346         helper->GetTLinkNodeMap().find( SMESH_TLink( corner1, corner2 ));
347       if ( l2n != helper->GetTLinkNodeMap().end() )
348         defaultMedium = l2n->second;
349     }
350     return defaultMedium;
351   }
352
353   //================================================================================
354   /*!
355    * \brief Assure that mesh on given shapes is quadratic
356    */
357   //================================================================================
358
359   // void makeQuadratic( const TopTools_IndexedMapOfShape& shapes,
360   //                     SMESH_Mesh*                       mesh )
361   // {
362   //   for ( int i = 1; i <= shapes.Extent(); ++i )
363   //   {
364   //     SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) );
365   //     if ( !smDS ) continue;
366   //     SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
367   //     if ( !elemIt->more() ) continue;
368   //     const SMDS_MeshElement* e = elemIt->next();
369   //     if ( !e || e->IsQuadratic() )
370   //       continue;
371
372   //     TIDSortedElemSet elems;
373   //     elems.insert( e );
374   //     while ( elemIt->more() )
375   //       elems.insert( elems.end(), elemIt->next() );
376
377   //     SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false );
378   //   }
379   // }
380
381   //================================================================================
382   /*!
383    * \brief Restrict size of elements on the given edge 
384    */
385   //================================================================================
386
387   void setLocalSize(const TopoDS_Edge& edge,
388                     double             size,
389                     netgen::Mesh&      mesh,
390                     const bool         overrideMinH = true)
391   {
392     if ( size <= std::numeric_limits<double>::min() )
393       return;
394     Standard_Real u1, u2;
395     Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
396     if ( curve.IsNull() )
397     {
398       TopoDS_Iterator vIt( edge );
399       if ( !vIt.More() ) return;
400       gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
401       NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH );
402     }
403     else
404     {
405       const int nb = (int)( 1.5 * SMESH_Algo::EdgeLength( edge ) / size );
406       Standard_Real delta = (u2-u1)/nb;
407       for(int i=0; i<nb; i++)
408       {
409         Standard_Real u = u1 + delta*i;
410         gp_Pnt p = curve->Value(u);
411         NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH );
412         netgen::Point3d pi(p.X(), p.Y(), p.Z());
413         double resultSize = mesh.GetH(pi);
414         if ( resultSize - size > 0.1*size )
415           // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
416           NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201, overrideMinH );
417       }
418     }
419   }
420
421   //================================================================================
422   /*!
423    * \brief Return triangle size for a given chordalError and radius of curvature
424    */
425   //================================================================================
426
427   double elemSizeForChordalError( double chordalError, double radius )
428   {
429     if ( 2 * radius < chordalError )
430       return 1.5 * radius;
431     return Sqrt( 3 ) * Sqrt( chordalError * ( 2 * radius - chordalError ));
432   }
433
434   //=============================================================================
435   /*!
436    *
437    */
438   //=============================================================================
439
440   void setLocalSize(const TopoDS_Shape& GeomShape, double LocalSize)
441   {
442     if ( GeomShape.IsNull() ) return;
443     TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
444     if (GeomType == TopAbs_COMPOUND) {
445       for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
446         setLocalSize(it.Value(), LocalSize);
447       }
448       return;
449     }
450     int key;
451     if (! ShapesWithLocalSize.Contains(GeomShape))
452       key = ShapesWithLocalSize.Add(GeomShape);
453     else
454       key = ShapesWithLocalSize.FindIndex(GeomShape);
455     if (GeomType == TopAbs_VERTEX) {
456       VertexId2LocalSize[key] = LocalSize;
457     } else if (GeomType == TopAbs_EDGE) {
458       EdgeId2LocalSize[key] = LocalSize;
459     } else if (GeomType == TopAbs_FACE) {
460       FaceId2LocalSize[key] = LocalSize;
461     } else if (GeomType == TopAbs_SOLID) {
462       SolidId2LocalSize[key] = LocalSize;
463     }
464     return;
465   }
466
467   //================================================================================
468   /*!
469    * \brief Return faceNgID or faceNgID-1 depending on side the given proxy face lies
470    *  \param [in] f - proxy face
471    *  \param [in] solidSMDSIDs - IDs of SOLIDs sharing the FACE on which face lies
472    *  \param [in] faceNgID - NETGEN ID of the FACE
473    *  \return int - NETGEN ID of the FACE
474    */
475   //================================================================================
476
477   int getFaceNgID( const SMDS_MeshElement* face,
478                    const int *             solidSMDSIDs,
479                    const int               faceNgID )
480   {
481     for ( int i = 0; i < 3; ++i )
482     {
483       const SMDS_MeshNode* n = face->GetNode( i );
484       const int      shapeID = n->GetShapeID();
485       if ( shapeID == solidSMDSIDs[0] )
486         return faceNgID - 1;
487       if ( shapeID == solidSMDSIDs[1] )
488         return faceNgID;
489     }
490     std::vector<const SMDS_MeshNode*> fNodes( face->begin_nodes(), face->end_nodes() );
491     std::vector<const SMDS_MeshElement*> vols;
492     if ( SMDS_Mesh::GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ))
493       for ( size_t i = 0; i < vols.size(); ++i )
494       {
495         const int shapeID = vols[i]->GetShapeID();
496         if ( shapeID == solidSMDSIDs[0] )
497           return faceNgID - 1;
498         if ( shapeID == solidSMDSIDs[1] )
499           return faceNgID;
500       }
501     return faceNgID;
502   }
503
504 } // namespace
505
506 //=============================================================================
507 /*!
508  *
509  */
510 //=============================================================================
511
512 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh*         mesh,
513                                           const TopoDS_Shape& aShape,
514                                           const bool          isVolume)
515   : _mesh    (mesh),
516     _shape   (aShape),
517     _isVolume(isVolume),
518     _optimize(true),
519     _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
520     _isViscousLayers2D(false),
521     _chordalError(-1), // means disabled
522     _ngMesh(NULL),
523     _occgeom(NULL),
524     _curShapeIndex(-1),
525     _progressTic(1),
526     _totalTime(1.0),
527     _simpleHyp(NULL),
528     _viscousLayersHyp(NULL),
529     _ptrToMe(NULL)
530 {
531   SetDefaultParameters();
532   ShapesWithLocalSize.Clear();
533   VertexId2LocalSize.clear();
534   EdgeId2LocalSize.clear();
535   FaceId2LocalSize.clear();
536   SolidId2LocalSize.clear();
537   ControlPoints.clear();
538   ShapesWithControlPoints.clear();
539 }
540
541 //================================================================================
542 /*!
543  * Destructor
544  */
545 //================================================================================
546
547 NETGENPlugin_Mesher::~NETGENPlugin_Mesher()
548 {
549   if ( _ptrToMe )
550     *_ptrToMe = NULL;
551   _ptrToMe = 0;
552   _ngMesh = NULL;
553 }
554
555 //================================================================================
556 /*!
557  * Set pointer to NETGENPlugin_Mesher* field of the holder, that will be
558  * nullified at destruction of this
559  */
560 //================================================================================
561
562 void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr )
563 {
564   if ( _ptrToMe )
565     *_ptrToMe = NULL;
566
567   _ptrToMe = ptr;
568
569   if ( _ptrToMe )
570     *_ptrToMe = this;
571 }
572
573 //================================================================================
574 /*!
575  * \brief Initialize global NETGEN parameters with default values
576  */
577 //================================================================================
578
579 void NETGENPlugin_Mesher::SetDefaultParameters()
580 {
581   netgen::MeshingParameters& mparams = netgen::mparam;
582   mparams = netgen::MeshingParameters();
583   // maximal mesh edge size
584   mparams.maxh            = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
585   mparams.minh            = 0;
586   // minimal number of segments per edge
587   mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
588   // rate of growth of size between elements
589   mparams.grading         = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
590   // safety factor for curvatures (elements per radius)
591   mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
592   // create elements of second order
593   mparams.secondorder     = NETGENPlugin_Hypothesis::GetDefaultSecondOrder();
594   // quad-dominated surface meshing
595   if (_isVolume)
596     mparams.quad          = 0;
597   else
598     mparams.quad          = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed();
599   _fineness               = NETGENPlugin_Hypothesis::GetDefaultFineness();
600   mparams.uselocalh       = NETGENPlugin_Hypothesis::GetDefaultSurfaceCurvature();
601   netgen::merge_solids    = NETGENPlugin_Hypothesis::GetDefaultFuseEdges();
602 }
603
604 //=============================================================================
605 /*!
606  * Pass parameters to NETGEN
607  */
608 //=============================================================================
609 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
610 {
611   if (hyp)
612   {
613     netgen::MeshingParameters& mparams = netgen::mparam;
614     // Initialize global NETGEN parameters:
615     // maximal mesh segment size
616     mparams.maxh               = hyp->GetMaxSize();
617     // maximal mesh element linear size
618     mparams.minh               = hyp->GetMinSize();
619     // minimal number of segments per edge
620     mparams.segmentsperedge    = hyp->GetNbSegPerEdge();
621     // rate of growth of size between elements
622     mparams.grading            = hyp->GetGrowthRate();
623     // safety factor for curvatures (elements per radius)
624     mparams.curvaturesafety    = hyp->GetNbSegPerRadius();
625     // create elements of second order
626     mparams.secondorder        = hyp->GetSecondOrder() ? 1 : 0;
627     // quad-dominated surface meshing
628     mparams.quad               = hyp->GetQuadAllowed() ? 1 : 0;
629     _optimize                  = hyp->GetOptimize();
630     _fineness                  = hyp->GetFineness();
631     mparams.uselocalh          = hyp->GetSurfaceCurvature();
632     netgen::merge_solids       = hyp->GetFuseEdges();
633     _chordalError              = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
634     mparams.optsteps2d         = _optimize ? hyp->GetNbSurfOptSteps() : 0;
635     mparams.optsteps3d         = _optimize ? hyp->GetNbVolOptSteps()  : 0;
636     mparams.elsizeweight       = hyp->GetElemSizeWeight();
637     mparams.opterrpow          = hyp->GetWorstElemMeasure();
638     mparams.delaunay           = hyp->GetUseDelauney();
639     mparams.checkoverlap       = hyp->GetCheckOverlapping();
640     mparams.checkchartboundary = hyp->GetCheckChartBoundary();
641     _simpleHyp                 = NULL;
642     // mesh size file
643 #ifdef NETGEN_V6
644     // std::string
645     mparams.meshsizefilename = hyp->GetMeshSizeFile();
646 #else
647     // const char*
648     mparams.meshsizefilename= hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
649 #endif
650     const NETGENPlugin_Hypothesis::TLocalSize& localSizes = hyp->GetLocalSizesAndEntries();
651     if ( !localSizes.empty() )
652     {
653       SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
654       NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
655       for ( ; it != localSizes.end() ; it++)
656       {
657         std::string entry = (*it).first;
658         double        val = (*it).second;
659         // --
660         GEOM::GEOM_Object_var aGeomObj;
661         SALOMEDS::SObject_var aSObj = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( entry.c_str() );
662         if ( !aSObj->_is_nil() ) {
663           CORBA::Object_var obj = aSObj->GetObject();
664           aGeomObj = GEOM::GEOM_Object::_narrow(obj);
665           aSObj->UnRegister();
666         }
667         TopoDS_Shape S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
668         setLocalSize(S, val);
669       }
670     }
671   }
672 }
673
674 //=============================================================================
675 /*!
676  * Pass simple parameters to NETGEN
677  */
678 //=============================================================================
679
680 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
681 {
682   _simpleHyp = hyp;
683   if ( _simpleHyp )
684     SetDefaultParameters();
685 }
686
687 //================================================================================
688 /*!
689  * \brief Store a Viscous Layers hypothesis
690  */
691 //================================================================================
692
693 void NETGENPlugin_Mesher::SetParameters(const StdMeshers_ViscousLayers* hyp )
694 {
695   _viscousLayersHyp = hyp;
696 }
697
698 //================================================================================
699 /*!
700  * \brief Set local size on shapes defined by SetParameters()
701  */
702 //================================================================================
703
704 void NETGENPlugin_Mesher::SetLocalSize( netgen::OCCGeometry& occgeo,
705                                         netgen::Mesh&        ngMesh)
706 {
707   // edges
708   std::map<int,double>::const_iterator it;
709   for( it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
710   {
711     int   key = (*it).first;
712     double hi = (*it).second;
713     const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
714     setLocalSize( TopoDS::Edge(shape), hi, ngMesh );
715   }
716   // vertices
717   for(it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
718   {
719     int   key = (*it).first;
720     double hi = (*it).second;
721     const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
722     gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex(shape) );
723     NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, p.XYZ(), hi );
724   }
725   // faces
726   for(it=FaceId2LocalSize.begin(); it!=FaceId2LocalSize.end(); it++)
727   {
728     int    key = (*it).first;
729     double val = (*it).second;
730     const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
731     int faceNgID = occgeo.fmap.FindIndex(shape);
732     if ( faceNgID >= 1 )
733     {
734 #ifdef NETGEN_V6
735       occgeo.SetFaceMaxH(faceNgID-1, val);
736 #else
737       occgeo.SetFaceMaxH(faceNgID, val);
738 #endif
739       for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
740         setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, ngMesh );
741     }
742     else if ( !ShapesWithControlPoints.count( key ))
743     {
744       SMESHUtils::createPointsSampleFromFace( TopoDS::Face( shape ), val, ControlPoints );
745       ShapesWithControlPoints.insert( key );
746     }
747   }
748   //solids
749   for(it=SolidId2LocalSize.begin(); it!=SolidId2LocalSize.end(); it++)
750   {
751     int    key = (*it).first;
752     double val = (*it).second;
753     if ( !ShapesWithControlPoints.count( key ))
754     {
755       const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
756       SMESHUtils::createPointsSampleFromSolid( TopoDS::Solid( shape ), val, ControlPoints );
757       ShapesWithControlPoints.insert( key );
758     }
759   }
760
761   if ( !ControlPoints.empty() )
762   {
763     for ( size_t i = 0; i < ControlPoints.size(); ++i )
764       NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, ControlPoints[i].XYZ(), ControlPoints[i].Size() );
765   }
766   return;
767 }
768
769 //================================================================================
770 /*!
771  * \brief Restrict local size to achieve a required _chordalError
772  */
773 //================================================================================
774
775 void NETGENPlugin_Mesher::SetLocalSizeForChordalError( netgen::OCCGeometry& occgeo,
776                                                        netgen::Mesh&        ngMesh)
777 {
778   if ( _chordalError <= 0. )
779     return;
780
781   TopLoc_Location loc;
782   BRepLProp_SLProps surfProp( 2, 1e-6 );
783   const double sizeCoef = 0.95;
784
785   // find non-planar FACEs with non-constant curvature
786   std::vector<int> fInd;
787   for ( int i = 1; i <= occgeo.fmap.Extent(); ++i )
788   {
789     const TopoDS_Face& face = TopoDS::Face( occgeo.fmap( i ));
790     BRepAdaptor_Surface surfAd( face, false );
791     switch ( surfAd.GetType() )
792     {
793     case GeomAbs_Plane:
794       continue;
795     case GeomAbs_Cylinder:
796     case GeomAbs_Sphere:
797     case GeomAbs_Torus: // constant curvature
798     {
799       surfProp.SetSurface( surfAd );
800       surfProp.SetParameters( 0, 0 );
801       double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
802       double    size = elemSizeForChordalError( _chordalError, 1 / maxCurv );
803 #ifdef NETGEN_V6
804       occgeo.SetFaceMaxH( i-1, size * sizeCoef );
805 #else
806       occgeo.SetFaceMaxH( i, size * sizeCoef );
807 #endif
808       // limit size one edges
809       TopTools_MapOfShape edgeMap;
810       for ( TopExp_Explorer eExp( face, TopAbs_EDGE ); eExp.More(); eExp.Next() )
811         if ( edgeMap.Add( eExp.Current() ))
812           setLocalSize( TopoDS::Edge( eExp.Current() ), size, ngMesh, /*overrideMinH=*/false );
813       break;
814     }
815     default:
816       Handle(Geom_Surface) surf = BRep_Tool::Surface( face, loc );
817       if ( GeomLib_IsPlanarSurface( surf ).IsPlanar() )
818         continue;
819       fInd.push_back( i );
820     }
821   }
822   // set local size
823   if ( !fInd.empty() )
824   {
825     BRep_Builder b;
826     TopoDS_Compound allFacesComp;
827     b.MakeCompound( allFacesComp );
828     for ( size_t i = 0; i < fInd.size(); ++i )
829       b.Add( allFacesComp, occgeo.fmap( fInd[i] ));
830
831     // copy the shape to avoid spoiling its triangulation
832     TopoDS_Shape allFacesCompCopy = BRepBuilderAPI_Copy( allFacesComp );
833
834     // create triangulation with desired chordal error
835     BRepMesh_IncrementalMesh( allFacesCompCopy,
836                               _chordalError,
837                               /*isRelative = */Standard_False,
838                               /*theAngDeflection = */ 0.5,
839                               /*isInParallel = */Standard_True);
840
841     // loop on FACEs
842     for ( TopExp_Explorer fExp( allFacesCompCopy, TopAbs_FACE ); fExp.More(); fExp.Next() )
843     {
844       const TopoDS_Face& face = TopoDS::Face( fExp.Current() );
845       Handle(Poly_Triangulation) triangulation = BRep_Tool::Triangulation ( face, loc );
846       if ( triangulation.IsNull() ) continue;
847
848       BRepAdaptor_Surface surf( face, false );
849       surfProp.SetSurface( surf );
850
851       gp_XY    uv[3];
852       gp_XYZ    p[3];
853       double size[3];
854       for ( int i = 1; i <= triangulation->NbTriangles(); ++i )
855       {
856         Standard_Integer n1,n2,n3;
857         triangulation->Triangles()(i).Get( n1,n2,n3 );
858         p [0] = triangulation->Nodes()(n1).Transformed(loc).XYZ();
859         p [1] = triangulation->Nodes()(n2).Transformed(loc).XYZ();
860         p [2] = triangulation->Nodes()(n3).Transformed(loc).XYZ();
861         uv[0] = triangulation->UVNodes()(n1).XY();
862         uv[1] = triangulation->UVNodes()(n2).XY();
863         uv[2] = triangulation->UVNodes()(n3).XY();
864         surfProp.SetParameters( uv[0].X(), uv[0].Y() );
865         if ( !surfProp.IsCurvatureDefined() )
866           break;
867
868         for ( int n = 0; n < 3; ++n ) // get size at triangle nodes
869         {
870           surfProp.SetParameters( uv[n].X(), uv[n].Y() );
871           double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
872           size[n] = elemSizeForChordalError( _chordalError, 1 / maxCurv );
873         }
874         for ( int n1 = 0; n1 < 3; ++n1 ) // limit size along each triangle edge
875         {
876           int n2 = ( n1 + 1 ) % 3;
877           double minSize = size[n1], maxSize = size[n2];
878           if ( size[n1] > size[n2] )
879             minSize = size[n2], maxSize = size[n1];
880
881           if ( maxSize / minSize < 1.2 ) // netgen ignores size difference < 1.2
882           {
883             ngMesh.RestrictLocalHLine ( netgen::Point3d( p[n1].X(), p[n1].Y(), p[n1].Z() ),
884                                         netgen::Point3d( p[n2].X(), p[n2].Y(), p[n2].Z() ),
885                                         sizeCoef * minSize );
886           }
887           else
888           {
889             gp_XY uvVec( uv[n2] - uv[n1] );
890             double len = ( p[n1] - p[n2] ).Modulus();
891             int     nb = int( len / minSize ) + 1;
892             for ( int j = 0; j <= nb; ++j )
893             {
894               double r = double( j ) / nb;
895               gp_XY uvj = uv[n1] + r * uvVec;
896
897               surfProp.SetParameters( uvj.X(), uvj.Y() );
898               double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
899               double       h = elemSizeForChordalError( _chordalError, 1 / maxCurv );
900
901               const gp_Pnt& pj = surfProp.Value();
902               netgen::Point3d ngP( pj.X(), pj.Y(), pj.Z());
903               ngMesh.RestrictLocalH( ngP, h * sizeCoef );
904             }
905           }
906         }
907       }
908     }
909   }
910 }
911
912 //================================================================================
913 /*!
914  * \brief Initialize netgen::OCCGeometry with OCCT shape
915  */
916 //================================================================================
917
918 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry&     occgeo,
919                                              const TopoDS_Shape&      shape,
920                                              SMESH_Mesh&              mesh,
921                                              list< SMESH_subMesh* > * meshedSM,
922                                              NETGENPlugin_Internals*  intern)
923 {
924   updateTriangulation( shape );
925
926   Bnd_Box bb;
927   BRepBndLib::Add (shape, bb);
928   double x1,y1,z1,x2,y2,z2;
929   bb.Get (x1,y1,z1,x2,y2,z2);
930   netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
931   netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
932   occgeo.boundingbox = netgen::Box<3> (p1,p2);
933
934   occgeo.shape = shape;
935   occgeo.changed = 1;
936
937   // fill maps of shapes of occgeo with not yet meshed subshapes
938
939   // get root submeshes
940   list< SMESH_subMesh* > rootSM;
941   const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
942   if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
943     rootSM.push_back( mesh.GetSubMesh( shape ));
944   }
945   else {
946     for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
947       rootSM.push_back( mesh.GetSubMesh( it.Value() ));
948   }
949
950   int totNbFaces = 0;
951
952   // add subshapes of empty submeshes
953   list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
954   for ( ; rootIt != rootEnd; ++rootIt ) {
955     SMESH_subMesh * root = *rootIt;
956     SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
957                                                                /*complexShapeFirst=*/true);
958     // to find a right orientation of subshapes (PAL20462)
959     TopTools_IndexedMapOfShape subShapes;
960     TopExp::MapShapes(root->GetSubShape(), subShapes);
961     while ( smIt->more() )
962     {
963       SMESH_subMesh*  sm = smIt->next();
964       TopoDS_Shape shape = sm->GetSubShape();
965       totNbFaces += ( shape.ShapeType() == TopAbs_FACE );
966       if ( intern && intern->isShapeToPrecompute( shape ))
967         continue;
968       if ( !meshedSM || sm->IsEmpty() )
969       {
970         if ( shape.ShapeType() != TopAbs_VERTEX )
971           shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
972         if ( shape.Orientation() >= TopAbs_INTERNAL )
973           shape.Orientation( TopAbs_FORWARD ); // issue 0020676
974         switch ( shape.ShapeType() ) {
975         case TopAbs_FACE  : occgeo.fmap.Add( shape ); break;
976         case TopAbs_EDGE  : occgeo.emap.Add( shape ); break;
977         case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
978         case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
979         default:;
980         }
981       }
982       // collect submeshes of meshed shapes
983       else if (meshedSM)
984       {
985         const int dim = SMESH_Gen::GetShapeDim( shape );
986         meshedSM[ dim ].push_back( sm );
987       }
988     }
989   }
990   occgeo.facemeshstatus.SetSize (totNbFaces);
991   occgeo.facemeshstatus = 0;
992   occgeo.face_maxh_modified.SetSize(totNbFaces);
993   occgeo.face_maxh_modified = 0;
994   occgeo.face_maxh.SetSize(totNbFaces);
995   occgeo.face_maxh = netgen::mparam.maxh;
996 }
997
998 //================================================================================
999 /*!
1000  * \brief Return a default min size value suitable for the given geometry.
1001  */
1002 //================================================================================
1003
1004 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
1005                                               const double        maxSize)
1006 {
1007   updateTriangulation( geom );
1008
1009   TopLoc_Location loc;
1010   int i1, i2, i3;
1011   const int* pi[4] = { &i1, &i2, &i3, &i1 };
1012   double minh = 1e100;
1013   Bnd_B3d bb;
1014   TopExp_Explorer fExp( geom, TopAbs_FACE );
1015   for ( ; fExp.More(); fExp.Next() )
1016   {
1017     Handle(Poly_Triangulation) triangulation =
1018       BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
1019     if ( triangulation.IsNull() ) continue;
1020     const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
1021     const TColgp_Array1OfPnt&   points = triangulation->Nodes();
1022     const Poly_Array1OfTriangle& trias = triangulation->Triangles();
1023     for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
1024     {
1025       trias(iT).Get( i1, i2, i3 );
1026       for ( int j = 0; j < 3; ++j )
1027       {
1028         double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
1029         if ( dist2 < minh && fTol*fTol < dist2 )
1030           minh = dist2;
1031         bb.Add( points(*pi[j]));
1032       }
1033     }
1034   }
1035   if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
1036   {
1037     minh = 1e-3 * sqrt( bb.SquareExtent());
1038     //cout << "BND BOX minh = " <<minh << endl;
1039   }
1040   else
1041   {
1042     minh = sqrt( minh ); // triangulation for visualization is rather fine
1043     //cout << "TRIANGULATION minh = " <<minh << endl;
1044   }
1045   if ( minh > 0.5 * maxSize )
1046     minh = maxSize / 3.;
1047
1048   return minh;
1049 }
1050
1051 //================================================================================
1052 /*!
1053  * \brief Restrict size of elements at a given point
1054  */
1055 //================================================================================
1056
1057 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh,
1058                                             const gp_XYZ& p,
1059                                             double        size,
1060                                             const bool    overrideMinH)
1061 {
1062   if ( size <= std::numeric_limits<double>::min() )
1063     return;
1064   if ( netgen::mparam.minh > size )
1065   {
1066     if ( overrideMinH )
1067     {
1068       ngMesh.SetMinimalH( size );
1069       netgen::mparam.minh = size;
1070     }
1071     else
1072     {
1073       size = netgen::mparam.minh;
1074     }
1075   }
1076   netgen::Point3d pi(p.X(), p.Y(), p.Z());
1077   ngMesh.RestrictLocalH( pi, size );
1078 }
1079
1080 //================================================================================
1081 /*!
1082  * \brief fill ngMesh with nodes and elements of computed submeshes
1083  */
1084 //================================================================================
1085
1086 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry&           occgeom,
1087                                      netgen::Mesh&                  ngMesh,
1088                                      vector<const SMDS_MeshNode*>&  nodeVec,
1089                                      const list< SMESH_subMesh* > & meshedSM,
1090                                      SMESH_MesherHelper*            quadHelper,
1091                                      SMESH_ProxyMesh::Ptr           proxyMesh)
1092 {
1093   TNode2IdMap nodeNgIdMap;
1094   for ( size_t i = 1; i < nodeVec.size(); ++i )
1095     nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
1096
1097   TopTools_MapOfShape visitedShapes;
1098   map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
1099   set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
1100
1101   SMESH_MesherHelper helper (*_mesh);
1102   SMESHDS_Mesh* meshDS = _mesh->GetMeshDS();
1103
1104   int faceNgID = ngMesh.GetNFD();
1105
1106   list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
1107   for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
1108   {
1109     SMESH_subMesh* sm = *smIt;
1110     if ( !visitedShapes.Add( sm->GetSubShape() ))
1111       continue;
1112
1113     const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
1114     if ( !smDS ) continue;
1115
1116     switch ( sm->GetSubShape().ShapeType() )
1117     {
1118     case TopAbs_EDGE: { // EDGE
1119       // ----------------------
1120       TopoDS_Edge geomEdge  = TopoDS::Edge( sm->GetSubShape() );
1121       if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
1122         geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
1123
1124       // Add ng segments for each not meshed FACE the EDGE bounds
1125       PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
1126       while ( const TopoDS_Shape * anc = fIt->next() )
1127       {
1128         faceNgID = occgeom.fmap.FindIndex( *anc );
1129         if ( faceNgID < 1 )
1130           continue; // meshed face
1131
1132         int faceSMDSId = meshDS->ShapeToIndex( *anc );
1133         if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
1134           continue; // already treated EDGE
1135
1136         TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
1137         if ( face.Orientation() >= TopAbs_INTERNAL )
1138           face.Orientation( TopAbs_FORWARD ); // issue 0020676
1139
1140         // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
1141         helper.SetSubShape( face );
1142         list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
1143                                                        visitedEdgeSM2Faces );
1144         if ( edges.empty() )
1145           continue; // wrong ancestor?
1146
1147         // find out orientation of <edges> within <face>
1148         TopoDS_Edge eNotSeam = edges.front();
1149         if ( helper.HasSeam() )
1150         {
1151           list< TopoDS_Edge >::iterator eIt = edges.begin();
1152           while ( helper.IsRealSeam( *eIt )) ++eIt;
1153           if ( eIt != edges.end() )
1154             eNotSeam = *eIt;
1155         }
1156         TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
1157         bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
1158
1159         // get all nodes from connected <edges>
1160         const bool skipMedium = netgen::mparam.secondorder;//smDS->IsQuadratic();
1161         StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, skipMedium, &helper );
1162         const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
1163         if ( points.empty() )
1164           return false; // invalid node params?
1165         smIdType i, nbSeg = fSide.NbSegments();
1166
1167         // remember EDGEs of fSide to treat only once
1168         for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
1169           visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
1170
1171         double otherSeamParam = 0;
1172         bool isSeam = false;
1173
1174         // add segments
1175
1176         int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
1177
1178         for ( i = 0; i < nbSeg; ++i )
1179         {
1180           const UVPtStruct& p1 = points[ i ];
1181           const UVPtStruct& p2 = points[ i+1 ];
1182
1183           if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
1184           {
1185             isSeam = false;
1186             if ( helper.IsRealSeam( p1.node->GetShapeID() ))
1187             {
1188               TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
1189               isSeam = helper.IsRealSeam( e );
1190               if ( isSeam )
1191               {
1192                 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
1193               }
1194             }
1195           }
1196           netgen::Segment seg;
1197           // ng node ids
1198           seg[0] = prevNgId;
1199           seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
1200           // node param on curve
1201           seg.epgeominfo[ 0 ].dist = p1.param;
1202           seg.epgeominfo[ 1 ].dist = p2.param;
1203           // uv on face
1204           seg.epgeominfo[ 0 ].u = p1.u;
1205           seg.epgeominfo[ 0 ].v = p1.v;
1206           seg.epgeominfo[ 1 ].u = p2.u;
1207           seg.epgeominfo[ 1 ].v = p2.v;
1208
1209           //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
1210           //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
1211
1212           //seg.epgeominfo[ iEnd ].edgenr = edgeID; //  = geom.emap.FindIndex(edge);
1213           seg.si = faceNgID;                   // = geom.fmap.FindIndex (face);
1214           seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1215           ngMesh.AddSegment (seg);
1216
1217           SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
1218           RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
1219
1220 #ifdef DUMP_SEGMENTS
1221           cout << "Segment: " << seg.edgenr << " on SMESH face " << meshDS->ShapeToIndex( face ) << endl
1222                << "\tface index: " << seg.si << endl
1223                << "\tp1: " << seg[0] << endl
1224                << "\tp2: " << seg[1] << endl
1225                << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1226                << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1227             //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1228                << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1229                << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
1230             //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1231 #endif
1232           if ( isSeam )
1233           {
1234             if ( helper.GetPeriodicIndex() && 1 ) {
1235               seg.epgeominfo[ 0 ].u = otherSeamParam;
1236               seg.epgeominfo[ 1 ].u = otherSeamParam;
1237               swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
1238             } else {
1239               seg.epgeominfo[ 0 ].v = otherSeamParam;
1240               seg.epgeominfo[ 1 ].v = otherSeamParam;
1241               swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
1242             }
1243             swap( seg[0], seg[1] );
1244             swap( seg.epgeominfo[0].dist, seg.epgeominfo[1].dist );
1245             seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1246             ngMesh.AddSegment( seg );
1247 #ifdef DUMP_SEGMENTS
1248             cout << "Segment: " << seg.edgenr << endl
1249                  << "\t is SEAM (reverse) of the previous. "
1250                  << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
1251                  << " = " << otherSeamParam << endl;
1252 #endif
1253           }
1254           else if ( fOri == TopAbs_INTERNAL )
1255           {
1256             swap( seg[0], seg[1] );
1257             swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1258             seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1259             ngMesh.AddSegment( seg );
1260 #ifdef DUMP_SEGMENTS
1261             cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
1262 #endif
1263           }
1264         }
1265       } // loop on geomEdge ancestors
1266
1267       if ( quadHelper ) // remember medium nodes of sub-meshes
1268       {
1269         SMDS_ElemIteratorPtr edges = smDS->GetElements();
1270         while ( edges->more() )
1271         {
1272           const SMDS_MeshElement* e = edges->next();
1273           if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshEdge*>( e )))
1274             break;
1275         }
1276       }
1277
1278       break;
1279     } // case TopAbs_EDGE
1280
1281     case TopAbs_FACE: { // FACE
1282       // ----------------------
1283       const TopoDS_Face& geomFace  = TopoDS::Face( sm->GetSubShape() );
1284       helper.SetSubShape( geomFace );
1285       bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
1286
1287       // Find solids the geomFace bounds
1288       int solidID1 = 0, solidID2 = 0; // ng IDs
1289       int solidSMDSIDs[2] = { 0,0 };  // smds IDs
1290       {
1291         PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
1292         while ( const TopoDS_Shape * solid = solidIt->next() )
1293         {
1294           int id = occgeom.somap.FindIndex ( *solid );
1295           if ( solidID1 && id != solidID1 ) solidID2 = id;
1296           else                              solidID1 = id;
1297           if ( id ) solidSMDSIDs[ bool( solidSMDSIDs[0] )] = meshDS->ShapeToIndex( *solid );
1298         }
1299       }
1300       if ( proxyMesh && proxyMesh->GetProxySubMesh( geomFace ))
1301       {
1302         // if a proxy sub-mesh contains temporary faces, then these faces
1303         // should be used to mesh only one SOLID
1304         bool hasTmp = false;
1305         smDS = proxyMesh->GetSubMesh( geomFace );
1306         SMDS_ElemIteratorPtr faces = smDS->GetElements();
1307         while ( faces->more() )
1308         {
1309           const SMDS_MeshElement* f = faces->next();
1310           if ( proxyMesh->IsTemporary( f ))
1311           {
1312             hasTmp = true;
1313             if ( solidSMDSIDs[1] && proxyMesh->HasPrismsOnTwoSides( meshDS->MeshElements( geomFace )))
1314               break;
1315             else
1316               solidSMDSIDs[1] = 0;
1317             std::vector<const SMDS_MeshNode*> fNodes( f->begin_nodes(), f->end_nodes() );
1318             std::vector<const SMDS_MeshElement*> vols;
1319             if ( meshDS->GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ) == 1 )
1320             {
1321               int geomID = vols[0]->GetShapeID();
1322               const TopoDS_Shape& solid =  meshDS->IndexToShape( geomID );
1323               if ( !solid.IsNull() )
1324                 solidID1 = occgeom.somap.FindIndex ( solid );
1325               solidID2 = 0;
1326               break;
1327             }
1328           }
1329         }
1330         const int fID = occgeom.fmap.FindIndex( geomFace );
1331         if ( !hasTmp ) // shrunk mesh
1332         {
1333           // move netgen points according to moved nodes
1334           SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
1335           while ( smIt->more() )
1336           {
1337             SMESH_subMesh* sub = smIt->next();
1338             if ( !sub->GetSubMeshDS() ) continue;
1339             SMDS_NodeIteratorPtr nodeIt = sub->GetSubMeshDS()->GetNodes();
1340             while ( nodeIt->more() )
1341             {
1342               const SMDS_MeshNode* n = nodeIt->next();
1343               int ngID = ngNodeId( n, ngMesh, nodeNgIdMap );
1344               netgen::MeshPoint& ngPoint = ngMesh.Point( ngID );
1345               ngPoint(0) = n->X();
1346               ngPoint(1) = n->Y();
1347               ngPoint(2) = n->Z();
1348             }
1349           }
1350           // remove faces near boundary to avoid their overlapping
1351           // with shrunk faces
1352           for ( int i = 1; i <= ngMesh.GetNSE(); ++i )
1353           {
1354             const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1355             if ( elem.GetIndex() == fID )
1356             {
1357               for ( int iN = 0; iN < elem.GetNP(); ++iN )
1358                 if ( ngMesh[ elem[ iN ]].Type() != netgen::SURFACEPOINT )
1359                 {
1360                   ngMesh.DeleteSurfaceElement( i );
1361                   break;
1362                 }
1363             }
1364           }
1365         }
1366         // exclude faces generated by NETGEN from computation of 3D mesh
1367         //if ( hasTmp )
1368         {
1369           faceNgID++;
1370           ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID,/*solid1=*/0,/*solid2=*/0,0 ));
1371           for (int i = 1; i <= ngMesh.GetNSE(); ++i )
1372           {
1373             const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1374             if ( elem.GetIndex() == fID )
1375               const_cast< netgen::Element2d& >( elem ).SetIndex( faceNgID );
1376           }
1377         }
1378       } // if proxy
1379       else
1380       {
1381         solidSMDSIDs[1] = 0;
1382       }
1383       const bool hasVLOn2Sides = ( solidSMDSIDs[1] > 0 );
1384
1385       // Add ng face descriptors of meshed faces
1386       faceNgID++;
1387       if ( hasVLOn2Sides )
1388       {
1389         // viscous layers are on two sides of the FACE
1390         ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, 0, 0 ));
1391         faceNgID++;
1392         ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, 0, solidID2, 0 ));
1393       }
1394       else
1395       {
1396         ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, solidID2, 0 ));
1397       }
1398       // if second oreder is required, even already meshed faces must be passed to NETGEN
1399       int fID = occgeom.fmap.Add( geomFace );
1400       if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1401       occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1402       while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
1403       {
1404         fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
1405         if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1406         occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1407       }
1408       // Problem with the second order in a quadrangular mesh remains.
1409       // 1) All quadrangles generated by NETGEN are moved to an inexistent face
1410       //    by FillSMesh() (find "AddFaceDescriptor")
1411       // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
1412       //    are on faces where quadrangles were.
1413       // Due to these 2 points, wrong geom faces are used while conversion to quadratic
1414       // of the mentioned above quadrangles and triangles
1415
1416       // Orient the face correctly in solidID1 (issue 0020206)
1417       bool reverse = false;
1418       if ( solidID1 ) {
1419         TopoDS_Shape solid = occgeom.somap( solidID1 );
1420         TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
1421         if ( faceOriInSolid >= 0 )
1422           reverse =
1423             helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
1424       }
1425
1426       // Add surface elements
1427
1428       netgen::Element2d tri(3);
1429       tri.SetIndex( faceNgID );
1430       SMESH_TNodeXYZ xyz[3];
1431
1432 #ifdef DUMP_TRIANGLES
1433       cout << "SMESH face " << meshDS->ShapeToIndex( geomFace )
1434            << " internal="<<isInternalFace << endl;
1435 #endif
1436
1437       SMDS_ElemIteratorPtr faces = smDS->GetElements();
1438       while ( faces->more() )
1439       {
1440         const SMDS_MeshElement* f = faces->next();
1441         if ( f->NbNodes() % 3 != 0 ) // not triangle
1442         {
1443           PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID);
1444           if ( const TopoDS_Shape * solid = solidIt->next() )
1445             sm = _mesh->GetSubMesh( *solid );
1446           SMESH_BadInputElements* badElems =
1447             new SMESH_BadInputElements( meshDS, COMPERR_BAD_INPUT_MESH, "Not triangle sub-mesh");
1448           badElems->add( f );
1449           sm->GetComputeError().reset( badElems );
1450           return false;
1451         }
1452
1453         if ( hasVLOn2Sides )
1454           tri.SetIndex( getFaceNgID( f, solidSMDSIDs, faceNgID ));
1455
1456         for ( int i = 0; i < 3; ++i )
1457         {
1458           const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
1459           xyz[i].Set( node );
1460
1461           // get node UV on face
1462           int shapeID = node->GetShapeID();
1463           if ( helper.IsSeamShape( shapeID ))
1464           {
1465             if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->GetShapeID() ))
1466               inFaceNode = f->GetNodeWrap( i-1 );
1467             else
1468               inFaceNode = f->GetNodeWrap( i+1 );
1469           }
1470           gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
1471
1472           int ind = reverse ? 3-i : i+1;
1473           tri.GeomInfoPi(ind).u = uv.X();
1474           tri.GeomInfoPi(ind).v = uv.Y();
1475           tri.PNum      (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
1476         }
1477
1478         // pass a triangle size to NG size-map
1479         double size = ( ( xyz[0] - xyz[1] ).Modulus() +
1480                         ( xyz[1] - xyz[2] ).Modulus() +
1481                         ( xyz[2] - xyz[0] ).Modulus() ) / 3;
1482         gp_XYZ gc = ( xyz[0] + xyz[1] + xyz[2] ) / 3;
1483         RestrictLocalSize( ngMesh, gc, size, /*overrideMinH=*/false );
1484
1485         ngMesh.AddSurfaceElement (tri);
1486 #ifdef DUMP_TRIANGLES
1487         cout << tri << endl;
1488 #endif
1489
1490         if ( isInternalFace )
1491         {
1492           swap( tri[1], tri[2] );
1493           ngMesh.AddSurfaceElement (tri);
1494 #ifdef DUMP_TRIANGLES
1495           cout << tri << endl;
1496 #endif
1497         }
1498       } // loop on sub-mesh faces
1499
1500       if ( quadHelper ) // remember medium nodes of sub-meshes
1501       {
1502         SMDS_ElemIteratorPtr faces = smDS->GetElements();
1503         while ( faces->more() )
1504         {
1505           const SMDS_MeshElement* f = faces->next();
1506           if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshFace*>( f )))
1507             break;
1508         }
1509       }
1510
1511       break;
1512     } // case TopAbs_FACE
1513
1514     case TopAbs_VERTEX: { // VERTEX
1515       // --------------------------
1516       // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
1517       // else netgen removes a free node and nodeVector becomes invalid
1518       PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
1519                                                      *sm->GetFather(),
1520                                                      TopAbs_EDGE );
1521       bool toAdd = false;
1522       while ( const TopoDS_Shape* e = ansIt->next() )
1523       {
1524         SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
1525         if (( toAdd = ( eSub->IsEmpty() && !SMESH_Algo::isDegenerated( TopoDS::Edge( *e )))))
1526           break;
1527       }
1528       if ( toAdd )
1529       {
1530         SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
1531         if ( nodeIt->more() )
1532           ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
1533       }
1534       break;
1535     }
1536     default:;
1537     } // switch
1538   } // loop on submeshes
1539
1540   // fill nodeVec
1541   nodeVec.resize( ngMesh.GetNP() + 1 );
1542   TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
1543   for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
1544     nodeVec[ node_NgId->second ] = node_NgId->first;
1545
1546   return true;
1547 }
1548
1549 //================================================================================
1550 /*!
1551  * \brief Duplicate mesh faces on internal geom faces
1552  */
1553 //================================================================================
1554
1555 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
1556                                       netgen::Mesh&              ngMesh,
1557                                       NETGENPlugin_Internals&    internalShapes)
1558 {
1559   SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1560   
1561   // find ng indices of internal faces
1562   set<int> ngFaceIds;
1563   for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
1564   {
1565     int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
1566     if ( internalShapes.isInternalShape( smeshID ))
1567       ngFaceIds.insert( ngFaceID );
1568   }
1569   if ( !ngFaceIds.empty() )
1570   {
1571     // duplicate faces
1572     int i, nbFaces = ngMesh.GetNSE();
1573     for ( i = 1; i <= nbFaces; ++i)
1574     {
1575       netgen::Element2d elem = ngMesh.SurfaceElement(i);
1576       if ( ngFaceIds.count( elem.GetIndex() ))
1577       {
1578         swap( elem[1], elem[2] );
1579         ngMesh.AddSurfaceElement (elem);
1580       }
1581     }
1582   }
1583 }
1584
1585 //================================================================================
1586 /*!
1587  * \brief Tries to heal the mesh on a FACE. The FACE is supposed to be partially
1588  *        meshed due to NETGEN failure
1589  *  \param [in] occgeom - geometry
1590  *  \param [in,out] ngMesh - the mesh to fix
1591  *  \param [inout] faceID - ID of the FACE to fix the mesh on
1592  *  \return bool - is mesh is or becomes OK
1593  */
1594 //================================================================================
1595
1596 bool NETGENPlugin_Mesher::FixFaceMesh(const netgen::OCCGeometry& occgeom,
1597                                       netgen::Mesh&              ngMesh,
1598                                       const int                  faceID)
1599 {
1600   // we address a case where the FACE is almost fully meshed except small holes
1601   // of usually triangular shape at FACE boundary (IPAL52861)
1602
1603   // The case appeared to be not simple: holes only look triangular but
1604   // indeed are a self intersecting polygon. A reason of the bug was in coincident
1605   // NG points on a seam edge. But the code below is very nice, leave it for
1606   // another case.
1607   return false;
1608
1609
1610   if ( occgeom.fmap.Extent() < faceID )
1611     return false;
1612   //const TopoDS_Face& face = TopoDS::Face( occgeom.fmap( faceID ));
1613
1614   // find free links on the FACE
1615   TLinkMap linkMap;
1616   for ( int iF = 1; iF <= ngMesh.GetNSE(); ++iF )
1617   {
1618     const netgen::Element2d& elem = ngMesh.SurfaceElement(iF);
1619     if ( faceID != elem.GetIndex() )
1620       continue;
1621     int n0 = elem[ elem.GetNP() - 1 ];
1622     for ( int i = 0; i < elem.GetNP(); ++i )
1623     {
1624       int n1 = elem[i];
1625       Link link( n0, n1 );
1626       if ( !linkMap.Add( link ))
1627         linkMap.Remove( link );
1628       n0 = n1;
1629     }
1630   }
1631   // add/remove boundary links
1632   for ( int iSeg = 1; iSeg <= ngMesh.GetNSeg(); ++iSeg )
1633   {
1634     const netgen::Segment& seg = ngMesh.LineSegment( iSeg );
1635     if ( seg.si != faceID ) // !edgeIDs.Contains( seg.edgenr ))
1636       continue;
1637     Link link( seg[1], seg[0] ); // reverse!!!
1638     if ( !linkMap.Add( link ))
1639       linkMap.Remove( link );
1640   }
1641   if ( linkMap.IsEmpty() )
1642     return true;
1643   if ( linkMap.Extent() < 3 )
1644     return false;
1645
1646   // make triangles of the links
1647
1648   netgen::Element2d tri(3);
1649   tri.SetIndex ( faceID );
1650
1651   TLinkMap::Iterator linkIt( linkMap );
1652   Link link1 = linkIt.Value();
1653   // look for a link connected to link1
1654   TLinkMap::Iterator linkIt2 = linkIt;
1655   for ( linkIt2.Next(); linkIt2.More(); linkIt2.Next() )
1656   {
1657     const Link& link2 = linkIt2.Value();
1658     if ( link2.IsConnected( link1 ))
1659     {
1660       // look for a link connected to both link1 and link2
1661       TLinkMap::Iterator linkIt3 = linkIt2;
1662       for ( linkIt3.Next(); linkIt3.More(); linkIt3.Next() )
1663       {
1664         const Link& link3 = linkIt3.Value();
1665         if ( link3.IsConnected( link1 ) &&
1666              link3.IsConnected( link2 ) )
1667         {
1668           // add a triangle
1669           tri[0] = link1.n2;
1670           tri[1] = link1.n1;
1671           tri[2] = ( link2.Contains( link1.n1 ) ? link2.n1 : link3.n1 );
1672           if ( tri[0] == tri[2] || tri[1] == tri[2] )
1673             return false;
1674           ngMesh.AddSurfaceElement( tri );
1675
1676           // prepare for the next tria search
1677           if ( linkMap.Extent() == 3 )
1678             return true;
1679           linkMap.Remove( link3 );
1680           linkMap.Remove( link2 );
1681           linkIt.Next();
1682           linkMap.Remove( link1 );
1683           link1 = linkIt.Value();
1684           linkIt2 = linkIt;
1685           break;
1686         }
1687       }
1688     }
1689   }
1690   return false;
1691
1692 } // FixFaceMesh()
1693
1694 namespace
1695 {
1696   //================================================================================
1697   // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
1698   gp_XY_FunPtr(Subtracted);
1699   //gp_XY_FunPtr(Added);
1700
1701   //================================================================================
1702   /*!
1703    * \brief Evaluate distance between two 2d points along the surface
1704    */
1705   //================================================================================
1706
1707   double evalDist( const gp_XY&                uv1,
1708                    const gp_XY&                uv2,
1709                    const Handle(Geom_Surface)& surf,
1710                    const int                   stopHandler=-1)
1711   {
1712     if ( stopHandler > 0 ) // continue recursion
1713     {
1714       gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
1715       return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
1716     }
1717     double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1718     if ( stopHandler == 0 ) // stop recursion
1719       return dist3D;
1720     
1721     // start recursion if necessary
1722     double dist2D = SMESH_MesherHelper::ApplyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1723     if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1724       return dist3D; // equal parametrization of a planar surface
1725
1726     return evalDist( uv1, uv2, surf, 3 ); // start recursion
1727   }
1728
1729   //================================================================================
1730   /*!
1731    * \brief Data of vertex internal in geom face
1732    */
1733   //================================================================================
1734
1735   struct TIntVData
1736   {
1737     gp_XY uv;        //!< UV in face parametric space
1738     int   ngId;      //!< ng id of corresponding node
1739     gp_XY uvClose;   //!< UV of closest boundary node
1740     int   ngIdClose; //!< ng id of closest boundary node
1741   };
1742
1743   //================================================================================
1744   /*!
1745    * \brief Data of vertex internal in solid
1746    */
1747   //================================================================================
1748
1749   struct TIntVSoData
1750   {
1751     int   ngId;      //!< ng id of corresponding node
1752     int   ngIdClose; //!< ng id of closest 2d mesh element
1753     int   ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1754   };
1755
1756   inline double dist2( const netgen::MeshPoint& p1, const netgen::MeshPoint& p2 )
1757   {
1758     return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1759   }
1760
1761   // inline double dist2(const netgen::MeshPoint& p, const SMDS_MeshNode* n )
1762   // {
1763   //   return gp_Pnt( NGPOINT_COORDS(p)).SquareDistance( SMESH_NodeXYZ(n));
1764   // }
1765 }
1766
1767 //================================================================================
1768 /*!
1769  * \brief Make netgen take internal vertices in faces into account by adding
1770  *        segments including internal vertices
1771  *
1772  * This function works in supposition that 1D mesh is already computed in ngMesh
1773  */
1774 //================================================================================
1775
1776 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry&     occgeom,
1777                                                 netgen::Mesh&                  ngMesh,
1778                                                 vector<const SMDS_MeshNode*>&  nodeVec,
1779                                                 NETGENPlugin_Internals&        internalShapes)
1780 {
1781   if ((int) nodeVec.size() < ngMesh.GetNP() )
1782     nodeVec.resize( ngMesh.GetNP(), 0 );
1783
1784   SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1785   SMESH_MesherHelper helper( internalShapes.getMesh() );
1786
1787   const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1788   map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1789   for ( ; f2v != face2Vert.end(); ++f2v )
1790   {
1791     const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1792     if ( face.IsNull() ) continue;
1793     int faceNgID = occgeom.fmap.FindIndex (face);
1794     if ( faceNgID < 0 ) continue;
1795
1796     TopLoc_Location loc;
1797     Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1798
1799     helper.SetSubShape( face );
1800     helper.SetElementsOnShape( true );
1801
1802     // Get data of internal vertices and add them to ngMesh
1803
1804     multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1805
1806     int i, nbSegInit = ngMesh.GetNSeg();
1807
1808     // boundary characteristics
1809     double totSegLen2D = 0;
1810     int totNbSeg = 0;
1811
1812     const list<int>& iVertices = f2v->second;
1813     list<int>::const_iterator iv = iVertices.begin();
1814     for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1815     {
1816       TIntVData vData;
1817       // get node on vertex
1818       const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1819       const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1820       if ( !nV )
1821       {
1822         SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1823         sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1824         nV = SMESH_Algo::VertexNode( V, meshDS );
1825         if ( !nV ) continue;
1826       }
1827       // add ng node
1828       netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1829       ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1830       vData.ngId = ngMesh.GetNP();
1831       nodeVec.push_back( nV );
1832
1833       // get node UV
1834       bool uvOK = true;
1835       vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1836       if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1837
1838       // loop on all segments of the face to find the node closest to vertex and to count
1839       // average segment 2d length
1840       double closeDist2 = numeric_limits<double>::max(), dist2;
1841       int ngIdLast = 0;
1842       for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1843       {
1844         netgen::Segment & seg = ngMesh.LineSegment(i);
1845         if ( seg.si != faceNgID ) continue;
1846         gp_XY uv[2];
1847         for ( int iEnd = 0; iEnd < 2; ++iEnd)
1848         {
1849           uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1850           if ( ngIdLast == seg[ iEnd ] ) continue;
1851           dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1852           if ( dist2 < closeDist2 )
1853             vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1854           ngIdLast = seg[ iEnd ];
1855         }
1856         if ( !nbV )
1857         {
1858           totSegLen2D += helper.ApplyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1859           totNbSeg++;
1860         }
1861       }
1862       dist2VData.insert( make_pair( closeDist2, vData ));
1863     }
1864
1865     if ( totNbSeg == 0 ) break;
1866     double avgSegLen2d = totSegLen2D / totNbSeg;
1867
1868     // Loop on vertices to add segments
1869
1870     multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1871     for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1872     {
1873       double closeDist2 = dist_vData->first, dist2;
1874       TIntVData & vData = dist_vData->second;
1875
1876       // try to find more close node among segments added for internal vertices
1877       for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1878       {
1879         netgen::Segment & seg = ngMesh.LineSegment(i);
1880         if ( seg.si != faceNgID ) continue;
1881         gp_XY uv[2];
1882         for ( int iEnd = 0; iEnd < 2; ++iEnd)
1883         {
1884           uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1885           dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1886           if ( dist2 < closeDist2 )
1887             vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1888         }
1889       }
1890       // decide whether to use the closest node as the second end of segment or to
1891       // create a new point
1892       int segEnd1 = vData.ngId;
1893       int segEnd2 = vData.ngIdClose; // to use closest node
1894       gp_XY uvV = vData.uv, uvP = vData.uvClose;
1895       double segLenHint  = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1896       double nodeDist2D  = sqrt( closeDist2 );
1897       double nodeDist3D  = evalDist( vData.uv, vData.uvClose, surf );
1898       bool avgLenOK  = ( avgSegLen2d < 0.75 * nodeDist2D );
1899       bool hintLenOK = ( segLenHint  < 0.75 * nodeDist3D );
1900       //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1901       if ( hintLenOK || avgLenOK )
1902       {
1903         // create a point between the closest node and V
1904
1905         // how far from V
1906         double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1907         // direction from V to closet node in 2D
1908         gp_Dir2d v2n( helper.ApplyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1909         // new point
1910         uvP = vData.uv + r * nodeDist2D * v2n.XY();
1911         gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1912
1913         netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1914         ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1915         segEnd2 = ngMesh.GetNP();
1916         //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1917         SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1918         nodeVec.push_back( nP );
1919       }
1920       //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1921
1922       // Add the segment
1923       netgen::Segment seg;
1924
1925       if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1926       seg[0] = segEnd1;  // ng node id
1927       seg[1] = segEnd2;  // ng node id
1928       seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1929       seg.si = faceNgID;
1930
1931       seg.epgeominfo[ 0 ].dist = 0; // param on curve
1932       seg.epgeominfo[ 0 ].u    = uvV.X();
1933       seg.epgeominfo[ 0 ].v    = uvV.Y();
1934       seg.epgeominfo[ 1 ].dist = 1; // param on curve
1935       seg.epgeominfo[ 1 ].u    = uvP.X();
1936       seg.epgeominfo[ 1 ].v    = uvP.Y();
1937
1938 //       seg.epgeominfo[ 0 ].edgenr = 10; //  = geom.emap.FindIndex(edge);
1939 //       seg.epgeominfo[ 1 ].edgenr = 10; //  = geom.emap.FindIndex(edge);
1940
1941       ngMesh.AddSegment (seg);
1942
1943       // add reverse segment
1944       swap( seg[0], seg[1] );
1945       swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1946       seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1947       ngMesh.AddSegment (seg);
1948     }
1949
1950   }
1951   ngMesh.CalcSurfacesOfNode();
1952 }
1953
1954 //================================================================================
1955 /*!
1956  * \brief Make netgen take internal vertices in solids into account by adding
1957  *        faces including internal vertices
1958  *
1959  * This function works in supposition that 2D mesh is already computed in ngMesh
1960  */
1961 //================================================================================
1962
1963 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry&     occgeom,
1964                                                  netgen::Mesh&                  ngMesh,
1965                                                  vector<const SMDS_MeshNode*>&  nodeVec,
1966                                                  NETGENPlugin_Internals&        internalShapes)
1967 {
1968 #ifdef DUMP_TRIANGLES_SCRIPT
1969   // create a python script making a mesh containing triangles added for internal vertices
1970   ofstream py(DUMP_TRIANGLES_SCRIPT);
1971   py << "import SMESH"<< endl
1972      << "from salome.smesh import smeshBuilder"<<endl
1973      << "smesh = smeshBuilder.New()"<<endl
1974      << "m = smesh.Mesh(name='triangles')" << endl;
1975 #endif
1976   if ((int) nodeVec.size() < ngMesh.GetNP() )
1977     nodeVec.resize( ngMesh.GetNP(), 0 );
1978
1979   SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1980   SMESH_MesherHelper helper( internalShapes.getMesh() );
1981
1982   const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
1983   map<int,list<int> >::const_iterator s2v = so2Vert.begin();
1984   for ( ; s2v != so2Vert.end(); ++s2v )
1985   {
1986     const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
1987     if ( solid.IsNull() ) continue;
1988     int solidNgID = occgeom.somap.FindIndex (solid);
1989     if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
1990
1991     helper.SetSubShape( solid );
1992     helper.SetElementsOnShape( true );
1993
1994     // find ng indices of faces within the solid
1995     set<int> ngFaceIds;
1996     for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
1997       ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
1998     if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
1999       ngFaceIds.insert( 1 );
2000
2001     // Get data of internal vertices and add them to ngMesh
2002
2003     multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
2004
2005     int i, nbFaceInit = ngMesh.GetNSE();
2006
2007     // boundary characteristics
2008     double totSegLen = 0;
2009     int totNbSeg = 0;
2010
2011     const list<int>& iVertices = s2v->second;
2012     list<int>::const_iterator iv = iVertices.begin();
2013     for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
2014     {
2015       TIntVSoData vData;
2016       const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
2017
2018       // get node on vertex
2019       const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
2020       if ( !nV )
2021       {
2022         SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
2023         sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2024         nV = SMESH_Algo::VertexNode( V, meshDS );
2025         if ( !nV ) continue;
2026       }
2027       // add ng node
2028       netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
2029       ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
2030       vData.ngId = ngMesh.GetNP();
2031       nodeVec.push_back( nV );
2032
2033       // loop on all 2d elements to find the one closest to vertex and to count
2034       // average segment length
2035       double closeDist2 = numeric_limits<double>::max(), avgDist2;
2036       for (i = 1; i <= ngMesh.GetNSE(); ++i)
2037       {
2038         const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2039         if ( !ngFaceIds.count( elem.GetIndex() )) continue;
2040         avgDist2 = 0;
2041         multimap< double, int> dist2nID; // sort nodes of element by distance from V
2042         for ( int j = 0; j < elem.GetNP(); ++j)
2043         {
2044           netgen::MeshPoint mp = ngMesh.Point( elem[j] );
2045           double d2 = dist2( mpV, mp );
2046           dist2nID.insert( make_pair( d2, elem[j] ));
2047           avgDist2 += d2 / elem.GetNP();
2048           if ( !nbV )
2049             totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
2050         }
2051         double dist = dist2nID.begin()->first; //avgDist2;
2052         if ( dist < closeDist2 )
2053           vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
2054       }
2055       dist2VData.insert( make_pair( closeDist2, vData ));
2056     }
2057
2058     if ( totNbSeg == 0 ) break;
2059     double avgSegLen = totSegLen / totNbSeg;
2060
2061     // Loop on vertices to add triangles
2062
2063     multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
2064     for ( ; dist_vData != dist2VData.end(); ++dist_vData )
2065     {
2066       double closeDist2   = dist_vData->first;
2067       TIntVSoData & vData = dist_vData->second;
2068
2069       const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
2070
2071       // try to find more close face among ones added for internal vertices
2072       for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
2073       {
2074         double avgDist2 = 0;
2075         multimap< double, int> dist2nID;
2076         const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2077         for ( int j = 0; j < elem.GetNP(); ++j)
2078         {
2079           double d = dist2( mpV, ngMesh.Point( elem[j] ));
2080           dist2nID.insert( make_pair( d, elem[j] ));
2081           avgDist2 += d / elem.GetNP();
2082           if ( avgDist2 < closeDist2 )
2083             vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
2084         }
2085       }
2086       // sort nodes of the closest face by angle with vector from V to the closest node
2087       const double tol = numeric_limits<double>::min();
2088       map< double, int > angle2ID;
2089       const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
2090       netgen::MeshPoint mp[2];
2091       mp[0] = ngMesh.Point( vData.ngIdCloseN );
2092       gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
2093       gp_XYZ pV( NGPOINT_COORDS( mpV ));
2094       gp_Vec v2p1( pV, p1 );
2095       double distN1 = v2p1.Magnitude();
2096       if ( distN1 <= tol ) continue;
2097       v2p1 /= distN1;
2098       for ( int j = 0; j < closeFace.GetNP(); ++j)
2099       {
2100         mp[1] = ngMesh.Point( closeFace[j] );
2101         gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
2102         angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
2103       }
2104       // get node with angle of 60 degrees or greater
2105       map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
2106       if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
2107       const double minAngle = 30. * M_PI / 180.;
2108       const double angle = angle_id->first;
2109       bool angleOK = ( angle > minAngle );
2110
2111       // find points to create a triangle
2112       netgen::Element2d tri(3);
2113       tri.SetIndex ( 1 );
2114       tri[0] = vData.ngId;
2115       tri[1] = vData.ngIdCloseN; // to use the closest nodes
2116       tri[2] = angle_id->second; // to use the node with best angle
2117
2118       // decide whether to use the closest node and the node with best angle or to create new ones
2119       for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
2120       {
2121         bool createNew = !angleOK; //, distOK = true;
2122         double distFromV;
2123         int triInd = isBestAngleN ? 2 : 1;
2124         mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
2125         if ( isBestAngleN )
2126         {
2127           if ( angleOK )
2128           {
2129             double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
2130             createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
2131           }
2132           else if ( angle < tol )
2133           {
2134             v2p1.SetX( v2p1.X() + 1e-3 );
2135           }
2136           distFromV = distN1;
2137         }
2138         else
2139         {
2140           double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
2141           bool     avgLenOK = ( avgSegLen < 0.75 * distN1 );
2142           bool    hintLenOK = ( segLenHint  < 0.75 * distN1 );
2143           createNew = (createNew || avgLenOK || hintLenOK );
2144           // we create a new node not closer than 0.5 to the closest face
2145           // in order not to clash with other close face
2146           double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
2147           distFromV = r * distN1;
2148         }
2149         if ( createNew )
2150         {
2151           // create a new point, between the node and the vertex if angleOK
2152           gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
2153           gp_Vec v2p( pV, p ); v2p.Normalize();
2154           if ( isBestAngleN && !angleOK )
2155             p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
2156           else
2157             p = pV + v2p.XYZ() * distFromV;
2158
2159           if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
2160
2161           mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
2162           ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
2163           tri[triInd] = ngMesh.GetNP();
2164           nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
2165         }
2166       }
2167       ngMesh.AddSurfaceElement (tri);
2168       swap( tri[1], tri[2] );
2169       ngMesh.AddSurfaceElement (tri);
2170
2171 #ifdef DUMP_TRIANGLES_SCRIPT
2172       py << "n1 = m.AddNode( "<< mpV(0)<<", "<< mpV(1)<<", "<< mpV(2)<<") "<< endl
2173          << "n2 = m.AddNode( "<< mp[0](0)<<", "<< mp[0](1)<<", "<< mp[0](2)<<") "<< endl
2174          << "n3 = m.AddNode( "<< mp[1](0)<<", "<< mp[1](1)<<", "<< mp[1](2)<<" )" << endl
2175          << "m.AddFace([n1,n2,n3])" << endl;
2176 #endif
2177     } // loop on internal vertices of a solid
2178
2179   } // loop on solids with internal vertices
2180 }
2181
2182 //================================================================================
2183 /*!
2184  * \brief Fill netgen mesh with segments of a FACE
2185  *  \param ngMesh - netgen mesh
2186  *  \param geom - container of OCCT geometry to mesh
2187  *  \param wires - data of nodes on FACE boundary
2188  *  \param helper - mesher helper holding the FACE
2189  *  \param nodeVec - vector of nodes in which node index == netgen ID
2190  *  \retval SMESH_ComputeErrorPtr - error description 
2191  */
2192 //================================================================================
2193
2194 SMESH_ComputeErrorPtr
2195 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh&                    ngMesh,
2196                                        netgen::OCCGeometry&             geom,
2197                                        const TSideVector&               wires,
2198                                        SMESH_MesherHelper&              helper,
2199                                        vector< const SMDS_MeshNode* > & nodeVec,
2200                                        const bool                       overrideMinH)
2201 {
2202   // ----------------------------
2203   // Check wires and count nodes
2204   // ----------------------------
2205   smIdType nbNodes = 0;
2206   for ( size_t iW = 0; iW < wires.size(); ++iW )
2207   {
2208     StdMeshers_FaceSidePtr wire = wires[ iW ];
2209     if ( wire->MissVertexNode() )
2210     {
2211       // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
2212       // It seems that there is no reason for this limitation
2213 //       return TError
2214 //         (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
2215     }
2216     const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2217     if ((int) uvPtVec.size() != wire->NbPoints() )
2218       return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
2219                                      SMESH_Comment("Unexpected nb of points on wire ") << iW
2220                                      << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
2221     nbNodes += wire->NbPoints();
2222   }
2223   nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
2224   if ( nodeVec.empty() )
2225     nodeVec.push_back( 0 );
2226
2227   // -----------------
2228   // Fill netgen mesh
2229   // -----------------
2230
2231   const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
2232                                                          NETGENPlugin_NETGEN_2D_ONLY */
2233
2234   // map for nodes on vertices since they can be shared between wires
2235   // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
2236   map<const SMDS_MeshNode*, int > node2ngID;
2237   if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
2238   {
2239     set< int > subIDs; // ids of sub-shapes of the FACE
2240     for ( size_t iW = 0; iW < wires.size(); ++iW )
2241     {
2242       StdMeshers_FaceSidePtr wire = wires[ iW ];
2243       for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
2244       {
2245         subIDs.insert( wire->EdgeID( iE ));
2246         subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
2247       }
2248     }
2249     for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
2250       if ( subIDs.count( nodeVec[ngID]->GetShapeID() ))
2251         node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
2252   }
2253
2254   const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
2255   if ( ngMesh.GetNFD() < 1 )
2256     ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceID, solidID, solidID, 0 ));
2257
2258   for ( size_t iW = 0; iW < wires.size(); ++iW )
2259   {
2260     StdMeshers_FaceSidePtr       wire = wires[ iW ];
2261     const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2262     const smIdType         nbSegments = wire->NbPoints() - 1;
2263
2264     // assure the 1st node to be in node2ngID, which is needed to correctly
2265     // "close chain of segments" (see below) in case if the 1st node is not
2266     // onVertex because it is on a Viscous layer
2267     node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
2268
2269     // compute length of every segment
2270     vector<double> segLen( nbSegments );
2271     for ( int i = 0; i < nbSegments; ++i )
2272       segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
2273
2274     int edgeID = 1, posID = -2;
2275     bool isInternalWire = false;
2276     double vertexNormPar = 0;
2277     const int prevNbNGSeg = ngMesh.GetNSeg();
2278     for ( int i = 0; i < nbSegments; ++i ) // loop on segments
2279     {
2280       // Add the first point of a segment
2281
2282       const SMDS_MeshNode * n = uvPtVec[ i ].node;
2283       const int posShapeID = n->GetShapeID();
2284       bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
2285       bool onEdge   = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE   );
2286
2287       // skip nodes on degenerated edges
2288       if ( helper.IsDegenShape( posShapeID ) &&
2289            helper.IsDegenShape( uvPtVec[ i+1 ].node->GetShapeID() ))
2290         continue;
2291
2292       int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
2293       if ( onVertex || ( !wasNgMeshEmpty && onEdge ) || helper.IsRealSeam( posShapeID ))
2294         ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
2295       if ( ngID1 > ngMesh.GetNP() )
2296       {
2297         netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
2298         ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2299         nodeVec.push_back( n );
2300       }
2301       else // n is in ngMesh already, and ngID2 in prev segment is wrong
2302       {
2303         ngID2 = ngMesh.GetNP() + 1;
2304         if ( i > 0 ) // prev segment belongs to same wire
2305         {
2306           netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2307           prevSeg[1] = ngID1;
2308         }
2309       }
2310
2311       // Add the segment
2312
2313       netgen::Segment seg;
2314
2315       seg[0]     = ngID1;                // ng node id
2316       seg[1]     = ngID2;                // ng node id
2317       seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
2318       seg.si     = faceID;               // = geom.fmap.FindIndex (face);
2319
2320       for ( int iEnd = 0; iEnd < 2; ++iEnd)
2321       {
2322         const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
2323
2324         seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
2325         seg.epgeominfo[ iEnd ].u    = pnt.u;
2326         seg.epgeominfo[ iEnd ].v    = pnt.v;
2327
2328         // find out edge id and node parameter on edge
2329         onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
2330         if ( onVertex || posShapeID != posID )
2331         {
2332           // get edge id
2333           double normParam = pnt.normParam;
2334           if ( onVertex )
2335             normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
2336           int edgeIndexInWire = wire->EdgeIndex( normParam );
2337           vertexNormPar = wire->LastParameter( edgeIndexInWire );
2338           const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
2339           edgeID = geom.emap.FindIndex( edge );
2340           posID  = posShapeID;
2341           isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
2342           // if ( onVertex ) // param on curve is different on each of two edges
2343           //   seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
2344         }
2345         seg.epgeominfo[ iEnd ].edgenr = edgeID; //  = geom.emap.FindIndex(edge);
2346       }
2347
2348       ngMesh.AddSegment (seg);
2349       {
2350         // restrict size of elements near the segment
2351         SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
2352         // get an average size of adjacent segments to avoid sharp change of
2353         // element size (regression on issue 0020452, note 0010898)
2354         int   iPrev = SMESH_MesherHelper::WrapIndex( i-1, (int) nbSegments );
2355         int   iNext = SMESH_MesherHelper::WrapIndex( i+1, (int) nbSegments );
2356         double sumH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
2357         int   nbSeg = ( int( segLen[ iPrev ] > sumH / 100.)  +
2358                         int( segLen[ i     ] > sumH / 100.)  +
2359                         int( segLen[ iNext ] > sumH / 100.));
2360         if ( nbSeg > 0 )
2361           RestrictLocalSize( ngMesh, 0.5*(np1+np2), sumH / nbSeg, overrideMinH );
2362       }
2363       if ( isInternalWire )
2364       {
2365         swap (seg[0], seg[1]);
2366         swap( seg.epgeominfo[0], seg.epgeominfo[1] );
2367         seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
2368         ngMesh.AddSegment (seg);
2369       }
2370     } // loop on segments on a wire
2371
2372     // close chain of segments
2373     if ( nbSegments > 0 )
2374     {
2375       netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire ));
2376       const SMDS_MeshNode * lastNode = uvPtVec.back().node;
2377       lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
2378       if ( lastSeg[1] > ngMesh.GetNP() )
2379       {
2380         netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
2381         ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2382         nodeVec.push_back( lastNode );
2383       }
2384       if ( isInternalWire )
2385       {
2386         netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2387         realLastSeg[0] = lastSeg[1];
2388       }
2389     }
2390
2391 #ifdef DUMP_SEGMENTS
2392     cout << "BEGIN WIRE " << iW << endl;
2393     for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
2394     {
2395       netgen::Segment& seg = ngMesh.LineSegment( i );
2396       if ( i > 1 ) {
2397         netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
2398         if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
2399         {
2400           cout << "Segment: " << seg.edgenr << endl << "\tis REVERSE of the previous one" << endl;
2401           continue;
2402         }
2403       }
2404       cout << "Segment: " << seg.edgenr << endl
2405            << "\tp1: " << seg[0] << "   n" << nodeVec[ seg[0]]->GetID() << endl
2406            << "\tp2: " << seg[1] << "   n" << nodeVec[ seg[1]]->GetID() <<  endl
2407            << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
2408            << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
2409            << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
2410            << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
2411            << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
2412            << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
2413     }
2414     cout << "--END WIRE " << iW << endl;
2415 #else
2416     SMESH_Comment __not_unused_variable( prevNbNGSeg );
2417 #endif
2418
2419   } // loop on WIREs of a FACE
2420
2421   // add a segment instead of an internal vertex
2422   if ( wasNgMeshEmpty )
2423   {
2424     NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
2425     AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
2426   }
2427   ngMesh.CalcSurfacesOfNode();
2428
2429   return TError();
2430 }
2431
2432 //================================================================================
2433 /*!
2434  * \brief Fill SMESH mesh according to contents of netgen mesh
2435  *  \param occgeo - container of OCCT geometry to mesh
2436  *  \param ngMesh - netgen mesh
2437  *  \param initState - bn of entities in netgen mesh before computing
2438  *  \param sMesh - SMESH mesh to fill in
2439  *  \param nodeVec - vector of nodes in which node index == netgen ID
2440  *  \param comment - returns problem description
2441  *  \param quadHelper - holder of medium nodes of sub-meshes
2442  *  \retval int - error
2443  */
2444 //================================================================================
2445
2446 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry&          occgeo,
2447                                    netgen::Mesh&                       ngMesh,
2448                                    const NETGENPlugin_ngMeshInfo&      initState,
2449                                    SMESH_Mesh&                         sMesh,
2450                                    std::vector<const SMDS_MeshNode*>&  nodeVec,
2451                                    SMESH_Comment&                      comment,
2452                                    SMESH_MesherHelper*                 quadHelper)
2453 {
2454   int nbNod = ngMesh.GetNP();
2455   int nbSeg = ngMesh.GetNSeg();
2456   int nbFac = ngMesh.GetNSE();
2457   int nbVol = ngMesh.GetNE();
2458
2459   SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
2460
2461   // quadHelper is used for either
2462   // 1) making quadratic elements when a lower dimension mesh is loaded
2463   //    to SMESH before conversion to quadratic by NETGEN
2464   // 2) sewing of quadratic elements with quadratic elements of sub-meshes
2465   if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() )
2466     quadHelper = 0;
2467
2468   int ngID, nbInitNod = initState._nbNodes;
2469   if ( initState._elementsRemoved )
2470   {
2471     // PAL23427. Update nodeVec to track removal of netgen free points as a result
2472     // of removal of faces in FillNgMesh() in the case of a shrunk sub-mesh
2473     size_t i, nodeVecSize = nodeVec.size();
2474     const double eps = std::numeric_limits<double>::min();
2475     for ( i = ngID = 1; i < nodeVecSize; ++ngID, ++i )
2476     {
2477       gp_Pnt ngPnt( NGPOINT_COORDS( ngMesh.Point( ngID )));
2478       gp_Pnt node ( SMESH_NodeXYZ (nodeVec_ACCESS(i) ));
2479       if ( ngPnt.SquareDistance( node ) < eps )
2480       {
2481         nodeVec[ ngID ] = nodeVec[ i ];
2482       }
2483       else
2484       {
2485         --ngID;
2486       }
2487     }
2488     nodeVec.resize( ngID );
2489     nbInitNod = ngID - 1;
2490   }
2491   // -------------------------------------
2492   // Create and insert nodes into nodeVec
2493   // -------------------------------------
2494
2495   if ( nbNod > nbInitNod )
2496     nodeVec.resize( nbNod + 1 );
2497   for ( int i = nbInitNod+1; i <= nbNod; ++i )
2498   {
2499     const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
2500     SMDS_MeshNode* node = NULL;
2501     TopoDS_Vertex aVert;
2502     // First, netgen creates nodes on vertices in occgeo.vmap,
2503     // so node index corresponds to vertex index
2504     // but (issue 0020776) netgen does not create nodes with equal coordinates
2505     if ( i-nbInitNod <= occgeo.vmap.Extent() )
2506     {
2507       gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
2508       for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
2509       {
2510         aVert = TopoDS::Vertex( occgeo.vmap( iV ));
2511         gp_Pnt pV = BRep_Tool::Pnt( aVert );
2512         if ( p.SquareDistance( pV ) > 1e-20 )
2513           aVert.Nullify();
2514         else
2515           node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
2516       }
2517     }
2518     if (!node) // node not found on vertex
2519     {
2520       node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
2521       if (!aVert.IsNull())
2522         meshDS->SetNodeOnVertex(node, aVert);
2523     }
2524     nodeVec[i] = node;
2525   }
2526
2527   // -------------------------------------------
2528   // Create mesh segments along geometric edges
2529   // -------------------------------------------
2530
2531   int nbInitSeg = initState._nbSegments;
2532   for ( int i = nbInitSeg+1; i <= nbSeg; ++i )
2533   {
2534     const netgen::Segment& seg = ngMesh.LineSegment(i);
2535     TopoDS_Edge aEdge;
2536     int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
2537     int nbp = 0;
2538     double param2 = 0;
2539     for (int j=0; j < 3; ++j)
2540     {
2541       int pind = pinds[j];
2542       if (pind <= 0 || !nodeVec_ACCESS(pind))
2543         break;
2544       ++nbp;
2545       double param;
2546       if (j < 2)
2547       {
2548         if (aEdge.IsNull())
2549         {
2550           int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
2551           if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2552             aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
2553         }
2554         param = seg.epgeominfo[j].dist;
2555         param2 += param;
2556       }
2557       else // middle point
2558       {
2559         param = param2 * 0.5;
2560       }
2561       if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->GetShapeID() < 1)
2562       {
2563         meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
2564       }
2565     }
2566     if ( nbp > 1 )
2567     {
2568       SMDS_MeshEdge* edge = 0;
2569       if (nbp == 2) // second order ?
2570       {
2571         if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
2572           continue;
2573         if ( quadHelper ) // final mesh must be quadratic
2574           edge = quadHelper->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2575         else
2576           edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2577       }
2578       else
2579       {
2580         if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2581                                nodeVec_ACCESS(pinds[2])))
2582           continue;
2583         edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2584                                nodeVec_ACCESS(pinds[2]));
2585       }
2586       if (!edge)
2587       {
2588         if ( comment.empty() ) comment << "Cannot create a mesh edge";
2589         MESSAGE("Cannot create a mesh edge");
2590         nbSeg = nbFac = nbVol = 0;
2591         break;
2592       }
2593       if ( !aEdge.IsNull() && edge->GetShapeID() < 1 )
2594         meshDS->SetMeshElementOnShape(edge, aEdge);
2595     }
2596     else if ( comment.empty() )
2597     {
2598       comment << "Invalid netgen segment #" << i;
2599     }
2600   }
2601
2602   // ----------------------------------------
2603   // Create mesh faces along geometric faces
2604   // ----------------------------------------
2605
2606   int nbInitFac = initState._nbFaces;
2607   int quadFaceID = ngMesh.GetNFD() + 1;
2608   if ( nbInitFac < nbFac )
2609     // add a faces descriptor to exclude qudrangle elements generated by NETGEN
2610     // from computation of 3D mesh
2611     ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
2612
2613   vector<const SMDS_MeshNode*> nodes;
2614   for ( int i = nbInitFac+1; i <= nbFac; ++i )
2615   {
2616     const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2617     const int        aGeomFaceInd = elem.GetIndex();
2618     TopoDS_Face aFace;
2619     if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
2620       aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
2621     nodes.clear();
2622     for ( int j = 1; j <= elem.GetNP(); ++j )
2623     {
2624       int pind = elem.PNum(j);
2625       if ( pind < 1 || pind >= (int) nodeVec.size() )
2626         break;
2627       if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
2628       {
2629         nodes.push_back( node );
2630         if (!aFace.IsNull() && node->GetShapeID() < 1)
2631         {
2632           const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
2633           meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
2634         }
2635       }
2636     }
2637     if ((int) nodes.size() != elem.GetNP() )
2638     {
2639       if ( comment.empty() )
2640         comment << "Invalid netgen 2d element #" << i;
2641       continue; // bad node ids
2642     }
2643     SMDS_MeshFace* face = NULL;
2644     switch (elem.GetType())
2645     {
2646     case netgen::TRIG:
2647       if ( quadHelper ) // final mesh must be quadratic
2648         face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2]);
2649       else
2650         face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
2651       break;
2652     case netgen::QUAD:
2653       if ( quadHelper ) // final mesh must be quadratic
2654         face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2655       else
2656         face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2657       // exclude qudrangle elements from computation of 3D mesh
2658       const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2659       break;
2660     case netgen::TRIG6:
2661       nodes[5] = mediumNode( nodes[0],nodes[1],nodes[5], quadHelper );
2662       nodes[3] = mediumNode( nodes[1],nodes[2],nodes[3], quadHelper );
2663       nodes[4] = mediumNode( nodes[2],nodes[0],nodes[4], quadHelper );
2664       face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
2665       break;
2666     case netgen::QUAD8:
2667       nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2668       nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2669       nodes[5] = mediumNode( nodes[2],nodes[3],nodes[5], quadHelper );
2670       nodes[6] = mediumNode( nodes[3],nodes[0],nodes[6], quadHelper );
2671       face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
2672                              nodes[4],nodes[7],nodes[5],nodes[6]);
2673       // exclude qudrangle elements from computation of 3D mesh
2674       const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2675       break;
2676     default:
2677       MESSAGE("NETGEN created a face of unexpected type, ignoring");
2678       continue;
2679     }
2680     if ( !face )
2681     {
2682       if ( comment.empty() ) comment << "Cannot create a mesh face";
2683       MESSAGE("Cannot create a mesh face");
2684       nbSeg = nbFac = nbVol = 0;
2685       break;
2686     }
2687     if ( !aFace.IsNull() )
2688       meshDS->SetMeshElementOnShape( face, aFace );
2689   }
2690
2691   // ------------------
2692   // Create tetrahedra
2693   // ------------------
2694
2695   for ( int i = 1; i <= nbVol; ++i )
2696   {
2697     const netgen::Element& elem = ngMesh.VolumeElement(i);      
2698     int aSolidInd = elem.GetIndex();
2699     TopoDS_Solid aSolid;
2700     if ( aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent() )
2701       aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
2702     nodes.clear();
2703     for ( int j = 1; j <= elem.GetNP(); ++j )
2704     {
2705       int pind = elem.PNum(j);
2706       if ( pind < 1 || pind >= (int)nodeVec.size() )
2707         break;
2708       if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
2709       {
2710         nodes.push_back(node);
2711         if ( !aSolid.IsNull() && node->GetShapeID() < 1 )
2712           meshDS->SetNodeInVolume(node, aSolid);
2713       }
2714     }
2715     if ((int) nodes.size() != elem.GetNP() )
2716     {
2717       if ( comment.empty() )
2718         comment << "Invalid netgen 3d element #" << i;
2719       continue;
2720     }
2721     SMDS_MeshVolume* vol = NULL;
2722     switch ( elem.GetType() )
2723     {
2724     case netgen::TET:
2725       vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
2726       break;
2727     case netgen::TET10:
2728       nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2729       nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2730       nodes[5] = mediumNode( nodes[2],nodes[0],nodes[5], quadHelper );
2731       nodes[6] = mediumNode( nodes[0],nodes[3],nodes[6], quadHelper );
2732       nodes[8] = mediumNode( nodes[1],nodes[3],nodes[8], quadHelper );
2733       nodes[9] = mediumNode( nodes[2],nodes[3],nodes[9], quadHelper );
2734       vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
2735                               nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
2736       break;
2737     default:
2738       MESSAGE("NETGEN created a volume of unexpected type, ignoring");
2739       continue;
2740     }
2741     if (!vol)
2742     {
2743       if ( comment.empty() ) comment << "Cannot create a mesh volume";
2744       MESSAGE("Cannot create a mesh volume");
2745       nbSeg = nbFac = nbVol = 0;
2746       break;
2747     }
2748     if (!aSolid.IsNull())
2749       meshDS->SetMeshElementOnShape(vol, aSolid);
2750   }
2751   return comment.empty() ? 0 : 1;
2752 }
2753
2754 namespace
2755 {
2756   //================================================================================
2757   /*!
2758    * \brief Convert error into text
2759    */
2760   //================================================================================
2761
2762   std::string text(int err)
2763   {
2764     if ( !err )
2765       return string("");
2766     return
2767       SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2768   }
2769
2770   //================================================================================
2771   /*!
2772    * \brief Convert exception into text
2773    */
2774   //================================================================================
2775
2776   std::string text(Standard_Failure& ex)
2777   {
2778     SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2779     str << " at " << netgen::multithread.task
2780         << ": " << ex.DynamicType()->Name();
2781     if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2782       str << ": " << ex.GetMessageString();
2783     return str;
2784   }
2785   //================================================================================
2786   /*!
2787    * \brief Convert exception into text
2788    */
2789   //================================================================================
2790
2791   std::string text(netgen::NgException& ex)
2792   {
2793     SMESH_Comment str("NgException");
2794     if ( strlen( netgen::multithread.task ) > 0 )
2795       str << " at " << netgen::multithread.task;
2796     str << ": " << ex.What();
2797     return str;
2798   }
2799
2800   //================================================================================
2801   /*!
2802    * \brief Looks for triangles lying on a SOLID
2803    */
2804   //================================================================================
2805
2806   bool hasBadElemOnSolid( const list<const SMDS_MeshElement*>& elems,
2807                           SMESH_subMesh*                       solidSM )
2808   {
2809     TopTools_IndexedMapOfShape solidSubs;
2810     TopExp::MapShapes( solidSM->GetSubShape(), solidSubs );
2811     SMESHDS_Mesh* mesh = solidSM->GetFather()->GetMeshDS();
2812
2813     list<const SMDS_MeshElement*>::const_iterator e = elems.begin();
2814     for ( ; e != elems.end(); ++e )
2815     {
2816       const SMDS_MeshElement* elem = *e;
2817       // if ( elem->GetType() != SMDSAbs_Face ) -- 23047
2818       //   continue;
2819       int nbNodesOnSolid = 0, nbNodes = elem->NbNodes();
2820       SMDS_NodeIteratorPtr nIt = elem->nodeIterator();
2821       while ( nIt->more() )
2822       {
2823         const SMDS_MeshNode* n = nIt->next();
2824         const TopoDS_Shape&  s = mesh->IndexToShape( n->GetShapeID() );
2825         nbNodesOnSolid += ( !s.IsNull() && solidSubs.Contains( s ));
2826         if ( nbNodesOnSolid > 2 ||
2827              nbNodesOnSolid == nbNodes)
2828           return true;
2829       }
2830     }
2831     return false;
2832   }
2833
2834   const double edgeMeshingTime = 0.001;
2835   const double faceMeshingTime = 0.019;
2836   const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
2837   const double faceOptimizTime = 0.06;
2838   const double voluMeshingTime = 0.15;
2839   const double volOptimizeTime = 0.77;
2840 }
2841
2842 //=============================================================================
2843 /*!
2844  * Here we are going to use the NETGEN mesher
2845  */
2846 //=============================================================================
2847
2848 bool NETGENPlugin_Mesher::Compute()
2849 {
2850   NETGENPlugin_NetgenLibWrapper ngLib;
2851
2852   netgen::MeshingParameters& mparams = netgen::mparam;
2853
2854   SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2855   SMESH_MesherHelper quadHelper( *_mesh );
2856   quadHelper.SetIsQuadratic( mparams.secondorder );
2857
2858   // -------------------------
2859   // Prepare OCC geometry
2860   // -------------------------
2861
2862   netgen::OCCGeometry occgeo;
2863   list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2864   NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2865   PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2866   _occgeom = &occgeo;
2867
2868   _totalTime = edgeFaceMeshingTime;
2869   if ( _optimize )
2870     _totalTime += faceOptimizTime;
2871   if ( _isVolume )
2872     _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
2873   double doneTime = 0;
2874   _ticTime = -1;
2875   _progressTic = 1;
2876   _curShapeIndex = -1;
2877
2878   // -------------------------
2879   // Generate the mesh
2880   // -------------------------
2881
2882   _ngMesh = NULL;
2883   NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2884
2885   SMESH_Comment comment;
2886   int err = 0;
2887
2888   // vector of nodes in which node index == netgen ID
2889   vector< const SMDS_MeshNode* > nodeVec;
2890   
2891   {
2892     // ----------------
2893     // compute 1D mesh
2894     // ----------------
2895     if ( _simpleHyp )
2896     {
2897       // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2898       mparams.uselocalh = false;
2899       mparams.grading = 0.8; // not limitited size growth
2900
2901       if ( _simpleHyp->GetNumberOfSegments() )
2902         // nb of segments
2903         mparams.maxh = occgeo.boundingbox.Diam();
2904       else
2905         // segment length
2906         mparams.maxh = _simpleHyp->GetLocalLength();
2907     }
2908
2909     if ( mparams.maxh == 0.0 )
2910       mparams.maxh = occgeo.boundingbox.Diam();
2911     if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2912       mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2913
2914     // Local size on faces
2915     occgeo.face_maxh = mparams.maxh;
2916
2917     // Let netgen create _ngMesh and calculate element size on not meshed shapes
2918     int startWith = netgen::MESHCONST_ANALYSE;
2919     int endWith   = netgen::MESHCONST_ANALYSE;
2920     try
2921     {
2922       OCC_CATCH_SIGNALS;
2923
2924       err = ngLib.GenerateMesh(occgeo, startWith, endWith, _ngMesh);
2925
2926       if(netgen::multithread.terminate)
2927         return false;
2928
2929       comment << text(err);
2930     }
2931     catch (Standard_Failure& ex)
2932     {
2933       comment << text(ex);
2934     }
2935     catch (netgen::NgException & ex)
2936     {
2937       comment << text(ex);
2938 #ifdef NETGEN_V6
2939       bool hasSizeFile = !mparams.meshsizefilename.empty();
2940 #else
2941       bool hasSizeFile = mparams.meshsizefilename;
2942 #endif
2943       if ( hasSizeFile )
2944         throw SMESH_ComputeError(COMPERR_BAD_PARMETERS, comment );
2945     }
2946     err = 0; //- MESHCONST_ANALYSE isn't so important step
2947     if ( !_ngMesh )
2948       return false;
2949     ngLib.setMesh(( Ng_Mesh*) _ngMesh );
2950
2951     _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2952
2953     if ( !mparams.uselocalh ) // mparams.grading is not taken into account yet
2954       _ngMesh->LocalHFunction().SetGrading( mparams.grading );
2955
2956     if ( _simpleHyp )
2957     {
2958       // Pass 1D simple parameters to NETGEN
2959       // --------------------------------
2960       double nbSeg   = (double) _simpleHyp->GetNumberOfSegments();
2961       double segSize = _simpleHyp->GetLocalLength();
2962       for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2963       {
2964         const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2965         if ( nbSeg )
2966           segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2967         setLocalSize( e, segSize, *_ngMesh );
2968       }
2969     }
2970     else // if ( ! _simpleHyp )
2971     {
2972       // Local size on shapes
2973       SetLocalSize( occgeo, *_ngMesh );
2974       SetLocalSizeForChordalError( occgeo, *_ngMesh );
2975     }
2976
2977     // Precompute internal edges (issue 0020676) in order to
2978     // add mesh on them correctly (twice) to netgen mesh
2979     if ( !err && internals.hasInternalEdges() )
2980     {
2981       // load internal shapes into OCCGeometry
2982       netgen::OCCGeometry intOccgeo;
2983       internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
2984       intOccgeo.boundingbox = occgeo.boundingbox;
2985       intOccgeo.shape = occgeo.shape;
2986       intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
2987       intOccgeo.face_maxh = netgen::mparam.maxh;
2988       netgen::Mesh *tmpNgMesh = NULL;
2989       try
2990       {
2991         OCC_CATCH_SIGNALS;
2992         // compute local H on internal shapes in the main mesh
2993         //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
2994
2995         // let netgen create a temporary mesh
2996         ngLib.GenerateMesh(intOccgeo, startWith, endWith, tmpNgMesh);
2997
2998         if ( netgen::multithread.terminate )
2999           return false;
3000
3001         // copy LocalH from the main to temporary mesh
3002         initState.transferLocalH( _ngMesh, tmpNgMesh );
3003
3004         // compute mesh on internal edges
3005         startWith = endWith = netgen::MESHCONST_MESHEDGES;
3006         err = ngLib.GenerateMesh(intOccgeo, startWith, endWith, tmpNgMesh);
3007
3008         comment << text(err);
3009       }
3010       catch (Standard_Failure& ex)
3011       {
3012         comment << text(ex);
3013         err = 1;
3014       }
3015       initState.restoreLocalH( tmpNgMesh );
3016
3017       // fill SMESH by netgen mesh
3018       vector< const SMDS_MeshNode* > tmpNodeVec;
3019       FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
3020       err = ( err || !comment.empty() );
3021
3022       nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
3023     }
3024
3025     // Fill _ngMesh with nodes and segments of computed submeshes
3026     if ( !err )
3027     {
3028       err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
3029                 FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ], &quadHelper));
3030     }
3031     initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3032
3033     // Compute 1d mesh
3034     if (!err)
3035     {
3036       startWith = endWith = netgen::MESHCONST_MESHEDGES;
3037       try
3038       {
3039         OCC_CATCH_SIGNALS;
3040
3041         err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3042
3043         if ( netgen::multithread.terminate )
3044           return false;
3045
3046         comment << text(err);
3047       }
3048       catch (Standard_Failure& ex)
3049       {
3050         comment << text(ex);
3051         err = 1;
3052       }
3053     }
3054     if ( _isVolume )
3055       _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
3056
3057     mparams.uselocalh = true; // restore as it is used at surface optimization
3058
3059     // ---------------------
3060     // compute surface mesh
3061     // ---------------------
3062     if (!err)
3063     {
3064       // Pass 2D simple parameters to NETGEN
3065       if ( _simpleHyp ) {
3066         if ( double area = _simpleHyp->GetMaxElementArea() ) {
3067           // face area
3068           mparams.maxh = sqrt(2. * area/sqrt(3.0));
3069           mparams.grading = 0.4; // moderate size growth
3070         }
3071         else {
3072           // length from edges
3073           if ( _ngMesh->GetNSeg() ) {
3074             double edgeLength = 0;
3075             TopTools_MapOfShape visitedEdges;
3076             for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
3077               if( visitedEdges.Add(exp.Current()) )
3078                 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
3079             // we have to multiply length by 2 since for each TopoDS_Edge there
3080             // are double set of NETGEN edges, in other words, we have to
3081             // divide _ngMesh->GetNSeg() by 2.
3082             mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
3083           }
3084           else {
3085             mparams.maxh = 1000;
3086           }
3087           mparams.grading = 0.2; // slow size growth
3088         }
3089         mparams.quad = _simpleHyp->GetAllowQuadrangles();
3090         mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3091         _ngMesh->SetGlobalH (mparams.maxh);
3092         netgen::Box<3> bb = occgeo.GetBoundingBox();
3093         bb.Increase (bb.Diam()/20);
3094         _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
3095       }
3096
3097       // Care of vertices internal in faces (issue 0020676)
3098       if ( internals.hasInternalVertexInFace() )
3099       {
3100         // store computed segments in SMESH in order not to create SMESH
3101         // edges for ng segments added by AddIntVerticesInFaces()
3102         FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
3103         // add segments to faces with internal vertices
3104         AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
3105         initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3106       }
3107
3108       // Build viscous layers
3109       if (( _isViscousLayers2D ) ||
3110           ( !occgeo.fmap.IsEmpty() &&
3111             StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( occgeo.fmap(1) ), *_mesh )))
3112       {
3113         if ( !internals.hasInternalVertexInFace() ) {
3114           FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
3115           initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3116         }
3117         SMESH_ProxyMesh::Ptr viscousMesh;
3118         SMESH_MesherHelper   helper( *_mesh );
3119         for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
3120         {
3121           const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
3122           viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
3123           if ( !viscousMesh )
3124             return false;
3125           if ( viscousMesh->NbProxySubMeshes() == 0 )
3126             continue;
3127           // exclude from computation ng segments built on EDGEs of F
3128           for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
3129           {
3130             netgen::Segment & seg = _ngMesh->LineSegment(i);
3131             if (seg.si == faceID)
3132               seg.si = 0;
3133           }
3134           // add new segments to _ngMesh instead of excluded ones
3135           helper.SetSubShape( F );
3136           TSideVector wires =
3137             StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
3138                                                error, &helper, viscousMesh );
3139           error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
3140
3141           if ( !error ) error = SMESH_ComputeError::New();
3142         }
3143         initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3144       }
3145
3146       // Let netgen compute 2D mesh
3147       startWith = netgen::MESHCONST_MESHSURFACE;
3148       endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
3149       try
3150       {
3151         OCC_CATCH_SIGNALS;
3152
3153         err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3154
3155         if ( netgen::multithread.terminate )
3156           return false;
3157
3158         comment << text (err);
3159       }
3160       catch (Standard_Failure& ex)
3161       {
3162         comment << text(ex);
3163         //err = 1; -- try to make volumes anyway
3164       }
3165       catch (netgen::NgException& exc)
3166       {
3167         comment << text(exc);
3168         //err = 1; -- try to make volumes anyway
3169       }
3170     }
3171     if ( _isVolume )
3172     {
3173       doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
3174       _ticTime = doneTime / _totalTime / _progressTic;
3175     }
3176     // ---------------------
3177     // generate volume mesh
3178     // ---------------------
3179     // Fill _ngMesh with nodes and faces of computed 2D submeshes
3180     if ( !err && _isVolume &&
3181          ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad || _viscousLayersHyp ))
3182     {
3183       // load SMESH with computed segments and faces
3184       FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3185
3186       // compute prismatic boundary volumes
3187       smIdType nbQuad = _mesh->NbQuadrangles();
3188       SMESH_ProxyMesh::Ptr viscousMesh;
3189       if ( _viscousLayersHyp )
3190       {
3191         viscousMesh = _viscousLayersHyp->Compute( *_mesh, _shape );
3192         if ( !viscousMesh )
3193           return false;
3194       }
3195       // compute pyramids on quadrangles
3196       vector<SMESH_ProxyMesh::Ptr> pyramidMeshes( occgeo.somap.Extent() );
3197       if ( nbQuad > 0 )
3198         for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
3199         {
3200           StdMeshers_QuadToTriaAdaptor* adaptor = new StdMeshers_QuadToTriaAdaptor;
3201           pyramidMeshes[ iS-1 ].reset( adaptor );
3202           bool ok = adaptor->Compute( *_mesh, occgeo.somap(iS), viscousMesh.get() );
3203           if ( !ok )
3204             return false;
3205         }
3206       // add proxy faces to NG mesh
3207       list< SMESH_subMesh* > viscousSM;
3208       for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
3209       {
3210         list< SMESH_subMesh* > quadFaceSM;
3211         for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
3212           if ( pyramidMeshes[iS-1] && pyramidMeshes[iS-1]->GetProxySubMesh( face.Current() ))
3213           {
3214             quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
3215             meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
3216           }
3217           else if ( viscousMesh && viscousMesh->GetProxySubMesh( face.Current() ))
3218           {
3219             viscousSM.push_back( _mesh->GetSubMesh( face.Current() ));
3220             meshedSM[ MeshDim_2D ].remove( viscousSM.back() );
3221           }
3222         if ( !quadFaceSM.empty() )
3223           FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, pyramidMeshes[iS-1]);
3224       }
3225       if ( !viscousSM.empty() )
3226         FillNgMesh(occgeo, *_ngMesh, nodeVec, viscousSM, &quadHelper, viscousMesh );
3227
3228       // fill _ngMesh with faces of sub-meshes
3229       err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper));
3230       initState = NETGENPlugin_ngMeshInfo(_ngMesh, /*checkRemovedElems=*/true);
3231       // toPython( _ngMesh );
3232     }
3233     if (!err && _isVolume)
3234     {
3235       // Pass 3D simple parameters to NETGEN
3236       const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3237         dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3238       if ( simple3d ) {
3239         _ngMesh->Compress();
3240         if ( double vol = simple3d->GetMaxElementVolume() ) {
3241           // max volume
3242           mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3243           mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3244         }
3245         else {
3246           // length from faces
3247           mparams.maxh = _ngMesh->AverageH();
3248         }
3249         _ngMesh->SetGlobalH (mparams.maxh);
3250         mparams.grading = 0.4;
3251         ngLib.CalcLocalH( ngLib._ngMesh );
3252       }
3253       // Care of vertices internal in solids and internal faces (issue 0020676)
3254       if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
3255       {
3256         // store computed faces in SMESH in order not to create SMESH
3257         // faces for ng faces added here
3258         FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3259         // add ng faces to solids with internal vertices
3260         AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
3261         // duplicate mesh faces on internal faces
3262         FixIntFaces( occgeo, *_ngMesh, internals );
3263         initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3264       }
3265       // Let netgen compute 3D mesh
3266       startWith = endWith = netgen::MESHCONST_MESHVOLUME;
3267       try
3268       {
3269         OCC_CATCH_SIGNALS;
3270
3271         err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3272
3273         if ( netgen::multithread.terminate )
3274           return false;
3275
3276         if ( comment.empty() ) // do not overwrite a previous error
3277           comment << text(err);
3278       }
3279       catch (Standard_Failure& ex)
3280       {
3281         if ( comment.empty() ) // do not overwrite a previous error
3282           comment << text(ex);
3283         err = 1;
3284       }
3285       catch (netgen::NgException& exc)
3286       {
3287         if ( comment.empty() ) // do not overwrite a previous error
3288           comment << text(exc);
3289         err = 1;
3290       }
3291       _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
3292
3293       // Let netgen optimize 3D mesh
3294       if ( !err && _optimize )
3295       {
3296         startWith = endWith = netgen::MESHCONST_OPTVOLUME;
3297         try
3298         {
3299           OCC_CATCH_SIGNALS;
3300
3301           err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3302
3303           if ( netgen::multithread.terminate )
3304             return false;
3305
3306           if ( comment.empty() ) // do not overwrite a previous error
3307             comment << text(err);
3308         }
3309         catch (Standard_Failure& ex)
3310         {
3311           if ( comment.empty() ) // do not overwrite a previous error
3312             comment << text(ex);
3313         }
3314         catch (netgen::NgException& exc)
3315         {
3316           if ( comment.empty() ) // do not overwrite a previous error
3317             comment << text(exc);
3318         }
3319       }
3320     }
3321     if (!err && mparams.secondorder > 0)
3322     {
3323       try
3324       {
3325         OCC_CATCH_SIGNALS;
3326         if ( !meshedSM[ MeshDim_1D ].empty() )
3327         {
3328           // remove segments not attached to geometry (IPAL0052479)
3329           for (int i = 1; i <= _ngMesh->GetNSeg(); ++i)
3330           {
3331             const netgen::Segment & seg = _ngMesh->LineSegment (i);
3332             if ( seg.epgeominfo[ 0 ].edgenr == 0 )
3333             {
3334               _ngMesh->DeleteSegment( i );
3335               initState._nbSegments--;
3336             }
3337           }
3338           _ngMesh->Compress();
3339         }
3340         // convert to quadratic
3341 #ifdef NETGEN_V6
3342         occgeo.GetRefinement().MakeSecondOrder(*_ngMesh);
3343 #else
3344         netgen::OCCRefinementSurfaces(occgeo).MakeSecondOrder(*_ngMesh);
3345 #endif
3346
3347         // care of elements already loaded to SMESH
3348         // if ( initState._nbSegments > 0 )
3349         //   makeQuadratic( occgeo.emap, _mesh );
3350         // if ( initState._nbFaces > 0 )
3351         //   makeQuadratic( occgeo.fmap, _mesh );
3352       }
3353       catch (Standard_Failure& ex)
3354       {
3355         if ( comment.empty() ) // do not overwrite a previous error
3356           comment << "Exception in netgen at passing to 2nd order ";
3357       }
3358       catch (netgen::NgException& exc)
3359       {
3360         if ( comment.empty() ) // do not overwrite a previous error
3361           comment << exc.What();
3362       }
3363     }
3364   }
3365
3366   _ticTime = 0.98 / _progressTic;
3367
3368   //int nbNod = _ngMesh->GetNP();
3369   //int nbSeg = _ngMesh->GetNSeg();
3370   int nbFac = _ngMesh->GetNSE();
3371   int nbVol = _ngMesh->GetNE();
3372   bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
3373
3374   // Feed back the SMESHDS with the generated Nodes and Elements
3375   if ( true /*isOK*/ ) // get whatever built
3376   {
3377     FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3378
3379     if ( quadHelper.GetIsQuadratic() ) // remove free nodes
3380     {
3381       for ( size_t i = 0; i < nodeVec.size(); ++i )
3382         if ( nodeVec[i] && nodeVec[i]->NbInverseElements() == 0 )
3383         {
3384           _mesh->GetMeshDS()->RemoveFreeNode( nodeVec[i], 0, /*fromGroups=*/false );
3385           nodeVec[i]=0;
3386         }
3387       for ( size_t i = nodeVec.size()-1; i > 0; --i ) // remove trailing removed nodes
3388         if ( !nodeVec[i] )
3389           nodeVec.resize( i );
3390         else
3391           break;
3392     }
3393   }
3394   SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
3395   if ( readErr && readErr->HasBadElems() )
3396   {
3397     error = readErr;
3398     if ( !comment.empty() && !readErr->myComment.empty() ) comment += "\n";
3399     comment += readErr->myComment;
3400   }
3401   if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
3402     error->myName = COMPERR_ALGO_FAILED;
3403   if ( !comment.empty() )
3404     error->myComment = comment;
3405
3406   // SetIsAlwaysComputed( true ) to empty sub-meshes, which
3407   // appear if the geometry contains coincident sub-shape due
3408   // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
3409   const int nbMaps = 2;
3410   const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
3411     { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
3412   for ( int iMap = 0; iMap < nbMaps; ++iMap )
3413     for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
3414       if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
3415         if ( !sm->IsMeshComputed() )
3416           sm->SetIsAlwaysComputed( true );
3417
3418   // set bad compute error to subshapes of all failed sub-shapes
3419   if ( !error->IsOK() )
3420   {
3421     bool pb2D = false, pb3D = false;
3422     for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
3423       int status = occgeo.facemeshstatus[i-1];
3424       if (status == netgen::FACE_MESHED_OK ) continue;
3425       if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
3426         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3427         if ( !smError || smError->IsOK() ) {
3428           if ( status == netgen::FACE_FAILED )
3429             smError.reset( new SMESH_ComputeError( *error ));
3430           else
3431             smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
3432           if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3433             smError->myName = COMPERR_WARNING;
3434         }
3435         pb2D = pb2D || smError->IsKO();
3436       }
3437     }
3438     if ( !pb2D ) // all faces are OK
3439       for (int i = 1; i <= occgeo.somap.Extent(); i++)
3440         if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
3441         {
3442           bool smComputed = nbVol && !sm->IsEmpty();
3443           if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
3444           {
3445             size_t nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
3446             SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3447             smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > (smIdType) nbIntV );
3448           }
3449           SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3450           if ( !smComputed && ( !smError || smError->IsOK() ))
3451           {
3452             smError = error;
3453             if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3454             {
3455               smError->myName = COMPERR_WARNING;
3456             }
3457             else if ( smError->HasBadElems() ) // bad surface mesh
3458             {
3459               if ( !hasBadElemOnSolid
3460                    ( static_cast<SMESH_BadInputElements*>( smError.get() )->myBadElements, sm ))
3461                 smError.reset();
3462             }
3463           }
3464           pb3D = pb3D || ( smError && smError->IsKO() );
3465         }
3466     if ( !pb2D && !pb3D )
3467       err = 0; // no fatal errors, only warnings
3468   }
3469
3470   ngLib._isComputeOk = !err;
3471
3472   return !err;
3473 }
3474
3475 //=============================================================================
3476 /*!
3477  * Evaluate
3478  */
3479 //=============================================================================
3480 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
3481 {
3482   netgen::MeshingParameters& mparams = netgen::mparam;
3483
3484
3485   // -------------------------
3486   // Prepare OCC geometry
3487   // -------------------------
3488   netgen::OCCGeometry occgeo;
3489   NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
3490   PrepareOCCgeometry( occgeo, _shape, *_mesh, 0, &internals );
3491
3492   bool tooManyElems = false;
3493   const int hugeNb = std::numeric_limits<int>::max() / 100;
3494
3495   // ----------------
3496   // evaluate 1D 
3497   // ----------------
3498   // pass 1D simple parameters to NETGEN
3499   if ( _simpleHyp )
3500   {
3501     // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
3502     mparams.uselocalh = false;
3503     mparams.grading = 0.8; // not limitited size growth
3504
3505     if ( _simpleHyp->GetNumberOfSegments() )
3506       // nb of segments
3507       mparams.maxh = occgeo.boundingbox.Diam();
3508     else
3509       // segment length
3510       mparams.maxh = _simpleHyp->GetLocalLength();
3511   }
3512
3513   if ( mparams.maxh == 0.0 )
3514     mparams.maxh = occgeo.boundingbox.Diam();
3515   if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
3516     mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
3517
3518   // let netgen create _ngMesh and calculate element size on not meshed shapes
3519   NETGENPlugin_NetgenLibWrapper ngLib;
3520   netgen::Mesh *ngMesh = NULL;
3521   int startWith = netgen::MESHCONST_ANALYSE;
3522   int endWith   = netgen::MESHCONST_MESHEDGES;
3523   int err = ngLib.GenerateMesh(occgeo, startWith, endWith, ngMesh);
3524
3525   if(netgen::multithread.terminate)
3526     return false;
3527
3528   ngLib.setMesh(( Ng_Mesh*) ngMesh );
3529   if (err) {
3530     if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
3531       sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
3532     return false;
3533   }
3534   // if ( _simpleHyp )
3535   // {
3536   //   // Pass 1D simple parameters to NETGEN
3537   //   // --------------------------------
3538   //   int      nbSeg = _simpleHyp->GetNumberOfSegments();
3539   //   double segSize = _simpleHyp->GetLocalLength();
3540   //   for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
3541   //   {
3542   //     const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
3543   //     if ( nbSeg )
3544   //       segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
3545   //     setLocalSize( e, segSize, *ngMesh );
3546   //   }
3547   // }
3548   // else // if ( ! _simpleHyp )
3549   // {
3550   //   // Local size on shapes
3551   //   SetLocalSize( occgeo, *ngMesh );
3552   // }
3553   // calculate total nb of segments and length of edges
3554   double fullLen = 0.0;
3555   smIdType fullNbSeg = 0;
3556   int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
3557   TopTools_DataMapOfShapeInteger Edge2NbSeg;
3558   for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
3559   {
3560     TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3561     if( !Edge2NbSeg.Bind(E,0) )
3562       continue;
3563
3564     double aLen = SMESH_Algo::EdgeLength(E);
3565     fullLen += aLen;
3566
3567     vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(E)];
3568     if ( aVec.empty() )
3569       aVec.resize( SMDSEntity_Last, 0);
3570     else
3571       fullNbSeg += aVec[ entity ];
3572   }
3573
3574   // store nb of segments computed by Netgen
3575   TLinkMap linkMap;
3576   for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
3577   {
3578     const netgen::Segment& seg = ngMesh->LineSegment(i);
3579     Link link(seg[0], seg[1]);
3580     if ( !linkMap.Add( link )) continue;
3581     int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
3582     if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
3583     {
3584       vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
3585       aVec[ entity ]++;
3586     }
3587   }
3588   // store nb of nodes on edges computed by Netgen
3589   TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
3590   for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
3591   {
3592     vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
3593     if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
3594       aVec[SMDSEntity_Node] = mparams.secondorder > 0  ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
3595
3596     fullNbSeg += aVec[ entity ];
3597     Edge2NbSeg( Edge2NbSegIt.Key() ) = (int) aVec[ entity ];
3598   }
3599   if ( fullNbSeg == 0 )
3600     return false;
3601
3602   // ----------------
3603   // evaluate 2D 
3604   // ----------------
3605   if ( _simpleHyp ) {
3606     if ( double area = _simpleHyp->GetMaxElementArea() ) {
3607       // face area
3608       mparams.maxh = sqrt(2. * area/sqrt(3.0));
3609       mparams.grading = 0.4; // moderate size growth
3610     }
3611     else {
3612       // length from edges
3613       mparams.maxh = fullLen / double( fullNbSeg );
3614       mparams.grading = 0.2; // slow size growth
3615     }
3616   }
3617   mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3618   mparams.maxh = min( mparams.maxh, fullLen / double( fullNbSeg ) * (1. + mparams.grading));
3619
3620   for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
3621   {
3622     TopoDS_Face F = TopoDS::Face( exp.Current() );
3623     SMESH_subMesh *sm = _mesh->GetSubMesh(F);
3624     GProp_GProps G;
3625     BRepGProp::SurfaceProperties(F,G);
3626     double anArea = G.Mass();
3627     tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
3628     int nb1d = 0;
3629     if ( !tooManyElems )
3630     {
3631       TopTools_MapOfShape edges;
3632       for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
3633         if ( edges.Add( exp1.Current() ))
3634           nb1d += Edge2NbSeg.Find(exp1.Current());
3635     }
3636     int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
3637     int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
3638
3639     vector<smIdType> aVec(SMDSEntity_Last, 0);
3640     if( mparams.secondorder > 0 ) {
3641       int nb1d_in = (nbFaces*3 - nb1d) / 2;
3642       aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3643       aVec[SMDSEntity_Quad_Triangle] = nbFaces;
3644     }
3645     else {
3646       aVec[SMDSEntity_Node] = Max ( nbNodes, 0  );
3647       aVec[SMDSEntity_Triangle] = nbFaces;
3648     }
3649     aResMap[sm].swap(aVec);
3650   }
3651
3652   // ----------------
3653   // evaluate 3D
3654   // ----------------
3655   if(_isVolume) {
3656     // pass 3D simple parameters to NETGEN
3657     const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3658       dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3659     if ( simple3d ) {
3660       if ( double vol = simple3d->GetMaxElementVolume() ) {
3661         // max volume
3662         mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3663         mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3664       }
3665       else {
3666         // using previous length from faces
3667       }
3668       mparams.grading = 0.4;
3669       mparams.maxh = min( mparams.maxh, fullLen / double( fullNbSeg ) * (1. + mparams.grading));
3670     }
3671     GProp_GProps G;
3672     BRepGProp::VolumeProperties(_shape,G);
3673     double aVolume = G.Mass();
3674     double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
3675     tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
3676     int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
3677     int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3678     vector<smIdType> aVec(SMDSEntity_Last, 0 );
3679     if ( tooManyElems ) // avoid FPE
3680     {
3681       aVec[SMDSEntity_Node] = hugeNb;
3682       aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
3683     }
3684     else
3685     {
3686       if( mparams.secondorder > 0 ) {
3687         aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3688         aVec[SMDSEntity_Quad_Tetra] = nbVols;
3689       }
3690       else {
3691         aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3692         aVec[SMDSEntity_Tetra] = nbVols;
3693       }
3694     }
3695     SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
3696     aResMap[sm].swap(aVec);
3697   }
3698
3699   return true;
3700 }
3701
3702 double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* /*holder*/,
3703                                         const int *       algoProgressTic,
3704                                         const double *    algoProgress) const
3705 {
3706   ((int&) _progressTic ) = *algoProgressTic + 1;
3707
3708   if ( !_occgeom ) return 0;
3709
3710   double progress = -1;
3711   if ( !_isVolume )
3712   {
3713     if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
3714     {
3715       ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
3716     }
3717     else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
3718     {
3719       int doneShapeIndex = -1;
3720       while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
3721               _occgeom->facemeshstatus[ doneShapeIndex+1 ])
3722         doneShapeIndex++;
3723       if ( doneShapeIndex+1 != _curShapeIndex )
3724       {
3725         ((int&) _curShapeIndex) = doneShapeIndex+1;
3726         double    doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
3727         double         doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
3728         ((double&)    _ticTime) = doneTime / _totalTime / _progressTic;
3729         // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3730         //      << " " << doneTime / _totalTime / _progressTic << endl;
3731       }
3732     }
3733   }
3734   else if ( !_optimize && _occgeom->somap.Extent() > 1 )
3735   {
3736     int curShapeIndex = _curShapeIndex;
3737     if ( _ngMesh->GetNE() > 0 )
3738     {
3739       netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
3740       curShapeIndex = el.GetIndex();
3741     }
3742     if ( curShapeIndex != _curShapeIndex )
3743     {
3744       ((int&) _curShapeIndex) = curShapeIndex;
3745       double    doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
3746       double         doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
3747       ((double&)    _ticTime) = doneTime / _totalTime / _progressTic;
3748       // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3749       //      << " " << doneTime / _totalTime / _progressTic << endl;
3750     }
3751   }
3752
3753   if ( _ticTime > 0 )
3754     progress  = Max( *algoProgressTic * _ticTime, *algoProgress );
3755
3756   if ( progress > 0 )
3757   {
3758     if ( _isVolume &&
3759          netgen::multithread.task[0] == 'D'/*elaunay meshing*/ &&
3760          progress > voluMeshingTime )
3761     {
3762       progress = voluMeshingTime;
3763       ((double&) _ticTime) = voluMeshingTime / _totalTime / _progressTic;
3764     }
3765     ((int&) *algoProgressTic )++;
3766     ((double&) *algoProgress) = progress;
3767   }
3768   //cout << progress << " "  << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
3769
3770   return Min( progress, 0.99 );
3771 }
3772
3773 //================================================================================
3774 /*!
3775  * \brief Read mesh entities preventing successful computation from "test.out" file
3776  */
3777 //================================================================================
3778
3779 SMESH_ComputeErrorPtr
3780 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
3781 {
3782   if ( nodeVec.size() < 2 ) return SMESH_ComputeErrorPtr();
3783   SMESH_BadInputElements* err =
3784     new SMESH_BadInputElements( nodeVec.back()->GetMesh(), COMPERR_BAD_INPUT_MESH,
3785                                 "Some edges multiple times in surface mesh");
3786   SMESH_File file("test.out");
3787   vector<int> two(2);
3788   vector<int> three1(3), three2(3);
3789   const char* badEdgeStr = " multiple times in surface mesh";
3790   const int   badEdgeStrLen = (int) strlen( badEdgeStr );
3791   const int   nbNodes = (int) nodeVec.size();
3792
3793   while( !file.eof() )
3794   {
3795     if ( strncmp( file, "Edge ", 5 ) == 0 &&
3796          file.getInts( two ) &&
3797          strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
3798          two[0] < nbNodes  &&  two[1] < nbNodes )
3799     {
3800       err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
3801       file += (int) badEdgeStrLen;
3802     }
3803     else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
3804     {
3805 // Intersecting: 
3806 // openelement 18 with open element 126
3807 // 41  36  38  
3808 // 69  70  72
3809       file.getLine();
3810       const char* pos = file;
3811       bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
3812       ok = ok && file.getInts( two );
3813       ok = ok && file.getInts( three1 );
3814       ok = ok && file.getInts( three2 );
3815       for ( int i = 0; ok && i < 3; ++i )
3816         ok = ( three1[i] < nbNodes && nodeVec[ three1[i]]);
3817       for ( int i = 0; ok && i < 3; ++i ) 
3818         ok = ( three2[i] < nbNodes && nodeVec[ three2[i]]);
3819       if ( ok )
3820       {
3821         err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
3822                                                             nodeVec[ three1[1]],
3823                                                             nodeVec[ three1[2]]));
3824         err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
3825                                                             nodeVec[ three2[1]],
3826                                                             nodeVec[ three2[2]]));
3827         err->myComment = "Intersecting triangles";
3828       }
3829       else
3830       {
3831         file.setPos( pos );
3832       }
3833     }
3834     else
3835     {
3836       ++file;
3837     }
3838   }
3839
3840 #ifdef _DEBUG_
3841   size_t nbBadElems = err->myBadElements.size();
3842   if ( nbBadElems ) nbBadElems++; // avoid warning: variable set but not used
3843 #endif
3844
3845   return SMESH_ComputeErrorPtr( err );
3846 }
3847
3848 //================================================================================
3849 /*!
3850  * \brief Write a python script creating an equivalent SALOME mesh.
3851  * This is useful to see what mesh is passed as input for the next step of mesh
3852  * generation (of mesh of higher dimension)
3853  */
3854 //================================================================================
3855
3856 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh )
3857 {
3858   const char*  pyFile = "/tmp/ngMesh.py";
3859   ofstream outfile( pyFile, ios::out );
3860   if ( !outfile ) return;
3861
3862   outfile << "import salome, SMESH" << std::endl
3863           << "from salome.smesh import smeshBuilder" << std::endl
3864           << "smesh = smeshBuilder.New()" << std::endl
3865           << "mesh = smesh.Mesh()" << std::endl << std::endl;
3866
3867   using namespace netgen;
3868   PointIndex pi;
3869   for (pi = PointIndex::BASE; 
3870        pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3871   {
3872     outfile << "mesh.AddNode( ";
3873     outfile << (*ngMesh)[pi](0) << ", ";
3874     outfile << (*ngMesh)[pi](1) << ", ";
3875     outfile << (*ngMesh)[pi](2) << ") ## "<< pi << std::endl;
3876   }
3877
3878   int nbDom = ngMesh->GetNDomains();
3879   for ( int i = 0; i < nbDom; ++i )
3880     outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< std::endl;
3881
3882   SurfaceElementIndex sei;
3883   for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3884   {
3885     outfile << "mesh.AddFace([ ";
3886     Element2d sel = (*ngMesh)[sei];
3887     for (int j = 0; j < sel.GetNP(); j++)
3888       outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3889     if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3890     outfile << std::endl;
3891
3892     if ((*ngMesh)[sei].GetIndex())
3893     {
3894       if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3895         outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << std::endl;
3896       if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3897         outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << std::endl;
3898     }
3899   }
3900
3901   for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3902   {
3903     Element el = (*ngMesh)[ei];
3904     outfile << "mesh.AddVolume([ ";
3905     for (int j = 0; j < el.GetNP(); j++)
3906       outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3907     outfile << std::endl;
3908   }
3909
3910   for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3911   {
3912     const Segment & seg = ngMesh->LineSegment (i);
3913     outfile << "mesh.AddEdge([ "
3914             << seg[0] << ", "
3915             << seg[1] << " ])" << std::endl;
3916   }
3917   std::cout << "Write " << pyFile << std::endl;
3918 }
3919
3920 //================================================================================
3921 /*!
3922  * \brief Constructor of NETGENPlugin_ngMeshInfo
3923  */
3924 //================================================================================
3925
3926 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh,
3927                                                   bool          checkRemovedElems):
3928   _elementsRemoved( false ), _copyOfLocalH(0)
3929 {
3930   if ( ngMesh )
3931   {
3932     _nbNodes    = ngMesh->GetNP();
3933     _nbSegments = ngMesh->GetNSeg();
3934     _nbFaces    = ngMesh->GetNSE();
3935     _nbVolumes  = ngMesh->GetNE();
3936
3937     if ( checkRemovedElems )
3938       for ( int i = 1; i <= ngMesh->GetNSE() &&  !_elementsRemoved; ++i )
3939         _elementsRemoved = ngMesh->SurfaceElement(i).IsDeleted();
3940   }
3941   else
3942   {
3943     _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
3944   }
3945 }
3946
3947 //================================================================================
3948 /*!
3949  * \brief Copy LocalH member from one netgen mesh to another
3950  */
3951 //================================================================================
3952
3953 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
3954                                               netgen::Mesh* toMesh )
3955 {
3956   if ( !fromMesh->LocalHFunctionGenerated() ) return;
3957   if ( !toMesh->LocalHFunctionGenerated() )
3958     NETGENPlugin_NetgenLibWrapper::CalcLocalH( toMesh );
3959
3960   const size_t size = sizeof( netgen::LocalH );
3961   _copyOfLocalH = new char[ size ];
3962   memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
3963   memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
3964 }
3965
3966 //================================================================================
3967 /*!
3968  * \brief Restore LocalH member of a netgen mesh
3969  */
3970 //================================================================================
3971
3972 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
3973 {
3974   if ( _copyOfLocalH )
3975   {
3976     const size_t size = sizeof( netgen::LocalH );
3977     memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
3978     delete [] _copyOfLocalH;
3979     _copyOfLocalH = 0;
3980   }
3981 }
3982
3983 //================================================================================
3984 /*!
3985  * \brief Find "internal" sub-shapes
3986  */
3987 //================================================================================
3988
3989 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh&         mesh,
3990                                                 const TopoDS_Shape& shape,
3991                                                 bool                is3D )
3992   : _mesh( mesh ), _is3D( is3D )
3993 {
3994   SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3995
3996   TopExp_Explorer f,e;
3997   for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
3998   {
3999     int faceID = meshDS->ShapeToIndex( f.Current() );
4000
4001     // find not computed internal edges
4002
4003     for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
4004       if ( e.Current().Orientation() == TopAbs_INTERNAL )
4005       {
4006         SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
4007         if ( eSM->IsEmpty() )
4008         {
4009           _e2face.insert( make_pair( eSM->GetId(), faceID ));
4010           for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
4011             _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
4012         }
4013       }
4014
4015     // find internal vertices in a face
4016     set<int> intVV; // issue 0020850 where same vertex is twice in a face
4017     for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
4018       if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
4019       {
4020         int vID = meshDS->ShapeToIndex( fSub.Value() );
4021         if ( intVV.insert( vID ).second )
4022           _f2v[ faceID ].push_back( vID );
4023       }
4024
4025     if ( is3D )
4026     {
4027       // find internal faces and their subshapes where nodes are to be doubled
4028       //  to make a crack with non-sewed borders
4029
4030       if ( f.Current().Orientation() == TopAbs_INTERNAL )
4031       {
4032         _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
4033
4034         // edges
4035         list< TopoDS_Shape > edges;
4036         for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
4037           if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
4038           {
4039             _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
4040             edges.push_back( e.Current() );
4041             // find border faces
4042             PShapeIteratorPtr fIt =
4043               SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
4044             while ( const TopoDS_Shape* pFace = fIt->next() )
4045               if ( !pFace->IsSame( f.Current() ))
4046                 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
4047           }
4048         // vertices
4049         // we consider vertex internal if it is shared by more than one internal edge
4050         list< TopoDS_Shape >::iterator edge = edges.begin();
4051         for ( ; edge != edges.end(); ++edge )
4052           for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
4053           {
4054             set<int> internalEdges;
4055             PShapeIteratorPtr eIt =
4056               SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
4057             while ( const TopoDS_Shape* pEdge = eIt->next() )
4058             {
4059               int edgeID = meshDS->ShapeToIndex( *pEdge );
4060               if ( isInternalShape( edgeID ))
4061                 internalEdges.insert( edgeID );
4062             }
4063             if ( internalEdges.size() > 1 )
4064               _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
4065           }
4066       }
4067     }
4068   } // loop on geom faces
4069
4070   // find vertices internal in solids
4071   if ( is3D )
4072   {
4073     for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
4074     {
4075       int soID = meshDS->ShapeToIndex( so.Current() );
4076       for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
4077         if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
4078           _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
4079     }
4080   }
4081 }
4082
4083 //================================================================================
4084 /*!
4085  * \brief Find mesh faces on non-internal geom faces sharing internal edge
4086  * some nodes of which are to be doubled to make the second border of the "crack"
4087  */
4088 //================================================================================
4089
4090 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
4091 {
4092   if ( _intShapes.empty() ) return;
4093
4094   SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
4095   SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
4096
4097   // loop on internal geom edges
4098   set<int>::const_iterator intShapeId = _intShapes.begin();
4099   for ( ; intShapeId != _intShapes.end(); ++intShapeId )
4100   {
4101     const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
4102     if ( s.ShapeType() != TopAbs_EDGE ) continue;
4103
4104     // get internal and non-internal geom faces sharing the internal edge <s>
4105     int intFace = 0;
4106     set<int>::iterator bordFace = _borderFaces.end();
4107     PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
4108     while ( const TopoDS_Shape* pFace = faces->next() )
4109     {
4110       int faceID = meshDS->ShapeToIndex( *pFace );
4111       if ( isInternalShape( faceID ))
4112         intFace = faceID;
4113       else
4114         bordFace = _borderFaces.insert( faceID ).first;
4115     }
4116     if ( bordFace == _borderFaces.end() || !intFace ) continue;
4117
4118     // get all links of mesh faces on internal geom face sharing nodes on edge <s>
4119     set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
4120     list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
4121     int nbSuspectFaces = 0;
4122     SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
4123     if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
4124     SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
4125     while ( smIt->more() )
4126     {
4127       SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
4128       if ( !sm ) continue;
4129       SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4130       while ( nIt->more() )
4131       {
4132         const SMDS_MeshNode* nOnEdge = nIt->next();
4133         SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
4134         while ( fIt->more() )
4135         {
4136           const SMDS_MeshElement* f = fIt->next();
4137           const int nbNodes = f->NbCornerNodes();
4138           if ( intFaceSM->Contains( f ))
4139           {
4140             for ( int i = 0; i < nbNodes; ++i )
4141               links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
4142           }
4143           else
4144           {
4145             int nbDblNodes = 0;
4146             for ( int i = 0; i < nbNodes; ++i )
4147               nbDblNodes += isInternalShape( f->GetNode(i)->GetShapeID() );
4148             if ( nbDblNodes )
4149               suspectFaces[ nbDblNodes < 2 ].push_back( f );
4150             nbSuspectFaces++;
4151           }
4152         }
4153       }
4154     }
4155     // suspectFaces[0] having link with same orientation as mesh faces on
4156     // the internal geom face are <borderElems>. suspectFaces[1] have
4157     // only one node on edge <s>, we decide on them later (at the 2nd loop)
4158     // by links of <borderElems> found at the 1st and 2nd loops
4159     set< SMESH_OrientedLink > borderLinks;
4160     for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
4161     {
4162       list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
4163       for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
4164       {
4165         const SMDS_MeshElement* f = *fIt;
4166         bool isBorder = false, linkFound = false, borderLinkFound = false;
4167         list< SMESH_OrientedLink > faceLinks;
4168         int nbNodes = f->NbCornerNodes();
4169         for ( int i = 0; i < nbNodes; ++i )
4170         {
4171           SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
4172           faceLinks.push_back( link );
4173           if ( !linkFound )
4174           {
4175             set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
4176             if ( foundLink != links.end() )
4177             {
4178               linkFound= true;
4179               isBorder = ( foundLink->_reversed == link._reversed );
4180               if ( !isBorder && !isPostponed ) break;
4181               faceLinks.pop_back();
4182             }
4183             else if ( isPostponed && !borderLinkFound )
4184             {
4185               foundLink = borderLinks.find( link );
4186               if ( foundLink != borderLinks.end() )
4187               {
4188                 borderLinkFound = true;
4189                 isBorder = ( foundLink->_reversed != link._reversed );
4190               }
4191             }
4192           }
4193         }
4194         if ( isBorder )
4195         {
4196           borderElems.insert( f );
4197           borderLinks.insert( faceLinks.begin(), faceLinks.end() );
4198         }
4199         else if ( !linkFound && !borderLinkFound )
4200         {
4201           suspectFaces[1].push_back( f );
4202           if ( nbF > 2 * nbSuspectFaces )
4203             break; // dead loop protection
4204         }
4205       }
4206     }
4207   }
4208 }
4209
4210 //================================================================================
4211 /*!
4212  * \brief put internal shapes in maps and fill in submeshes to precompute
4213  */
4214 //================================================================================
4215
4216 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
4217                                                TopTools_IndexedMapOfShape& emap,
4218                                                TopTools_IndexedMapOfShape& vmap,
4219                                                list< SMESH_subMesh* > smToPrecompute[])
4220 {
4221   if ( !hasInternalEdges() ) return;
4222   map<int,int>::const_iterator ev_face = _e2face.begin();
4223   for ( ; ev_face != _e2face.end(); ++ev_face )
4224   {
4225     const TopoDS_Shape& ev   = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
4226     const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
4227
4228     ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
4229     fmap.Add( face );
4230     //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
4231
4232     smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
4233   }
4234 }
4235
4236 //================================================================================
4237 /*!
4238  * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
4239  */
4240 //================================================================================
4241
4242 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
4243                                                TopTools_IndexedMapOfShape& emap,
4244                                                list< SMESH_subMesh* >&     intFaceSM,
4245                                                list< SMESH_subMesh* >&     boundarySM)
4246 {
4247   if ( !hasInternalFaces() ) return;
4248
4249   // <fmap> and <emap> are for not yet meshed shapes
4250   // <intFaceSM> is for submeshes of faces
4251   // <boundarySM> is for meshed edges and vertices
4252
4253   intFaceSM.clear();
4254   boundarySM.clear();
4255
4256   set<int> shapeIDs ( _intShapes );
4257   if ( !_borderFaces.empty() )
4258     shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
4259
4260   set<int>::const_iterator intS = shapeIDs.begin();
4261   for ( ; intS != shapeIDs.end(); ++intS )
4262   {
4263     SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
4264
4265     if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
4266
4267     intFaceSM.push_back( sm );
4268
4269     // add submeshes of not computed internal faces
4270     if ( !sm->IsEmpty() ) continue;
4271
4272     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
4273     while ( smIt->more() )
4274     {
4275       sm = smIt->next();
4276       const TopoDS_Shape& s = sm->GetSubShape();
4277
4278       if ( sm->IsEmpty() )
4279       {
4280         // not yet meshed
4281         switch ( s.ShapeType() ) {
4282         case TopAbs_FACE: fmap.Add ( s ); break;
4283         case TopAbs_EDGE: emap.Add ( s ); break;
4284         default:;
4285         }
4286       }
4287       else
4288       {
4289         if ( s.ShapeType() != TopAbs_FACE )
4290           boundarySM.push_back( sm );
4291       }
4292     }
4293   }
4294 }
4295
4296 //================================================================================
4297 /*!
4298  * \brief Return true if given shape is to be precomputed in order to be correctly
4299  * added to netgen mesh
4300  */
4301 //================================================================================
4302
4303 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
4304 {
4305   int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
4306   switch ( s.ShapeType() ) {
4307   case TopAbs_FACE  : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
4308   case TopAbs_EDGE  : return isInternalEdge( shapeID );
4309   case TopAbs_VERTEX: break;
4310   default:;
4311   }
4312   return false;
4313 }
4314
4315 //================================================================================
4316 /*!
4317  * \brief Return SMESH
4318  */
4319 //================================================================================
4320
4321 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
4322 {
4323   return const_cast<SMESH_Mesh&>( _mesh );
4324 }
4325
4326 //================================================================================
4327 /*!
4328  * \brief Access to a counter of NETGENPlugin_NetgenLibWrapper instances
4329  */
4330 //================================================================================
4331
4332 int& NETGENPlugin_NetgenLibWrapper::instanceCounter()
4333 {
4334   static int theCouner = 0;
4335   return theCouner;
4336 }
4337
4338 //================================================================================
4339 /*!
4340  * \brief Initialize netgen library
4341  */
4342 //================================================================================
4343
4344 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper():
4345   _ngMesh(0)
4346 {
4347   if ( instanceCounter() == 0 )
4348   {
4349     Ng_Init();
4350     if ( !netgen::testout )
4351       netgen::testout = new ofstream( "test.out" );
4352   }
4353
4354   ++instanceCounter();
4355
4356   _isComputeOk      = false;
4357   _coutBuffer       = NULL;
4358   _ngcout           = NULL;
4359   _ngcerr           = NULL;
4360   if ( !getenv( "KEEP_NETGEN_OUTPUT" ))
4361   {
4362     // redirect all netgen output (mycout,myerr,cout) to _outputFileName
4363     _outputFileName = getOutputFileName();
4364     _ngcout         = netgen::mycout;
4365     _ngcerr         = netgen::myerr;
4366     netgen::mycout  = new ofstream ( _outputFileName.c_str() );
4367     netgen::myerr   = netgen::mycout;
4368     _coutBuffer     = std::cout.rdbuf();
4369 #ifdef _DEBUG_
4370     std::cout << "NOTE: netgen output is redirected to file " << _outputFileName << std::endl;
4371 #else
4372     std::cout.rdbuf( netgen::mycout->rdbuf() );
4373 #endif
4374   }
4375
4376   setMesh( Ng_NewMesh() );
4377 }
4378
4379 //================================================================================
4380 /*!
4381  * \brief Finish using netgen library
4382  */
4383 //================================================================================
4384
4385 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
4386 {
4387   --instanceCounter();
4388
4389   Ng_DeleteMesh( ngMesh() );
4390   Ng_Exit();
4391   RemoveTmpFiles();
4392   if ( _coutBuffer )
4393     std::cout.rdbuf( _coutBuffer );
4394 #ifdef _DEBUG_
4395   if( _isComputeOk )
4396 #endif
4397     removeOutputFile();
4398 }
4399
4400 //================================================================================
4401 /*!
4402  * \brief Set netgen mesh to delete at destruction
4403  */
4404 //================================================================================
4405
4406 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
4407 {
4408   if ( _ngMesh )
4409     Ng_DeleteMesh( ngMesh() );
4410   _ngMesh = (netgen::Mesh*) mesh;
4411 }
4412
4413 //================================================================================
4414 /*!
4415  * \brief Perform a step of mesh generation
4416  *  \param [inout] occgeo - geometry to mesh
4417  *  \param [inout] startWith - start step
4418  *  \param [inout] endWith - end step
4419  *  \param [inout] ngMesh - netgen mesh
4420  *  \return int - is error
4421  */
4422 //================================================================================
4423
4424 int NETGENPlugin_NetgenLibWrapper::GenerateMesh( netgen::OCCGeometry& occgeo,
4425                                                  int startWith, int endWith,
4426                                                  netgen::Mesh* & ngMesh )
4427 {
4428   int err = 0;
4429 #ifdef NETGEN_V6
4430
4431   if ( !ngMesh )
4432     ngMesh = new netgen::Mesh;
4433   ngMesh->SetGeometry( shared_ptr<netgen::NetgenGeometry>( &occgeo, &NOOP_Deleter ));
4434
4435   netgen::mparam.perfstepsstart = startWith;
4436   netgen::mparam.perfstepsend   = endWith;
4437   std::shared_ptr<netgen::Mesh> meshPtr( ngMesh, &NOOP_Deleter );
4438   err = occgeo.GenerateMesh( meshPtr, netgen::mparam );
4439
4440 #else
4441   #ifdef NETGEN_V5
4442
4443   err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
4444
4445   #else
4446
4447   char *optstr = 0;
4448   err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
4449
4450   #endif
4451 #endif
4452   return err;
4453 }
4454
4455 //================================================================================
4456 /*!
4457  * \brief Create a mesh size tree
4458  */
4459 //================================================================================
4460
4461 void NETGENPlugin_NetgenLibWrapper::CalcLocalH( netgen::Mesh * ngMesh )
4462 {
4463 #if defined( NETGEN_V5 ) || defined( NETGEN_V6 )
4464   ngMesh->CalcLocalH(netgen::mparam.grading);
4465 #else
4466   ngMesh->CalcLocalH();
4467 #endif
4468 }
4469
4470 //================================================================================
4471 /*!
4472  * \brief Return a unique file name
4473  */
4474 //================================================================================
4475
4476 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
4477 {
4478   std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
4479
4480   TCollection_AsciiString aGenericName = aTmpDir.c_str();
4481   aGenericName += "NETGEN_";
4482 #ifndef WIN32
4483   aGenericName += getpid();
4484 #else
4485   aGenericName += _getpid();
4486 #endif
4487   aGenericName += "_";
4488   aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
4489   aGenericName += ".out";
4490
4491   return aGenericName.ToCString();
4492 }
4493
4494 //================================================================================
4495 /*!
4496  * \brief Remove "test.out" and "problemfaces" files in current directory
4497  */
4498 //================================================================================
4499
4500 void NETGENPlugin_NetgenLibWrapper::RemoveTmpFiles()
4501 {
4502   bool rm =  SMESH_File("test.out").remove() ;
4503 #ifndef WIN32
4504   if ( rm && netgen::testout && instanceCounter() == 0 )
4505   {
4506     delete netgen::testout;
4507     netgen::testout = 0;
4508   }
4509 #endif
4510   SMESH_File("problemfaces").remove();
4511   SMESH_File("occmesh.rep").remove();
4512 }
4513
4514 //================================================================================
4515 /*!
4516  * \brief Remove file with netgen output
4517  */
4518 //================================================================================
4519
4520 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
4521 {
4522   if ( !_outputFileName.empty() )
4523   {
4524     if ( _ngcout )
4525     {
4526       delete netgen::mycout;
4527       netgen::mycout = _ngcout;
4528       netgen::myerr  = _ngcerr;
4529       _ngcout        = 0;
4530     }
4531     string    tmpDir = SALOMEDS_Tool::GetDirFromPath ( _outputFileName );
4532     string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
4533     SALOMEDS_Tool::ListOfFiles aFiles;
4534     aFiles.reserve(1);
4535     aFiles.push_back(aFileName.c_str());
4536
4537     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles, true );
4538   }
4539 }