Salome HOME
Fix "restrict size of elements near the segment"
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_Mesher.cxx
index c6bfbd51b16ec334efb3d0cb36b9d1a197fea389..8587523843169e20778eee874950710a46fbe8b1 100644 (file)
@@ -46,6 +46,8 @@
 #include <StdMeshers_QuadToTriaAdaptor.hxx>
 #include <StdMeshers_ViscousLayers2D.hxx>
 
+#include <SALOMEDS_Tool.hxx>
+
 #include <utilities.h>
 
 #include <BRepBuilderAPI_Copy.hxx>
@@ -53,6 +55,7 @@
 #include <Bnd_B3d.hxx>
 #include <NCollection_Map.hxx>
 #include <Standard_ErrorHandler.hxx>
+#include <Standard_ProgramError.hxx>
 #include <TopExp.hxx>
 #include <TopExp_Explorer.hxx>
 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
@@ -61,6 +64,8 @@
 #include <TopTools_DataMapOfShapeShape.hxx>
 #include <TopTools_MapOfShape.hxx>
 #include <TopoDS.hxx>
+#include <OSD_File.hxx>
+#include <OSD_Path.hxx>
 
 // Netgen include files
 #ifndef OCCGEOMETRY
@@ -83,6 +88,9 @@ namespace netgen {
 #include <vector>
 #include <limits>
 
+#ifdef WIN32
+#include <process.h>
+#endif
 using namespace nglib;
 using namespace std;
 
@@ -119,7 +127,13 @@ NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh*         mesh,
     _optimize(true),
     _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
     _isViscousLayers2D(false),
-    _simpleHyp(NULL)
+    _ngMesh(NULL),
+    _occgeom(NULL),
+    _curShapeIndex(-1),
+    _progressTic(1),
+    _totalTime(1.0),
+    _simpleHyp(NULL),
+    _ptrToMe(NULL)
 {
   SetDefaultParameters();
   ShapesWithLocalSize.Clear();
@@ -128,6 +142,38 @@ NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh*         mesh,
   FaceId2LocalSize.clear();
 }
 
+//================================================================================
+/*!
+ * Destuctor
+ */
+//================================================================================
+
+NETGENPlugin_Mesher::~NETGENPlugin_Mesher()
+{
+  if ( _ptrToMe )
+    *_ptrToMe = NULL;
+  _ptrToMe = 0;
+  _ngMesh = NULL;
+}
+
+//================================================================================
+/*!
+ * Set pointer to NETGENPlugin_Mesher* field of the holder, that will be
+ * nullified at destruction of this
+ */
+//================================================================================
+
+void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr )
+{
+  if ( _ptrToMe )
+    *_ptrToMe = NULL;
+
+  _ptrToMe = ptr;
+
+  if ( _ptrToMe )
+    *_ptrToMe = this;
+}
+
 //================================================================================
 /*!
  * \brief Initialize global NETGEN parameters with default values
@@ -426,11 +472,8 @@ namespace
     //   {
     //     BRepTools::Clean (shape);
         try {
-#if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
           OCC_CATCH_SIGNALS;
-#endif
           BRepMesh_IncrementalMesh e(shape, 0.01, true);
-
         }
         catch (Standard_Failure)
         {
@@ -475,8 +518,9 @@ void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry&     occgeo,
 
   // get root submeshes
   list< SMESH_subMesh* > rootSM;
-  if ( SMESH_subMesh* sm = mesh.GetSubMeshContaining( shape )) {
-    rootSM.push_back( sm );
+  const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
+  if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
+    rootSM.push_back( mesh.GetSubMesh( shape ));
   }
   else {
     for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
@@ -1239,8 +1283,10 @@ void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry&
 #ifdef DUMP_TRIANGLES_SCRIPT
   // create a python script making a mesh containing triangles added for internal vertices
   ofstream py(DUMP_TRIANGLES_SCRIPT);
-  py << "from smesh import * "<< endl
-     << "m = Mesh(name='triangles')" << endl;
+  py << "import SMESH"<< endl
+     << "from salome.smesh import smeshBuilder"<<endl
+     << "smesh = smeshBuilder.New(salome.myStudy)"
+     << "m = smesh.Mesh(name='triangles')" << endl;
 #endif
   if ( nodeVec.size() < ngMesh.GetNP() )
     nodeVec.resize( ngMesh.GetNP(), 0 );
@@ -1619,11 +1665,14 @@ NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh&                    ngMesh,
         SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
         // get an average size of adjacent segments to avoid sharp change of
         // element size (regression on issue 0020452, note 0010898)
-        int iPrev = SMESH_MesherHelper::WrapIndex( i-1, nbSegments );
-        int iNext = SMESH_MesherHelper::WrapIndex( i+1, nbSegments );
-        double avgH = ( segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ]) / 3;
-
-        RestrictLocalSize( ngMesh, 0.5*(np1+np2), avgH );
+        int   iPrev = SMESH_MesherHelper::WrapIndex( i-1, nbSegments );
+        int   iNext = SMESH_MesherHelper::WrapIndex( i+1, nbSegments );
+        double sunH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
+        int   nbSeg = ( int( segLen[ iPrev ] > sunH / 100.)  +
+                        int( segLen[ i     ] > sunH / 100.)  +
+                        int( segLen[ iNext ] > sunH / 100.));
+        if ( nbSeg > 0 )
+          RestrictLocalSize( ngMesh, 0.5*(np1+np2), sunH / nbSeg );
       }
       if ( isInternalWire )
       {
@@ -2040,6 +2089,13 @@ namespace
     str << ": " << ex.What();
     return str;
   }
+
+  const double edgeMeshingTime = 0.001;
+  const double faceMeshingTime = 0.019;
+  const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
+  const double faceOptimizTime = 0.06;
+  const double voluMeshingTime = 0.15;
+  const double volOptimizeTime = 0.77;
 }
 
 //=============================================================================
@@ -2075,12 +2131,23 @@ bool NETGENPlugin_Mesher::Compute()
   list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
   NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
   PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
+  _occgeom = &occgeo;
+
+  _totalTime = edgeFaceMeshingTime;
+  if ( _optimize )
+    _totalTime += faceOptimizTime;
+  if ( _isVolume )
+    _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
+  double doneTime = 0;
+  _ticTime = -1;
+  _progressTic = 1;
+  _curShapeIndex = -1;
 
   // -------------------------
   // Generate the mesh
   // -------------------------
 
-  netgen::Mesh *ngMesh = NULL;
+  _ngMesh = NULL;
   NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
 
   SMESH_Comment comment;
@@ -2115,7 +2182,7 @@ bool NETGENPlugin_Mesher::Compute()
     // Local size on faces
     occgeo.face_maxh = mparams.maxh;
 
-    // Let netgen create ngMesh and calculate element size on not meshed shapes
+    // Let netgen create _ngMesh and calculate element size on not meshed shapes
 #ifndef NETGEN_V5
     char *optstr = 0;
 #endif
@@ -2125,14 +2192,13 @@ bool NETGENPlugin_Mesher::Compute()
     {
       OCC_CATCH_SIGNALS;
 #ifdef NETGEN_V5
-      err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
+      err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
 #else
-      err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
+      err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
 #endif
-#ifdef WITH_SMESH_CANCEL_COMPUTE
       if(netgen::multithread.terminate)
         return false;
-#endif
+
       comment << text(err);
     }
     catch (Standard_Failure& ex)
@@ -2140,11 +2206,11 @@ bool NETGENPlugin_Mesher::Compute()
       comment << text(ex);
     }
     err = 0; //- MESHCONST_ANALYSE isn't so important step
-    if ( !ngMesh )
+    if ( !_ngMesh )
       return false;
-    ngLib.setMesh(( Ng_Mesh*) ngMesh );
+    ngLib.setMesh(( Ng_Mesh*) _ngMesh );
 
-    ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
+    _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
 
     if ( _simpleHyp )
     {
@@ -2157,7 +2223,7 @@ bool NETGENPlugin_Mesher::Compute()
         const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
         if ( nbSeg )
           segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
-        setLocalSize( e, segSize, *ngMesh );
+        setLocalSize( e, segSize, *_ngMesh );
       }
     }
     else // if ( ! _simpleHyp )
@@ -2170,7 +2236,7 @@ bool NETGENPlugin_Mesher::Compute()
         double hi = (*it).second;
         const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
         const TopoDS_Edge& e = TopoDS::Edge(shape);
-        setLocalSize( e, hi, *ngMesh );
+        setLocalSize( e, hi, *_ngMesh );
       }
       for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
       {
@@ -2179,7 +2245,7 @@ bool NETGENPlugin_Mesher::Compute()
         const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
         const TopoDS_Vertex& v = TopoDS::Vertex(shape);
         gp_Pnt p = BRep_Tool::Pnt(v);
-        NETGENPlugin_Mesher::RestrictLocalSize( *ngMesh, p.XYZ(), hi );
+        NETGENPlugin_Mesher::RestrictLocalSize( *_ngMesh, p.XYZ(), hi );
       }
       for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
           it!=FaceId2LocalSize.end(); it++)
@@ -2190,7 +2256,7 @@ bool NETGENPlugin_Mesher::Compute()
         int faceNgID = occgeo.fmap.FindIndex(shape);
         occgeo.SetFaceMaxH(faceNgID, val);
         for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
-          setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *ngMesh );
+          setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *_ngMesh );
       }
     }
 
@@ -2210,7 +2276,7 @@ bool NETGENPlugin_Mesher::Compute()
       {
         OCC_CATCH_SIGNALS;
         // compute local H on internal shapes in the main mesh
-        //OCCSetLocalMeshSize(intOccgeo, *ngMesh); it deletes ngMesh->localH
+        //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
 
         // let netgen create a temporary mesh
 #ifdef NETGEN_V5
@@ -2218,12 +2284,11 @@ bool NETGENPlugin_Mesher::Compute()
 #else
         netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
 #endif
-#ifdef WITH_SMESH_CANCEL_COMPUTE
         if(netgen::multithread.terminate)
           return false;
-#endif
+
         // copy LocalH from the main to temporary mesh
-        initState.transferLocalH( ngMesh, tmpNgMesh );
+        initState.transferLocalH( _ngMesh, tmpNgMesh );
 
         // compute mesh on internal edges
         startWith = endWith = netgen::MESHCONST_MESHEDGES;
@@ -2249,13 +2314,13 @@ bool NETGENPlugin_Mesher::Compute()
       nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
     }
 
-    // Fill ngMesh with nodes and segments of computed submeshes
+    // Fill _ngMesh with nodes and segments of computed submeshes
     if ( !err )
     {
-      err = ! ( FillNgMesh(occgeo, *ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
-                FillNgMesh(occgeo, *ngMesh, nodeVec, meshedSM[ MeshDim_1D ]));
+      err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
+                FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ]));
     }
-    initState = NETGENPlugin_ngMeshInfo(ngMesh);
+    initState = NETGENPlugin_ngMeshInfo(_ngMesh);
 
     // Compute 1d mesh
     if (!err)
@@ -2265,14 +2330,13 @@ bool NETGENPlugin_Mesher::Compute()
       {
         OCC_CATCH_SIGNALS;
 #ifdef NETGEN_V5
-        err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
+        err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
 #else
-        err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
+        err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
 #endif
-#ifdef WITH_SMESH_CANCEL_COMPUTE
         if(netgen::multithread.terminate)
           return false;
-#endif
+
         comment << text(err);
       }
       catch (Standard_Failure& ex)
@@ -2281,6 +2345,9 @@ bool NETGENPlugin_Mesher::Compute()
         err = 1;
       }
     }
+    if ( _isVolume )
+      _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
+
     mparams.uselocalh = true; // restore as it is used at surface optimization
 
     // ---------------------
@@ -2297,7 +2364,7 @@ bool NETGENPlugin_Mesher::Compute()
         }
         else {
           // length from edges
-          if ( ngMesh->GetNSeg() ) {
+          if ( _ngMesh->GetNSeg() ) {
             double edgeLength = 0;
             TopTools_MapOfShape visitedEdges;
             for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
@@ -2305,8 +2372,8 @@ bool NETGENPlugin_Mesher::Compute()
                 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
             // we have to multiply length by 2 since for each TopoDS_Edge there
             // are double set of NETGEN edges, in other words, we have to
-            // divide ngMesh->GetNSeg() by 2.
-            mparams.maxh = 2*edgeLength / ngMesh->GetNSeg();
+            // divide _ngMesh->GetNSeg() by 2.
+            mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
           }
           else {
             mparams.maxh = 1000;
@@ -2315,10 +2382,10 @@ bool NETGENPlugin_Mesher::Compute()
         }
         mparams.quad = _simpleHyp->GetAllowQuadrangles();
         mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
-        ngMesh->SetGlobalH (mparams.maxh);
+        _ngMesh->SetGlobalH (mparams.maxh);
         netgen::Box<3> bb = occgeo.GetBoundingBox();
         bb.Increase (bb.Diam()/20);
-        ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
+        _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
       }
 
       // Care of vertices internal in faces (issue 0020676)
@@ -2326,18 +2393,18 @@ bool NETGENPlugin_Mesher::Compute()
       {
         // store computed segments in SMESH in order not to create SMESH
         // edges for ng segments added by AddIntVerticesInFaces()
-        FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
+        FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
         // add segments to faces with internal vertices
-        AddIntVerticesInFaces( occgeo, *ngMesh, nodeVec, internals );
-        initState = NETGENPlugin_ngMeshInfo(ngMesh);
+        AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
+        initState = NETGENPlugin_ngMeshInfo(_ngMesh);
       }
 
       // Build viscous layers
       if ( _isViscousLayers2D )
       {
         if ( !internals.hasInternalVertexInFace() ) {
-          FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
-          initState = NETGENPlugin_ngMeshInfo(ngMesh);
+          FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
+          initState = NETGENPlugin_ngMeshInfo(_ngMesh);
         }
         SMESH_ProxyMesh::Ptr viscousMesh;
         SMESH_MesherHelper   helper( *_mesh );
@@ -2348,22 +2415,22 @@ bool NETGENPlugin_Mesher::Compute()
           if ( !viscousMesh )
             return false;
           // exclude from computation ng segments built on EDGEs of F
-          for (int i = 1; i <= ngMesh->GetNSeg(); i++)
+          for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
           {
-            netgen::Segment & seg = ngMesh->LineSegment(i);
+            netgen::Segment & seg = _ngMesh->LineSegment(i);
             if (seg.si == faceID)
               seg.si = 0;
           }
-          // add new segments to ngMesh instead of excluded ones
+          // add new segments to _ngMesh instead of excluded ones
           helper.SetSubShape( F );
           TSideVector wires =
             StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
                                                error, viscousMesh );
-          error = AddSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
+          error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
 
           if ( !error ) error = SMESH_ComputeError::New();
         }
-        initState = NETGENPlugin_ngMeshInfo(ngMesh);
+        initState = NETGENPlugin_ngMeshInfo(_ngMesh);
       }
 
       // Let netgen compute 2D mesh
@@ -2373,14 +2440,13 @@ bool NETGENPlugin_Mesher::Compute()
       {
         OCC_CATCH_SIGNALS;
 #ifdef NETGEN_V5
-        err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
+        err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
 #else
-        err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
+        err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
 #endif
-#ifdef WITH_SMESH_CANCEL_COMPUTE
         if(netgen::multithread.terminate)
           return false;
-#endif
+
         comment << text (err);
       }
       catch (Standard_Failure& ex)
@@ -2394,14 +2460,19 @@ bool NETGENPlugin_Mesher::Compute()
         //err = 1; -- try to make volumes anyway
       }
     }
+    if ( _isVolume )
+    {
+      doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
+      _ticTime = doneTime / _totalTime / _progressTic;
+    }
     // ---------------------
     // generate volume mesh
     // ---------------------
-    // Fill ngMesh with nodes and faces of computed 2D submeshes
+    // Fill _ngMesh with nodes and faces of computed 2D submeshes
     if ( !err && _isVolume && ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad ))
     {
       // load SMESH with computed segments and faces
-      FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
+      FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
 
       // compute pyramids on quadrangles
       SMESH_ProxyMesh::Ptr proxyMesh;
@@ -2422,13 +2493,13 @@ bool NETGENPlugin_Mesher::Compute()
                 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
                 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
               }
-            FillNgMesh(occgeo, *ngMesh, nodeVec, quadFaceSM, proxyMesh);
+            FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, proxyMesh);
           }
         }
-      // fill ngMesh with faces of sub-meshes
-      err = ! ( FillNgMesh(occgeo, *ngMesh, nodeVec, meshedSM[ MeshDim_2D ]));
-      initState = NETGENPlugin_ngMeshInfo(ngMesh);
-      //toPython( ngMesh, "/tmp/ngPython.py");
+      // fill _ngMesh with faces of sub-meshes
+      err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ]));
+      initState = NETGENPlugin_ngMeshInfo(_ngMesh);
+      //toPython( _ngMesh, "/tmp/ngPython.py");
     }
     if (!err && _isVolume)
     {
@@ -2443,14 +2514,14 @@ bool NETGENPlugin_Mesher::Compute()
         }
         else {
           // length from faces
-          mparams.maxh = ngMesh->AverageH();
+          mparams.maxh = _ngMesh->AverageH();
         }
-        ngMesh->SetGlobalH (mparams.maxh);
+        _ngMesh->SetGlobalH (mparams.maxh);
         mparams.grading = 0.4;
 #ifdef NETGEN_V5
-        ngMesh->CalcLocalH(mparams.grading);
+        _ngMesh->CalcLocalH(mparams.grading);
 #else
-        ngMesh->CalcLocalH();
+        _ngMesh->CalcLocalH();
 #endif
       }
       // Care of vertices internal in solids and internal faces (issue 0020676)
@@ -2458,12 +2529,12 @@ bool NETGENPlugin_Mesher::Compute()
       {
         // store computed faces in SMESH in order not to create SMESH
         // faces for ng faces added here
-        FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
+        FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
         // add ng faces to solids with internal vertices
-        AddIntVerticesInSolids( occgeo, *ngMesh, nodeVec, internals );
+        AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
         // duplicate mesh faces on internal faces
-        FixIntFaces( occgeo, *ngMesh, internals );
-        initState = NETGENPlugin_ngMeshInfo(ngMesh);
+        FixIntFaces( occgeo, *_ngMesh, internals );
+        initState = NETGENPlugin_ngMeshInfo(_ngMesh);
       }
       // Let netgen compute 3D mesh
       startWith = endWith = netgen::MESHCONST_MESHVOLUME;
@@ -2471,14 +2542,13 @@ bool NETGENPlugin_Mesher::Compute()
       {
         OCC_CATCH_SIGNALS;
 #ifdef NETGEN_V5
-        err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
+        err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
 #else
-        err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
+        err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
 #endif
-#ifdef WITH_SMESH_CANCEL_COMPUTE
         if(netgen::multithread.terminate)
           return false;
-#endif
+
         if ( comment.empty() ) // do not overwrite a previos error
           comment << text(err);
       }
@@ -2494,6 +2564,8 @@ bool NETGENPlugin_Mesher::Compute()
           comment << text(exc);
         err = 1;
       }
+      _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
+
       // Let netgen optimize 3D mesh
       if ( !err && _optimize )
       {
@@ -2502,14 +2574,13 @@ bool NETGENPlugin_Mesher::Compute()
         {
           OCC_CATCH_SIGNALS;
 #ifdef NETGEN_V5
-          err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
+          err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
 #else
-          err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
+          err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
 #endif
-#ifdef WITH_SMESH_CANCEL_COMPUTE
           if(netgen::multithread.terminate)
             return false;
-#endif
+
           if ( comment.empty() ) // do not overwrite a previos error
             comment << text(err);
         }
@@ -2531,7 +2602,7 @@ bool NETGENPlugin_Mesher::Compute()
       {
         OCC_CATCH_SIGNALS;
         netgen::OCCRefinementSurfaces ref (occgeo);
-        ref.MakeSecondOrder (*ngMesh);
+        ref.MakeSecondOrder (*_ngMesh);
       }
       catch (Standard_Failure& ex)
       {
@@ -2545,10 +2616,13 @@ bool NETGENPlugin_Mesher::Compute()
       }
     }
   }
-  int nbNod = ngMesh->GetNP();
-  int nbSeg = ngMesh->GetNSeg();
-  int nbFac = ngMesh->GetNSE();
-  int nbVol = ngMesh->GetNE();
+
+  _ticTime = 0.98 / _progressTic;
+
+  int nbNod = _ngMesh->GetNP();
+  int nbSeg = _ngMesh->GetNSeg();
+  int nbFac = _ngMesh->GetNSE();
+  int nbVol = _ngMesh->GetNE();
   bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
 
   MESSAGE((err ? "Mesh Generation failure" : "End of Mesh Generation") <<
@@ -2559,7 +2633,7 @@ bool NETGENPlugin_Mesher::Compute()
 
   // Feed back the SMESHDS with the generated Nodes and Elements
   if ( true /*isOK*/ ) // get whatever built
-    FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment ); //!< 
+    FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment ); //!< 
 
   SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
   if ( readErr && !readErr->myBadElements.empty() )
@@ -2626,6 +2700,8 @@ bool NETGENPlugin_Mesher::Compute()
       err = 0; // no fatal errors, only warnings
   }
 
+  ngLib._isComputeOk = !err;
+
   return !err;
 }
 
@@ -2673,7 +2749,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
   if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
     mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
 
-  // let netgen create ngMesh and calculate element size on not meshed shapes
+  // let netgen create _ngMesh and calculate element size on not meshed shapes
   NETGENPlugin_NetgenLibWrapper ngLib;
   netgen::Mesh *ngMesh = NULL;
 #ifndef NETGEN_V5
@@ -2686,10 +2762,10 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
 #else
   int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
 #endif
-#ifdef WITH_SMESH_CANCEL_COMPUTE
+
   if(netgen::multithread.terminate)
     return false;
-#endif
+
   ngLib.setMesh(( Ng_Mesh*) ngMesh );
   if (err) {
     if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
@@ -2892,6 +2968,68 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
   return true;
 }
 
+double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder,
+                                        const int *       algoProgressTic,
+                                        const double *    algoProgress) const
+{
+  ((int&) _progressTic ) = *algoProgressTic + 1;
+
+  if ( !_occgeom ) return 0;
+
+  double progress = -1;
+  if ( !_isVolume )
+  {
+    if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
+    {
+      ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
+    }
+    else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
+    {
+      int doneShapeIndex = -1;
+      while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
+              _occgeom->facemeshstatus[ doneShapeIndex+1 ])
+        doneShapeIndex++;
+      if ( doneShapeIndex+1 != _curShapeIndex )
+      {
+        ((int&) _curShapeIndex) = doneShapeIndex+1;
+        double    doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
+        double         doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
+        ((double&)    _ticTime) = doneTime / _totalTime / _progressTic;
+        // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
+        //      << " " << doneTime / _totalTime / _progressTic << endl;
+      }
+    }
+  }
+  else if ( !_optimize && _occgeom->somap.Extent() > 1 )
+  {
+    int curShapeIndex = _curShapeIndex;
+    if ( _ngMesh->GetNE() > 0 )
+    {
+      netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
+      curShapeIndex = el.GetIndex();
+    }
+    if ( curShapeIndex != _curShapeIndex )
+    {
+      ((int&) _curShapeIndex) = curShapeIndex;
+      double    doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
+      double         doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
+      ((double&)    _ticTime) = doneTime / _totalTime / _progressTic;
+      // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
+      //      << " " << doneTime / _totalTime / _progressTic << endl;
+    }
+  }
+  if ( _ticTime > 0 )
+    progress  = Max( *algoProgressTic * _ticTime, *algoProgress );
+  if ( progress > 0 )
+  {
+    ((int&) *algoProgressTic )++;
+    ((double&) *algoProgress) = progress;
+  }
+  //cout << progress << " "  << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
+
+  return Min( progress, 0.99 );
+}
+
 //================================================================================
 /*!
  * \brief Remove "test.out" and "problemfaces" files in current directory
@@ -2900,11 +3038,14 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
 
 void NETGENPlugin_Mesher::RemoveTmpFiles()
 {
-  if ( SMESH_File("test.out").remove() && netgen::testout)
+  bool rm =  SMESH_File("test.out").remove() ;
+#ifndef WIN32
+  if (rm && netgen::testout)
   {
     delete netgen::testout;
     netgen::testout = 0;
   }
+#endif
   SMESH_File("problemfaces").remove();
   SMESH_File("occmesh.rep").remove();
 }
@@ -2988,7 +3129,9 @@ void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
   ofstream outfile(pyFile.c_str(), ios::out);
   if ( !outfile ) return;
 
-  outfile << "import smesh, SMESH" << endl
+  outfile << "import SMESH" << endl
+          << "from salome.smesh import smeshBuilder" << endl
+          << "smesh = smeshBuilder.New(salome.myStudy)" << endl
           << "mesh = smesh.Mesh()" << endl << endl;
 
   using namespace netgen;
@@ -3458,6 +3601,18 @@ SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
 {
   Ng_Init();
+
+  // redirect all netgen output (mycout,myerr,cout) to _outputFileName
+  _isComputeOk    = false;
+  _outputFileName = getOutputFileName();
+  netgen::mycout  = new ofstream ( _outputFileName.c_str() );
+  netgen::myerr   = netgen::mycout;
+  _coutBuffer     = std::cout.rdbuf();
+#ifdef _DEBUG_
+  cout << "NOTE: netgen output is redirected to file " << _outputFileName << endl;
+#endif
+  std::cout.rdbuf( netgen::mycout->rdbuf() );
+
   _ngMesh = Ng_NewMesh();
 }
 
@@ -3472,6 +3627,11 @@ NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
   Ng_DeleteMesh( _ngMesh );
   Ng_Exit();
   NETGENPlugin_Mesher::RemoveTmpFiles();
+  std::cout.rdbuf( _coutBuffer );
+#ifdef _DEBUG_
+  if( _isComputeOk )
+#endif
+    removeOutputFile();
 }
 
 //================================================================================
@@ -3486,3 +3646,53 @@ void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
     Ng_DeleteMesh( _ngMesh );
   _ngMesh = mesh;
 }
+
+//================================================================================
+/*!
+ * \brief Return a unique file name
+ */
+//================================================================================
+
+std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
+{
+  std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
+
+  TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
+  aGenericName += "NETGEN_";
+#ifndef WIN32
+  aGenericName += getpid();
+#else
+  aGenericName += _getpid();
+#endif
+  aGenericName += "_";
+  aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
+  aGenericName += ".out";
+
+  return aGenericName.ToCString();
+}
+
+//================================================================================
+/*!
+ * \brief Remove file with netgen output
+ */
+//================================================================================
+
+void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
+{
+  string tmpDir = SALOMEDS_Tool::GetDirFromPath( _outputFileName );
+  SALOMEDS::ListOfFileNames_var aFiles = new SALOMEDS::ListOfFileNames;
+  aFiles->length(1);
+  std::string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
+  aFiles[0] = aFileName.c_str();
+  if ( netgen::mycout)
+  {
+    delete netgen::mycout;
+    netgen::mycout = 0;
+    netgen::myerr = 0;
+  }
+  
+  SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles.in(), true );
+#ifdef _DEBUG_
+  //cout << "NOTE: netgen output log was REMOVED       " << _outputFileName << endl;
+#endif
+}