Salome HOME
Merge V9_dev branch into master
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_2D_ONLY.cxx
index acb11d6dae5ee78158b471a0625586332c891041..59baa3eb9b80b6e95b8b24c9b3a3728db415d981 100644 (file)
@@ -1,9 +1,9 @@
-// Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
+// Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
 //
 // This library is free software; you can redistribute it and/or
 // modify it under the terms of the GNU Lesser General Public
 // License as published by the Free Software Foundation; either
-// version 2.1 of the License.
+// version 2.1 of the License, or (at your option) any later version.
 //
 // This library is distributed in the hope that it will be useful,
 // but WITHOUT ANY WARRANTY; without even the implied warranty of
 #include "NETGENPlugin_Mesher.hxx"
 #include "NETGENPlugin_Hypothesis_2D.hxx"
 
-#include "SMDS_MeshElement.hxx"
-#include "SMDS_MeshNode.hxx"
-#include "SMESHDS_Mesh.hxx"
-#include "SMESH_Comment.hxx"
-#include "SMESH_Gen.hxx"
-#include "SMESH_Mesh.hxx"
-#include "SMESH_MesherHelper.hxx"
-#include "StdMeshers_FaceSide.hxx"
-#include "StdMeshers_MaxElementArea.hxx"
-#include "StdMeshers_LengthFromEdges.hxx"
-#include "StdMeshers_QuadranglePreference.hxx"
+#include <SMDS_MeshElement.hxx>
+#include <SMDS_MeshNode.hxx>
+#include <SMESHDS_Mesh.hxx>
+#include <SMESH_Comment.hxx>
+#include <SMESH_Gen.hxx>
+#include <SMESH_Mesh.hxx>
+#include <SMESH_MesherHelper.hxx>
+#include <SMESH_subMesh.hxx>
+#include <StdMeshers_FaceSide.hxx>
+#include <StdMeshers_LengthFromEdges.hxx>
+#include <StdMeshers_MaxElementArea.hxx>
+#include <StdMeshers_QuadranglePreference.hxx>
+#include <StdMeshers_ViscousLayers2D.hxx>
 
 #include <Precision.hxx>
 #include <Standard_ErrorHandler.hxx>
 #include <Standard_Failure.hxx>
 
-#include "utilities.h"
+#include <utilities.h>
 
 #include <list>
 #include <vector>
@@ -61,40 +63,47 @@ namespace nglib {
 #include <meshing.hpp>
 //#include <meshtype.hpp>
 namespace netgen {
+#ifdef NETGEN_V5
+  extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, MeshingParameters&, int, int);
+#else
   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
+#endif
+#if defined(NETGEN_V5) && defined(WIN32)
+  DLL_HEADER 
+#endif
   extern MeshingParameters mparam;
+  extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
 }
 
 using namespace std;
 using namespace netgen;
 using namespace nglib;
 
-//#define DUMP_SEGMENTS
-
 //=============================================================================
 /*!
  *  
  */
 //=============================================================================
 
-NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int hypId, int studyId,
+NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int        hypId,
                                                          SMESH_Gen* gen)
-  : SMESH_2D_Algo(hypId, studyId, gen)
+  : SMESH_2D_Algo(hypId, gen)
 {
-  MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY");
   _name = "NETGEN_2D_ONLY";
   
   _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
+  _onlyUnaryInput = false; // treat all FACEs at once
 
   _compatibleHypothesis.push_back("MaxElementArea");
   _compatibleHypothesis.push_back("LengthFromEdges");
   _compatibleHypothesis.push_back("QuadranglePreference");
   _compatibleHypothesis.push_back("NETGEN_Parameters_2D");
+  _compatibleHypothesis.push_back("ViscousLayers2D");
 
-  _hypMaxElementArea = 0;
-  _hypLengthFromEdges = 0;
+  _hypMaxElementArea       = 0;
+  _hypLengthFromEdges      = 0;
   _hypQuadranglePreference = 0;
-  _hypParameters = 0;
+  _hypParameters           = 0;
 }
 
 //=============================================================================
@@ -105,7 +114,7 @@ NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int hypId, int studyId,
 
 NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY()
 {
-  MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
+  //MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
 }
 
 //=============================================================================
@@ -121,6 +130,8 @@ bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh&         aMesh,
   _hypMaxElementArea = 0;
   _hypLengthFromEdges = 0;
   _hypQuadranglePreference = 0;
+  _hypParameters = 0;
+  _progressByTic = -1;
 
   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
 
@@ -132,6 +143,7 @@ bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh&         aMesh,
 
   aStatus = HYP_MISSING;
 
+  bool hasVL = false;
   list<const SMESHDS_Hypothesis*>::const_iterator ith;
   for (ith = hyps.begin(); ith != hyps.end(); ++ith )
   {
@@ -147,6 +159,8 @@ bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh&         aMesh,
       _hypQuadranglePreference = static_cast<const StdMeshers_QuadranglePreference*>(hyp);
     else if ( hypName == "NETGEN_Parameters_2D" )
       _hypParameters = static_cast<const NETGENPlugin_Hypothesis_2D*>(hyp);
+    else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
+      hasVL = true;
     else {
       aStatus = HYP_INCOMPATIBLE;
       return false;
@@ -155,414 +169,473 @@ bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh&         aMesh,
 
   int nbHyps = bool(_hypMaxElementArea) + bool(_hypLengthFromEdges) + bool(_hypParameters );
   if ( nbHyps > 1 )
-    aStatus = HYP_CONCURENT;
-  else if ( nbHyps == 1)
+    aStatus = HYP_CONCURRENT;
+  else if ( hasVL )
+    error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus ));
+  else
     aStatus = HYP_OK;
 
+  if ( aStatus == HYP_OK && _hypParameters && _hypQuadranglePreference )
+  {
+    aStatus = HYP_INCOMPAT_HYPS;
+    return error(SMESH_Comment("\"") << _hypQuadranglePreference->GetName()
+                 << "\" and \"" << _hypParameters->GetName()
+                 << "\" are incompatible hypotheses");
+  }
+
   return ( aStatus == HYP_OK );
 }
 
-//================================================================================
+// namespace
+// {
+//   void limitSize( netgen::Mesh* ngMesh,
+//                   const double  maxh )
+//   {
+//     // get bnd box
+//     netgen::Point3d pmin, pmax;
+//     ngMesh->GetBox( pmin, pmax, 0 );
+//     const double dx = pmax.X() - pmin.X();
+//     const double dy = pmax.Y() - pmin.Y();
+//     const double dz = pmax.Z() - pmin.Z();
+
+//     const int nbX = Max( 2, int( dx / maxh * 3 ));
+//     const int nbY = Max( 2, int( dy / maxh * 3 ));
+//     const int nbZ = Max( 2, int( dz / maxh * 3 ));
+
+//     if ( ! & ngMesh->LocalHFunction() )
+//       ngMesh->SetLocalH( pmin, pmax, 0.1 );
+
+//     netgen::Point3d p;
+//     for ( int i = 0; i <= nbX; ++i )
+//     {
+//       p.X() = pmin.X() +  i * dx / nbX;
+//       for ( int j = 0; j <= nbY; ++j )
+//       {
+//         p.Y() = pmin.Y() +  j * dy / nbY;
+//         for ( int k = 0; k <= nbZ; ++k )
+//         {
+//           p.Z() = pmin.Z() +  k * dz / nbZ;
+//           ngMesh->RestrictLocalH( p, maxh );
+//         }
+//       }
+//     }
+//   }
+// }
+
+//=============================================================================
 /*!
- * \brief Fill netgen mesh with segments
-  * \retval SMESH_ComputeErrorPtr - error description
+ *Here we are going to use the NETGEN mesher
  */
-//================================================================================
+//=============================================================================
 
-static TError addSegmentsToMesh(netgen::Mesh&                    ngMesh,
-                                OCCGeometry&                     geom,
-                                const TSideVector&               wires,
-                                SMESH_MesherHelper&              helper,
-                                vector< const SMDS_MeshNode* > & nodeVec)
+bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
+                                          const TopoDS_Shape& aShape)
 {
-  // ----------------------------
-  // Check wires and count nodes
-  // ----------------------------
-  int nbNodes = 0;
-  double totalLength = 0;
-  for ( int iW = 0; iW < wires.size(); ++iW )
-  {
-    StdMeshers_FaceSidePtr wire = wires[ iW ];
-    if ( wire->MissVertexNode() )
-    {
-      // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
-      // It seems that there is no reason for this limitation
-//       return TError
-//         (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
-      if (getenv("USER") && string("eap")==getenv("USER"))
-        cout << "Warning: NETGENPlugin_NETGEN_2D_ONLY : try to work with missing nodes on vertices"<<endl;
-    }
-    const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
-    if ( uvPtVec.size() != wire->NbPoints() )
-      return TError
-        (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,
-                                SMESH_Comment("Unexpected nb of points on wire ") << iW
-                                << ": " << uvPtVec.size()<<" != "<<wire->NbPoints()));
-    nbNodes += wire->NbPoints();
-    totalLength += wire->Length();
-  }
-  nodeVec.reserve( nbNodes );
+  netgen::multithread.terminate = 0;
+  //netgen::multithread.task = "Surface meshing";
 
-  // -----------------
-  // Fill netgen mesh
-  // -----------------
+  SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
+  SMESH_MesherHelper helper(aMesh);
+  helper.SetElementsOnShape( true );
 
-//   netgen::Box<3> bb = geom.GetBoundingBox();
-//   bb.Increase (bb.Diam()/10);
-//   ngMesh.SetLocalH (bb.PMin(), bb.PMax(), 0.5); // set grading
+  NETGENPlugin_NetgenLibWrapper ngLib;
+  ngLib._isComputeOk = false;
+
+  netgen::Mesh   ngMeshNoLocSize;
+  netgen::Mesh * ngMeshes[2] = { (netgen::Mesh*) ngLib._ngMesh,  & ngMeshNoLocSize };
+  netgen::OCCGeometry occgeoComm;
+
+  // min / max sizes are set as follows:
+  // if ( _hypParameters )
+  //    min and max are defined by the user
+  // else if ( _hypLengthFromEdges )
+  //    min = aMesher.GetDefaultMinSize()
+  //    max = average segment len of a FACE
+  // else if ( _hypMaxElementArea )
+  //    min = aMesher.GetDefaultMinSize()
+  //    max = f( _hypMaxElementArea )
+  // else
+  //    min = aMesher.GetDefaultMinSize()
+  //    max = max segment len of a FACE
 
-  // map for nodes on vertices since they can be shared between wires
-  // ( issue 0020676, face_int_box.brep)
-  map<const SMDS_MeshNode*, int > node2ngID;
+  NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
+  aMesher.SetParameters( _hypParameters ); // _hypParameters -> netgen::mparam
+  const bool toOptimize = _hypParameters ? _hypParameters->GetOptimize() : true;
+  if ( _hypMaxElementArea )
+  {
+    netgen::mparam.maxh = sqrt( 2. * _hypMaxElementArea->GetMaxArea() / sqrt(3.0) );
+  }
+  if ( _hypQuadranglePreference )
+    netgen::mparam.quad = true;
 
-  const int faceID = 1, solidID = 0;
-  if ( ngMesh.GetNFD() < 1 )
-    ngMesh.AddFaceDescriptor (FaceDescriptor(faceID, solidID, solidID, 0));
+  // local size is common for all FACEs in aShape?
+  const bool isCommonLocalSize = ( !_hypLengthFromEdges && !_hypMaxElementArea && netgen::mparam.uselocalh );
+  const bool isDefaultHyp = ( !_hypLengthFromEdges && !_hypMaxElementArea && !_hypParameters );
 
-  for ( int iW = 0; iW < wires.size(); ++iW )
+  if ( isCommonLocalSize ) // compute common local size in ngMeshes[0]
   {
-    StdMeshers_FaceSidePtr wire = wires[ iW ];
-    const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
-    const int nbSegments = wire->NbPoints() - 1;
-
-    // compute length of every segment
-    vector<double> segLen( nbSegments );
-    for ( int i = 0; i < nbSegments; ++i )
-      segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
-
-    int edgeID = 1, posID = -2;
-    bool isInternalWire = false;
-    for ( int i = 0; i < nbSegments; ++i ) // loop on segments
+    //list< SMESH_subMesh* > meshedSM[4]; --> all sub-shapes are added to occgeoComm
+    aMesher.PrepareOCCgeometry( occgeoComm, aShape, aMesh );//, meshedSM );
+
+    // local size set at MESHCONST_ANALYSE step depends on
+    // minh, face_maxh, grading and curvaturesafety; find minh if not set by the user
+    if ( !_hypParameters || netgen::mparam.minh < DBL_MIN )
     {
-      // Add the first point of a segment
-      const SMDS_MeshNode * n = uvPtVec[ i ].node;
-      const int posShapeID = n->getshapeId();
-      bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
-
-      // skip nodes on degenerated edges
-      if ( helper.IsDegenShape( posShapeID ) &&
-           helper.IsDegenShape( uvPtVec[ i+1 ].node->getshapeId() ))
+      if ( !_hypParameters )
+        netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam() / 3.;
+      netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
+    }
+    // set local size depending on curvature and NOT closeness of EDGEs
+    netgen::occparam.resthcloseedgeenable = false;
+    //netgen::occparam.resthcloseedgefac = 1.0 + netgen::mparam.grading;
+    occgeoComm.face_maxh = netgen::mparam.maxh;
+    netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0] );
+    occgeoComm.emap.Clear();
+    occgeoComm.vmap.Clear();
+
+    // set local size according to size of existing segments
+    const double factor = netgen::occparam.resthcloseedgefac;
+    TopTools_IndexedMapOfShape edgeMap;
+    TopExp::MapShapes( aMesh.GetShapeToMesh(), TopAbs_EDGE, edgeMap );
+    for ( int iE = 1; iE <= edgeMap.Extent(); ++iE )
+    {
+      const TopoDS_Shape& edge = edgeMap( iE );
+      if ( SMESH_Algo::isDegenerated( TopoDS::Edge( edge )))
         continue;
-
-      int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
-      if ( onVertex )
-        ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
-      if ( ngID1 > ngMesh.GetNP() )
-      {
-        MeshPoint mp( Point<3> (n->X(), n->Y(), n->Z()) );
-        ngMesh.AddPoint ( mp, 1, EDGEPOINT );
-        nodeVec.push_back( n );
-      }
-      else
+      SMESHDS_SubMesh* smDS = meshDS->MeshElements( edge );
+      if ( !smDS ) continue;
+      SMDS_ElemIteratorPtr segIt = smDS->GetElements();
+      while ( segIt->more() )
       {
-        ngID2 = ngMesh.GetNP() + 1;
-        if ( i > 0 ) // prev segment belongs to same wire
-        {
-          Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
-          prevSeg[1] = ngID1;
-        }
+        const SMDS_MeshElement* seg = segIt->next();
+        SMESH_TNodeXYZ n1 = seg->GetNode(0);
+        SMESH_TNodeXYZ n2 = seg->GetNode(1);
+        gp_XYZ p = 0.5 * ( n1 + n2 );
+        netgen::Point3d pi(p.X(), p.Y(), p.Z());
+        ngMeshes[0]->RestrictLocalH( pi, factor * ( n1 - n2 ).Modulus() );
       }
+    }
 
-      // Add the segment
-      Segment seg;
+    // set local size defined on shapes
+    aMesher.SetLocalSize( occgeoComm, *ngMeshes[0] );
+    aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMeshes[0] );
+    try {
+      ngMeshes[0]->LoadLocalMeshSize( mparam.meshsizefilename );
+    } catch (NgException & ex) {
+      return error( COMPERR_BAD_PARMETERS, ex.What() );
+    }
+  }
+  netgen::mparam.uselocalh = toOptimize; // restore as it is used at surface optimization
 
-      seg[0] = ngID1;  // ng node id
-      seg[1] = ngID2;  // ng node id
+  // ==================
+  // Loop on all FACEs
+  // ==================
 
-      seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
-      seg.si = faceID;                  // = geom.fmap.FindIndex (face);
+  vector< const SMDS_MeshNode* > nodeVec;
 
-      for ( int iEnd = 0; iEnd < 2; ++iEnd)
-      {
-        const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
+  TopExp_Explorer fExp( aShape, TopAbs_FACE );
+  for ( int iF = 0; fExp.More(); fExp.Next(), ++iF )
+  {
+    TopoDS_Face F = TopoDS::Face( fExp.Current() /*.Oriented( TopAbs_FORWARD )*/);
+    int    faceID = meshDS->ShapeToIndex( F );
+    SMESH_ComputeErrorPtr& faceErr = aMesh.GetSubMesh( F )->GetComputeError();
+
+    _quadraticMesh = helper.IsQuadraticSubMesh( F );
+    const bool ignoreMediumNodes = _quadraticMesh;
+
+    // build viscous layers if required
+    if ( F.Orientation() != TopAbs_FORWARD &&
+         F.Orientation() != TopAbs_REVERSED )
+      F.Orientation( TopAbs_FORWARD ); // avoid pb with TopAbs_INTERNAL
+    SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
+    if ( !proxyMesh )
+      continue;
 
-        seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
-        seg.epgeominfo[ iEnd ].u    = pnt.u;
-        seg.epgeominfo[ iEnd ].v    = pnt.v;
+    // ------------------------
+    // get all EDGEs of a FACE
+    // ------------------------
+    TSideVector wires =
+      StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, faceErr, &helper, proxyMesh );
+    if ( faceErr && !faceErr->IsOK() )
+      continue;
+    int nbWires = wires.size();
+    if ( nbWires == 0 )
+    {
+      faceErr.reset
+        ( new SMESH_ComputeError
+          ( COMPERR_ALGO_FAILED, "Problem in StdMeshers_FaceSide::GetFaceWires()" ));
+      continue;
+    }
+    if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
+    {
+      faceErr.reset
+        ( new SMESH_ComputeError
+          ( COMPERR_BAD_INPUT_MESH, SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments()) );
+      continue;
+    }
 
-        // find out edge id and node parameter on edge
-        onVertex = ( pnt.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
-        if ( onVertex || posShapeID != posID )
-        {
-          // get edge id
-          double normParam = pnt.normParam;
-          if ( onVertex )
-            normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
-          const TopoDS_Edge& edge = wire->Edge( wire->EdgeIndex( normParam ));
-          edgeID = geom.emap.FindIndex( edge );
-          posID  = posShapeID;
-          isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
-          // if ( onVertex ) // param on curve is different on each of two edges
-          //   seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
-        }
-        seg.epgeominfo[ iEnd ].edgenr = edgeID; //  = geom.emap.FindIndex(edge);
-      }
+    // ----------------------
+    // compute maxh of a FACE
+    // ----------------------
 
-      ngMesh.AddSegment (seg);
+    if ( !_hypParameters )
+    {
+      double edgeLength = 0;
+      if (_hypLengthFromEdges )
       {
-        // restrict size of elements near the segment
-        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;
-
-        NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, 0.5*(np1+np2), avgH );
+        // compute edgeLength as an average segment length
+        int nbSegments = 0;
+        for ( int iW = 0; iW < nbWires; ++iW )
+        {
+          edgeLength += wires[ iW ]->Length();
+          nbSegments += wires[ iW ]->NbSegments();
+        }
+        if ( nbSegments )
+          edgeLength /= nbSegments;
+        netgen::mparam.maxh = edgeLength;
       }
-#ifdef DUMP_SEGMENTS
-        cout << "Segment: " << seg.edgenr << endl
-           << "\tp1: " << seg[0] << endl
-           << "\tp2: " << seg[1] << endl
-           << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
-           << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
-           << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
-           << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
-           << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
-           << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
-#endif
-      if ( isInternalWire )
+      else if ( isDefaultHyp )
       {
-        swap (seg[0], seg[1]);
-        swap( seg.epgeominfo[0], seg.epgeominfo[1] );
-        seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
-        ngMesh.AddSegment (seg);
-#ifdef DUMP_SEGMENTS
-        cout << "Segment: " << seg.edgenr << endl << "\tis REVRESE of the previous one" << endl;
-#endif
+        // set edgeLength by a longest segment
+        double maxSeg2 = 0;
+        for ( int iW = 0; iW < nbWires; ++iW )
+        {
+          const UVPtStructVec& points = wires[ iW ]->GetUVPtStruct();
+          if ( points.empty() )
+            return error( COMPERR_BAD_INPUT_MESH );
+          gp_Pnt pPrev = SMESH_TNodeXYZ( points[0].node );
+          for ( size_t i = 1; i < points.size(); ++i )
+          {
+            gp_Pnt p = SMESH_TNodeXYZ( points[i].node );
+            maxSeg2 = Max( maxSeg2, p.SquareDistance( pPrev ));
+            pPrev = p;
+          }
+        }
+        edgeLength = sqrt( maxSeg2 ) * 1.05;
+        netgen::mparam.maxh = edgeLength;
       }
-    } // loop on segments on a wire
+      if ( netgen::mparam.maxh < DBL_MIN )
+        netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam();
 
-    // close chain of segments
-    if ( nbSegments > 0 )
-    {
-      Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire));
-      const SMDS_MeshNode * lastNode = uvPtVec.back().node;
-      lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
-      if ( lastSeg[1] > ngMesh.GetNP() )
-      {
-        MeshPoint mp( Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
-        ngMesh.AddPoint ( mp, 1, EDGEPOINT );
-        nodeVec.push_back( lastNode );
-      }
-      if ( isInternalWire )
+      if ( !isCommonLocalSize )
       {
-        Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
-        realLastSeg[0] = lastSeg[1];
+        netgen::mparam.minh = aMesher.GetDefaultMinSize( F, netgen::mparam.maxh );
       }
     }
 
-  } // loop on wires of a face
-
-  // add a segment instead of internal vertex
-  NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
-  NETGENPlugin_Mesher::addIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
+    // prepare occgeom
+    netgen::OCCGeometry occgeom;
+    occgeom.shape = F;
+    occgeom.fmap.Add( F );
+    occgeom.CalcBoundingBox();
+    occgeom.facemeshstatus.SetSize(1);
+    occgeom.facemeshstatus = 0;
+    occgeom.face_maxh_modified.SetSize(1);
+    occgeom.face_maxh_modified = 0;
+    occgeom.face_maxh.SetSize(1);
+    occgeom.face_maxh = netgen::mparam.maxh;
+
+    // -------------------------
+    // Fill netgen mesh
+    // -------------------------
+
+    // MESHCONST_ANALYSE step may lead to a failure, so we make an attempt
+    // w/o MESHCONST_ANALYSE at the second loop
+    int err = 0;
+    enum { LOC_SIZE, NO_LOC_SIZE };
+    int iLoop = isCommonLocalSize ? 0 : 1;
+    for ( ; iLoop < 2; iLoop++ )
+    {
+      //bool isMESHCONST_ANALYSE = false;
+      InitComputeError();
 
-  ngMesh.CalcSurfacesOfNode();
+      netgen::Mesh * ngMesh = ngMeshes[ iLoop ];
+      ngMesh->DeleteMesh();
 
-  return TError();
-}
+      if ( iLoop == NO_LOC_SIZE )
+      {
+        ngMesh->SetGlobalH ( mparam.maxh );
+        ngMesh->SetMinimalH( mparam.minh );
+        Box<3> bb = occgeom.GetBoundingBox();
+        bb.Increase (bb.Diam()/10);
+        ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparam.grading);
+        aMesher.SetLocalSize( occgeom, *ngMesh );
+        aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMesh );
+        try {
+          ngMesh->LoadLocalMeshSize( mparam.meshsizefilename );
+        } catch (NgException & ex) {
+          return error( COMPERR_BAD_PARMETERS, ex.What() );
+        }
+      }
 
-//=============================================================================
-/*!
- *Here we are going to use the NETGEN mesher
- */
-//=============================================================================
+      nodeVec.clear();
+      faceErr = aMesher.AddSegmentsToMesh( *ngMesh, occgeom, wires, helper, nodeVec,
+                                           /*overrideMinH=*/!_hypParameters);
+      if ( faceErr && !faceErr->IsOK() )
+        break;
 
-bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
-                                          const TopoDS_Shape& aShape)
-{
-#ifdef WITH_SMESH_CANCEL_COMPUTE
-  netgen::multithread.terminate = 0;
-#endif
-  MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::Compute()");
+      //if ( !isCommonLocalSize )
+      //limitSize( ngMesh, mparam.maxh * 0.8);
 
-  SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
-  int faceID = meshDS->ShapeToIndex( aShape );
+      // -------------------------
+      // Generate surface mesh
+      // -------------------------
 
-  SMESH_MesherHelper helper(aMesh);
-  _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
-  helper.SetElementsOnShape( true );
-  const bool ignoreMediumNodes = _quadraticMesh;
-  
-  // ------------------------
-  // get all edges of a face
-  // ------------------------
-  const TopoDS_Face F = TopoDS::Face( aShape.Oriented( TopAbs_FORWARD ));
-  TError problem;
-  TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem );
-  if ( problem && !problem->IsOK() )
-    return error( problem );
-  int nbWires = wires.size();
-  if ( nbWires == 0 )
-    return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
-  if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
-    return error(COMPERR_BAD_INPUT_MESH,
-                 SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
-
-  // --------------------
-  // compute edge length
-  // --------------------
+      const int startWith = MESHCONST_MESHSURFACE;
+      const int endWith   = toOptimize ? MESHCONST_OPTSURFACE : MESHCONST_MESHSURFACE;
 
-  NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
-  netgen::OCCGeometry occgeo;
-  aMesher.PrepareOCCgeometry( occgeo, F, aMesh );
-  occgeo.fmap.Clear(); // face can be reversed, which is wrong in this case (issue 19978)
-  occgeo.fmap.Add( F );
+      SMESH_Comment str;
+      try {
+        OCC_CATCH_SIGNALS;
 
-  if ( _hypParameters )
-  {
-    aMesher.SetParameters(_hypParameters);
-  }
-  else
-  {
-    double edgeLength = 0;
-    if (_hypLengthFromEdges || (!_hypLengthFromEdges && !_hypMaxElementArea))
-    {
-      int nbSegments = 0;
-      for ( int iW = 0; iW < nbWires; ++iW )
+#ifdef NETGEN_V5
+        err = netgen::OCCGenerateMesh(occgeom, ngMesh, netgen::mparam, startWith, endWith);
+#else
+        char *optstr = 0;
+        err = netgen::OCCGenerateMesh(occgeom, ngMesh, startWith, endWith, optstr);
+#endif
+        if ( netgen::multithread.terminate )
+          return false;
+        if ( err )
+          str << "Error in netgen::OCCGenerateMesh() at " << netgen::multithread.task;
+      }
+      catch (Standard_Failure& ex)
       {
-        edgeLength += wires[ iW ]->Length();
-        nbSegments += wires[ iW ]->NbSegments();
+        err = 1;
+        str << "Exception in  netgen::OCCGenerateMesh()"
+            << " at " << netgen::multithread.task
+            << ": " << ex.DynamicType()->Name();
+        if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
+          str << ": " << ex.GetMessageString();
+      }
+      catch (...) {
+        err = 1;
+        str << "Exception in  netgen::OCCGenerateMesh()"
+            << " at " << netgen::multithread.task;
+      }
+      if ( err )
+      {
+        if ( aMesher.FixFaceMesh( occgeom, *ngMesh, 1 ))
+          break;
+        if ( iLoop == LOC_SIZE )
+        {
+          netgen::mparam.minh = netgen::mparam.maxh;
+          netgen::mparam.maxh = 0;
+          for ( size_t iW = 0; iW < wires.size(); ++iW )
+          {
+            StdMeshers_FaceSidePtr wire = wires[ iW ];
+            const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
+            for ( size_t iP = 1; iP < uvPtVec.size(); ++iP )
+            {
+              SMESH_TNodeXYZ   p( uvPtVec[ iP ].node );
+              netgen::Point3d np( p.X(),p.Y(),p.Z());
+              double segLen = p.Distance( uvPtVec[ iP-1 ].node );
+              double   size = ngMesh->GetH( np );
+              netgen::mparam.minh = Min( netgen::mparam.minh, size );
+              netgen::mparam.maxh = Max( netgen::mparam.maxh, segLen );
+            }
+          }
+          //cerr << "min " << netgen::mparam.minh << " max " << netgen::mparam.maxh << endl;
+          netgen::mparam.minh *= 0.9;
+          netgen::mparam.maxh *= 1.1;
+          continue;
+        }
+        else
+        {
+          faceErr.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, str ));
+        }
       }
-      if ( nbSegments )
-        edgeLength /= nbSegments;
-    }
-    if ( _hypMaxElementArea )
-    {
-      double maxArea = _hypMaxElementArea->GetMaxArea();
-      edgeLength = sqrt(2. * maxArea/sqrt(3.0));
-    }
-    if ( edgeLength < DBL_MIN )
-      edgeLength = occgeo.GetBoundingBox().Diam();
-
-    netgen::mparam.maxh = edgeLength;
-    netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
-    netgen::mparam.quad = _hypQuadranglePreference ? 1 : 0;
-    netgen::mparam.grading = 0.7; // very coarse mesh by default
-  }
-#ifdef NETGEN_NEW
-  occgeo.face_maxh = netgen::mparam.maxh;
-#endif
-
-  // -------------------------
-  // Make input netgen mesh
-  // -------------------------
-
-  NETGENPlugin_NetgenLibWrapper ngLib;
-  netgen::Mesh * ngMesh = (netgen::Mesh*) ngLib._ngMesh;
-
-  Box<3> bb = occgeo.GetBoundingBox();
-  bb.Increase (bb.Diam()/10);
-  ngMesh->SetLocalH (bb.PMin(), bb.PMax(), netgen::mparam.grading);
-  ngMesh->SetGlobalH (netgen::mparam.maxh);
 
-  vector< const SMDS_MeshNode* > nodeVec;
-  problem = addSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
-  if ( problem && !problem->IsOK() )
-    return error( problem );
-
-  // -------------------------
-  // Generate surface mesh
-  // -------------------------
-
-  char *optstr = 0;
-  int startWith = MESHCONST_MESHSURFACE;
-  int endWith   = MESHCONST_OPTSURFACE;
-  int err = 1;
-
-  try {
-#if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
-    OCC_CATCH_SIGNALS;
-#endif
-    err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
-#ifdef WITH_SMESH_CANCEL_COMPUTE
-    if(netgen::multithread.terminate)
-      return false;
-#endif
-    if ( err )
-      error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
-  }
-  catch (Standard_Failure& ex)
-  {
-    SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
-    str << " at " << netgen::multithread.task
-        << ": " << ex.DynamicType()->Name();
-    if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
-      str << ": " << ex.GetMessageString();
-    error(str);
-  }
-  catch (...) {
-    SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
-    str << " at " << netgen::multithread.task;
-    error(str);
-  }
 
-  // ----------------------------------------------------
-  // Fill the SMESHDS with the generated nodes and faces
-  // ----------------------------------------------------
+      // ----------------------------------------------------
+      // Fill the SMESHDS with the generated nodes and faces
+      // ----------------------------------------------------
 
-  int nbNodes = ngMesh->GetNP();
-  int nbFaces = ngMesh->GetNSE();
+      int nbNodes = ngMesh->GetNP();
+      int nbFaces = ngMesh->GetNSE();
 
-  int nbInputNodes = nodeVec.size();
-  nodeVec.resize( nbNodes, 0 );
+      int nbInputNodes = nodeVec.size()-1;
+      nodeVec.resize( nbNodes+1, 0 );
 
-  // add nodes
-  for ( int i = nbInputNodes + 1; i <= nbNodes; ++i )
-  {
-    const MeshPoint& ngPoint = ngMesh->Point(i);
-#ifdef NETGEN_NEW
-    SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
-#else
-    SMDS_MeshNode * node = meshDS->AddNode(ngPoint.X(), ngPoint.Y(), ngPoint.Z());
-#endif
-    nodeVec[ i-1 ] = node;
-  }
+      // add nodes
+      for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
+      {
+        const MeshPoint& ngPoint = ngMesh->Point( ngID );
+        SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
+        nodeVec[ ngID ] = node;
+      }
 
-  // create faces
-  bool reverse = ( aShape.Orientation() == TopAbs_REVERSED );
-  int i,j;
-  for ( i = 1; i <= nbFaces ; ++i )
-  {
-    const Element2d& elem = ngMesh->SurfaceElement(i);
-    vector<const SMDS_MeshNode*> nodes( elem.GetNP() );
-    for (j=1; j <= elem.GetNP(); ++j)
-    {
-      int pind = elem.PNum(j);
-      if ( pind-1 < 0 )
-        break;
-      const SMDS_MeshNode* node = nodeVec.at(pind-1);
-      if ( reverse )
-        nodes[ nodes.size()-j ] = node;
-      else
-        nodes[ j-1 ] = node;
-      if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
+      // create faces
+      int i,j;
+      vector<const SMDS_MeshNode*> nodes;
+      for ( i = 1; i <= nbFaces ; ++i )
       {
-        const PointGeomInfo& pgi = elem.GeomInfoPi(j);
-        meshDS->SetNodeOnFace((SMDS_MeshNode*)node, faceID, pgi.u, pgi.v);
+        const Element2d& elem = ngMesh->SurfaceElement(i);
+        nodes.resize( elem.GetNP() );
+        for (j=1; j <= elem.GetNP(); ++j)
+        {
+          int pind = elem.PNum(j);
+          if ( pind < 1 )
+            break;
+          nodes[ j-1 ] = nodeVec[ pind ];
+          if ( nodes[ j-1 ]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
+          {
+            const PointGeomInfo& pgi = elem.GeomInfoPi(j);
+            meshDS->SetNodeOnFace( nodes[ j-1 ], faceID, pgi.u, pgi.v);
+          }
+        }
+        if ( j > elem.GetNP() )
+        {
+          if ( elem.GetType() == TRIG )
+            helper.AddFace(nodes[0],nodes[1],nodes[2]);
+          else
+            helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
+        }
       }
-    }
-    if ( j > elem.GetNP() )
-    {
-      SMDS_MeshFace* face = 0;
-      if ( elem.GetType() == TRIG )
-        face = helper.AddFace(nodes[0],nodes[1],nodes[2]);
-      else
-        face = helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
-    }
-  }
 
-  return !err;
+      break;
+    } // two attempts
+  } // loop on FACEs
+
+  return true;
 }
 
-#ifdef WITH_SMESH_CANCEL_COMPUTE
 void NETGENPlugin_NETGEN_2D_ONLY::CancelCompute()
 {
   SMESH_Algo::CancelCompute();
   netgen::multithread.terminate = 1;
 }
-#endif
+
+//================================================================================
+/*!
+ * \brief Return progress of Compute() [0.,1]
+ */
+//================================================================================
+
+double NETGENPlugin_NETGEN_2D_ONLY::GetProgress() const
+{
+  return -1;
+  // const char* task1 = "Surface meshing";
+  // //const char* task2 = "Optimizing surface";
+  // double& progress = const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progress;
+  // if ( _progressByTic < 0. &&
+  //      strncmp( netgen::multithread.task, task1, 3 ) == 0 )
+  // {
+  //   progress = Min( 0.25, SMESH_Algo::GetProgressByTic() ); // [0, 0.25]
+  // }
+  // else //if ( strncmp( netgen::multithread.task, task2, 3 ) == 0)
+  // {
+  //   if ( _progressByTic < 0 )
+  //   {
+  //     NETGENPlugin_NETGEN_2D_ONLY* me = (NETGENPlugin_NETGEN_2D_ONLY*) this;
+  //     me->_progressByTic = 0.25 / (_progressTic+1);
+  //   }
+  //   const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progressTic++;
+  //   progress = Max( progress, _progressByTic * _progressTic );
+  // }
+  // //cout << netgen::multithread.task << " " << _progressTic << endl;
+  // return Min( progress, 0.99 );
+}
 
 //=============================================================================
 /*!
@@ -611,7 +684,7 @@ bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
 
   // compute edge length
   double ELen = 0;
-  if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea) {
+  if (( _hypLengthFromEdges ) || ( !_hypLengthFromEdges && !_hypMaxElementArea )) {
     if ( nb1d > 0 )
       ELen = fullLen / nb1d;
   }