Salome HOME
Synchronize adm files
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_2D_ONLY.cxx
old mode 100644 (file)
new mode 100755 (executable)
index 0aac90b..6c54aac
@@ -1,9 +1,9 @@
-// Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
+// Copyright (C) 2007-2014  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
@@ -128,6 +128,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);
 
@@ -180,10 +182,8 @@ bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh&         aMesh,
 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()");
+  netgen::multithread.task = "Surface meshing";
 
   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
   int faceID = meshDS->ShapeToIndex( aShape );
@@ -192,9 +192,12 @@ bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
   _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
   helper.SetElementsOnShape( true );
   const bool ignoreMediumNodes = _quadraticMesh;
-  
+
   // build viscous layers if required
-  const TopoDS_Face F = TopoDS::Face( aShape/*.Oriented( TopAbs_FORWARD )*/);
+  TopoDS_Face F = TopoDS::Face( aShape/*.Oriented( TopAbs_FORWARD )*/);
+  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 )
     return false;
@@ -231,7 +234,7 @@ bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
   else
   {
     double edgeLength = 0;
-    if (_hypLengthFromEdges || (!_hypLengthFromEdges && !_hypMaxElementArea))
+    if (_hypLengthFromEdges /*|| (!_hypLengthFromEdges && !_hypMaxElementArea)*/)
     {
       int nbSegments = 0;
       for ( int iW = 0; iW < nbWires; ++iW )
@@ -242,18 +245,35 @@ bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
       if ( nbSegments )
         edgeLength /= nbSegments;
     }
-    if ( _hypMaxElementArea )
+    else if ( _hypMaxElementArea )
     {
       double maxArea = _hypMaxElementArea->GetMaxArea();
       edgeLength = sqrt(2. * maxArea/sqrt(3.0));
     }
+    else
+    {
+      // set edgeLength by a longest segment
+      double maxSeg2 = 0;
+      for ( int iW = 0; iW < nbWires; ++iW )
+      {
+        const UVPtStructVec& points = wires[ iW ]->GetUVPtStruct();
+        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;
+    }
     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
+    netgen::mparam.grading = 0.4; // Moderate fineness by default
   }
   occgeo.face_maxh = netgen::mparam.maxh;
 
@@ -261,122 +281,237 @@ bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
   // 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);
+  // MESHCONST_ANALYSE step may lead to a failure, so we make an attempt
+  // w/o MESHCONST_ANALYSE at the second loop
+  int err = 1;
+  int iLoop = netgen::mparam.uselocalh ? 0 : 1; // uselocalh depends on 
+  for ( ; iLoop < 2; iLoop++ )
+  {
+    bool isMESHCONST_ANALYSE = false;
+    InitComputeError();
 
-  vector< const SMDS_MeshNode* > nodeVec;
-  problem = aMesher.AddSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
-  if ( problem && !problem->IsOK() )
-    return error( problem );
-
-  // -------------------------
-  // Generate surface mesh
-  // -------------------------
+    NETGENPlugin_NetgenLibWrapper ngLib;
+    netgen::Mesh * ngMesh = (netgen::Mesh*) ngLib._ngMesh;
+    ngLib._isComputeOk = false;
 
 #ifndef NETGEN_V5
-  char *optstr = 0;
+    char *optstr = 0;
 #endif
-  int startWith = MESHCONST_MESHSURFACE;
-  int endWith   = MESHCONST_OPTSURFACE;
-  int err = 1;
+    int startWith = MESHCONST_ANALYSE;
+    int endWith   = MESHCONST_ANALYSE;
 
-  try {
-#if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
-    OCC_CATCH_SIGNALS;
-#endif
+    if ( !_hypLengthFromEdges && !_hypMaxElementArea && iLoop == 0 )
+    {
+      isMESHCONST_ANALYSE = true;
 #ifdef NETGEN_V5
-    err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
+      err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
 #else
-    err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
-#endif
-#ifdef WITH_SMESH_CANCEL_COMPUTE
-    if(netgen::multithread.terminate)
-      return false;
+      err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
 #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);
-  }
+      ngLib._ngMesh = 0;
+      ngLib.setMesh(( nglib::Ng_Mesh*) ngMesh );
+    }
+    else
+    {
+      Box<3> bb = occgeo.GetBoundingBox();
+      bb.Increase (bb.Diam()/10);
+      ngMesh->SetLocalH (bb.PMin(), bb.PMax(), netgen::mparam.grading);
+      ngMesh->SetGlobalH (netgen::mparam.maxh);
+    }
+    //cerr << "max " << netgen::mparam.maxh << " min " << netgen::mparam.minh << endl;
 
-  // ----------------------------------------------------
-  // Fill the SMESHDS with the generated nodes and faces
-  // ----------------------------------------------------
+    vector< const SMDS_MeshNode* > nodeVec;
+    problem = aMesher.AddSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
+    if ( problem && !problem->IsOK() )
+      return error( problem );
 
-  int nbNodes = ngMesh->GetNP();
-  int nbFaces = ngMesh->GetNSE();
+    if ( iLoop == 0 )
+    {
+      // limit element size near existing segments
+      TopTools_IndexedMapOfShape edgeMap;
+      PShapeIteratorPtr solidIt = helper.GetAncestors( F, aMesh, TopAbs_SOLID );
+      while ( const TopoDS_Shape* solid = solidIt->next() )
+      {
+        TopExp_Explorer eExp( *solid, TopAbs_EDGE );
+        for ( ; eExp.More(); eExp.Next() )
+        {
+          const TopoDS_Shape& edge = eExp.Current();
+          if (( SMESH_Algo::isDegenerated( TopoDS::Edge( edge ))) ||
+              ( helper.IsSubShape( edge, aShape )) ||
+              ( !edgeMap.Add( edge )))
+            continue;
+          SMESHDS_SubMesh* smDS = aMesh.GetMeshDS()->MeshElements( edge );
+          if ( !smDS ) continue;
+          SMDS_ElemIteratorPtr segIt = smDS->GetElements();
+          while ( segIt->more() )
+          {
+            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());
+            ngMesh->RestrictLocalH( pi, Max(( n1 - n2 ).Modulus(), netgen::mparam.minh ));
+          }
+        }
+      }
+    }
 
-  int nbInputNodes = nodeVec.size()-1;
-  nodeVec.resize( nbNodes+1, 0 );
+    // -------------------------
+    // Generate surface mesh
+    // -------------------------
 
-  // 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;
-  }
+    startWith = MESHCONST_MESHSURFACE;
+    endWith   = MESHCONST_OPTSURFACE;
 
-  // create faces
-  const bool reverse = false; //( 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)
+    netgen::mparam.uselocalh = true; // needed while optimization
+    try {
+      OCC_CATCH_SIGNALS;
+
+#ifdef NETGEN_V5
+      err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
+#else
+      err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
+#endif
+      if(netgen::multithread.terminate)
+        return false;
+      if ( err )
+        error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
+    }
+    catch (Standard_Failure& ex)
     {
-      int pind = elem.PNum(j);
-      if ( pind < 1 )
-        break;
-      const SMDS_MeshNode* node = nodeVec[ pind ];
-      if ( reverse )
-        nodes[ nodes.size()-j ] = node;
-      else
-        nodes[ j-1 ] = node;
-      if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
+      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);
+      err = 1;
+    }
+    catch (...) {
+      SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
+      str << " at " << netgen::multithread.task;
+      error(str);
+      err = 1;
+    }
+    if ( err /*&& !isMESHCONST_ANALYSE*/ && iLoop == 0 )
+    {
+      netgen::mparam.minh = netgen::mparam.maxh;
+      netgen::mparam.maxh = 0;
+      for ( int iW = 0; iW < wires.size(); ++iW )
       {
-        const PointGeomInfo& pgi = elem.GeomInfoPi(j);
-        meshDS->SetNodeOnFace((SMDS_MeshNode*)node, faceID, pgi.u, pgi.v);
+        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;
     }
-    if ( j > elem.GetNP() )
+
+    // ----------------------------------------------------
+    // Fill the SMESHDS with the generated nodes and faces
+    // ----------------------------------------------------
+
+    int nbNodes = ngMesh->GetNP();
+    int nbFaces = ngMesh->GetNSE();
+
+    int nbInputNodes = nodeVec.size()-1;
+    nodeVec.resize( nbNodes+1, 0 );
+
+    // add nodes
+    for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
     {
-      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]);
+      const MeshPoint& ngPoint = ngMesh->Point( ngID );
+      SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
+      nodeVec[ ngID ] = node;
     }
-  }
+
+    // create faces
+    const bool reverse = false; //( 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 )
+          break;
+        const SMDS_MeshNode* node = nodeVec[ pind ];
+        if ( reverse )
+          nodes[ nodes.size()-j ] = node;
+        else
+          nodes[ j-1 ] = node;
+        if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
+        {
+          const PointGeomInfo& pgi = elem.GeomInfoPi(j);
+          meshDS->SetNodeOnFace((SMDS_MeshNode*)node, faceID, pgi.u, pgi.v);
+        }
+      }
+      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]);
+      }
+    }
+
+    ngLib._isComputeOk = !err;
+    break;
+
+  } // two attempts
 
   return !err;
 }
 
-#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
+{
+  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 );
+}
 
 //=============================================================================
 /*!