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