Salome HOME
Merge changes from 'master' branch.
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_Remesher_2D.cxx
1 // Copyright (C) 2007-2016  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 // File      : NETGENPlugin_Remesher_2D.cxx
23 // Created   : Thu Sep 21 16:48:46 2017
24 // Author    : Edward AGAPOV (eap)
25 //
26
27 #include "NETGENPlugin_Remesher_2D.hxx"
28
29 #include "NETGENPlugin_Mesher.hxx"
30 #include "NETGENPlugin_Hypothesis_2D.hxx"
31
32 #include <SMDS_SetIterator.hxx>
33 #include <SMESHDS_Mesh.hxx>
34 #include <SMESH_ControlsDef.hxx>
35 #include <SMESH_Gen.hxx>
36 #include <SMESH_MeshAlgos.hxx>
37 #include <SMESH_MesherHelper.hxx>
38 #include <SMESH_subMesh.hxx>
39
40 #include <Bnd_B3d.hxx>
41 #include <Precision.hxx>
42
43 #include <occgeom.hpp>
44 #include <meshing.hpp>
45 #include <stlgeom.hpp>
46 //#include <stltool.hxx>
47
48 #include <boost/container/flat_set.hpp>
49
50 using namespace nglib;
51
52 // namespace netgen
53 // {
54 // #if defined(NETGEN_V5) && defined(WIN32)
55 //   DLL_HEADER 
56 // #endif
57 //   extern STLParameters stlparam;
58 // }
59
60 namespace
61 {
62   //=============================================================================
63   /*!
64    * \brief Fill holes in the mesh, since netgen can remesh only a closed shell mesh.
65    *        At destruction, remove triangles filling the holes
66    */
67   class HoleFiller
68   {
69   public:
70     HoleFiller( SMESH_Mesh& meshDS );
71     ~HoleFiller();
72     void AddHoleBorders( Ng_STL_Geometry * ngStlGeo );
73     void KeepHole() { myHole.clear(); myCapElems.clear(); }
74     void ClearCapElements() { myCapElems.clear(); }
75
76   private:
77     SMESHDS_Mesh*                          myMeshDS;
78     std::vector< std::vector< gp_XYZ > >   myHole;      // initial border nodes
79     std::vector< gp_XYZ >                  myInHolePos; // position inside each hole
80     std::vector< const SMDS_MeshElement* > myCapElems;  // elements closing holes
81   };
82
83   //================================================================================
84   /*!
85    * \brief Fill holes in the mesh
86    */
87   //================================================================================
88
89   HoleFiller::HoleFiller( SMESH_Mesh& theMesh ):
90     myMeshDS( theMesh.GetMeshDS() )
91   {
92     SMESH_MeshEditor editor( &theMesh );
93     {
94       // // merge nodes
95       // const double tol = Max( 0.1 * netgen::mparam.minh, Precision::Confusion() );
96       // TIDSortedNodeSet allNodes;
97       // SMESH_MeshEditor::TListOfListOfNodes equalNodes;
98       // editor.FindCoincidentNodes( allNodes, tol, equalNodes, true );
99       // editor.MergeNodes( equalNodes, /*noHoles=*/false );
100     }
101
102     // find holes
103     SMESH_MeshAlgos::TFreeBorderVec holes;
104     bool isManifold = true, isGoodOri = true;
105     SMESH_MeshAlgos::FindFreeBorders( *myMeshDS, holes, /*closedOnly=*/true,
106                                       &isManifold, &isGoodOri );
107
108     if ( !isManifold )
109     {
110       // set bad faces into a compute error
111       const char* text = "Non-manifold mesh. Only manifold mesh can be re-meshed";
112       SMESH_ComputeErrorPtr error = SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH, text );
113       SMESH::Controls::MultiConnection2D fun;
114       fun.SetMesh( myMeshDS );
115       SMDS_ElemIteratorPtr fIt = myMeshDS->elementsIterator( SMDSAbs_Face );
116       while ( fIt->more() )
117       {
118         const SMDS_MeshElement* f = fIt->next();
119         if ( fun.GetValue( f->GetID() ) > 2 )
120           error->myBadElements.push_back( f );
121       }
122       theMesh.GetSubMesh( theMesh.GetShapeToMesh() )->GetComputeError() = error;
123       throw SALOME_Exception( text );
124     }
125
126     // don't want to sew coincident borders
127     if ( !holes.empty() )
128     {
129       // define tolerance
130       double tol, len, sumLen = 0, minLen = 1e100;
131       int     nbSeg = 0;
132       for ( size_t i = 0; i < holes.size(); ++i )
133       {
134         nbSeg += holes[i].size();
135         SMESH_NodeXYZ p1 = holes[i][0];
136         for ( size_t iP = 1; iP < holes[i].size(); ++iP )
137         {
138           SMESH_NodeXYZ p2 = holes[i][iP];
139           len = ( p1 - p2 ).Modulus();
140           sumLen += len;
141           minLen = Min( minLen, len );
142           p1 = p2;
143         }
144       }
145       double avgLen = sumLen / nbSeg;
146       if ( minLen > 1e-5 * avgLen )
147         tol = 0.1 * minLen; // minLen is not degenerate
148       else
149         tol = 0.1 * avgLen;
150
151       SMESH_MeshAlgos::CoincidentFreeBorders freeBords;
152       SMESH_MeshAlgos::FindCoincidentFreeBorders( *myMeshDS, tol, freeBords );
153       if ( !freeBords._coincidentGroups.empty() )
154       {
155         const char* text = "Can't re-meshed a mesh with coincident free edges";
156         SMESH_ComputeErrorPtr error = SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH, text );
157         for ( size_t i = 0; i < freeBords._borders.size(); ++i )
158           error->myBadElements.insert( error->myBadElements.end(),
159                                        freeBords._borders[i].begin(),
160                                        freeBords._borders[i].end() );
161         theMesh.GetSubMesh( theMesh.GetShapeToMesh() )->GetComputeError() = error;
162         throw SALOME_Exception( text );
163       }
164     }
165
166     // fill holes
167     myHole.resize( holes.size() );
168     myInHolePos.resize( holes.size() );
169     std::vector<const SMDS_MeshElement*> newFaces;
170     for ( size_t i = 0; i < holes.size(); ++i )
171     {
172       newFaces.clear();
173       SMESH_MeshAlgos::FillHole( holes[i], *myMeshDS, newFaces );
174
175       // keep data to be able to remove hole filling faces after remeshing
176       if ( !newFaces.empty() )
177       {
178         myHole[i].resize( holes[i].size() );
179         for ( size_t iP = 0; iP < holes[i].size(); ++iP )
180           myHole[i][iP] = SMESH_NodeXYZ( holes[i][iP] );
181
182         myInHolePos[i] = ( SMESH_NodeXYZ( newFaces[0]->GetNode(0)) +
183                            SMESH_NodeXYZ( newFaces[0]->GetNode(1)) +
184                            SMESH_NodeXYZ( newFaces[0]->GetNode(2)) ) / 3.;
185         myCapElems.insert( myCapElems.end(), newFaces.begin(), newFaces.end() );
186         // unmark to be able to remove them if meshing is canceled
187         // for ( size_t iF = 0; iF < newFaces.size(); ++iF )
188         //   newFaces[iF]->setIsMarked( false );
189       }
190     }
191     // fix orientation
192     if ( !isGoodOri )
193     {
194       SMDS_ElemIteratorPtr fIt = myMeshDS->elementsIterator( SMDSAbs_Face );
195       while ( fIt->more() )
196       {
197         const SMDS_MeshElement* f = fIt->next();
198         gp_XYZ normal;
199         if ( SMESH_MeshAlgos::FaceNormal( f, normal ))
200         {
201           TIDSortedElemSet allFaces;
202           editor.Reorient2D( allFaces, normal, f );
203           break;
204         }
205       }
206     }
207   }
208   //================================================================================
209   /*!
210    * \brief Add hole borders to be kept in a new mesh
211    */
212   //================================================================================
213
214   void HoleFiller::AddHoleBorders( Ng_STL_Geometry * ngStlGeo )
215   {
216     for ( size_t i = 0; i < myHole.size(); ++i )
217       for ( size_t iP = 1; iP < myHole[i].size(); ++iP )
218       {
219         Ng_STL_AddEdge( ngStlGeo,
220                         myHole[i][iP-1].ChangeData(),
221                         myHole[i][iP-0].ChangeData() );
222       }
223   }
224   //================================================================================
225   /*!
226    * \brief Remove triangles filling the holes
227    */
228   //================================================================================
229
230   HoleFiller::~HoleFiller()
231   {
232     if ( myMeshDS->NbNodes() < 3 )
233       return;
234
235     if ( !myCapElems.empty() ) // old mesh not removed; simply remove myCapElems
236     {
237       for ( size_t i = 0; i < myCapElems.size(); ++i )
238         myMeshDS->RemoveFreeElement( myCapElems[i], /*sm=*/0 );
239       return;
240     }
241
242     bool hasOrphanNodes = true;
243
244     const double tol = Max( 1e-3 * netgen::mparam.minh, Precision::Confusion() );
245
246     for ( size_t i = 0; i < myHole.size(); ++i )
247     {
248       std::vector< gp_XYZ >& borderPnt = myHole[i];
249       const gp_XYZ&          inHolePos = myInHolePos[i];
250       if ( borderPnt.empty() ) continue;
251       borderPnt.pop_back(); // first point repeated at end
252
253       // mark all nodes located on the hole border
254
255       // new nodeSearcher for each hole, otherwise it contains removed nodes for i > 0
256       SMESHUtils::Deleter< SMESH_NodeSearcher > nodeSearcher;
257       if ( hasOrphanNodes )
258       {
259         std::vector< const SMDS_MeshNode* > sharedNodes;
260         sharedNodes.reserve( myMeshDS->NbNodes() );
261         SMDS_NodeIteratorPtr nIt = myMeshDS->nodesIterator();
262         while ( nIt->more() )
263         {
264           const SMDS_MeshNode* n = nIt->next();
265           if ( n->NbInverseElements() )
266             sharedNodes.push_back( n );
267         }
268         hasOrphanNodes = ((int) sharedNodes.size() < myMeshDS->NbNodes() );
269         SMDS_ElemIteratorPtr elemIt( new SMDS_NodeVectorElemIterator( sharedNodes.begin(),
270                                                                       sharedNodes.end() ));
271         nodeSearcher._obj = SMESH_MeshAlgos::GetNodeSearcher( elemIt );
272       }
273       else
274       {
275         nodeSearcher._obj = SMESH_MeshAlgos::GetNodeSearcher( *myMeshDS );
276       }
277
278       std::vector< const SMDS_MeshElement* > edgesToRemove;
279       edgesToRemove.reserve( borderPnt.size() );
280
281       // look for a border point coincident with a node
282       size_t iP = 0;
283       SMESH_NodeXYZ bordNode1;
284       for ( ; iP < borderPnt.size(); ++iP )
285       {
286         bordNode1 = nodeSearcher->FindClosestTo( borderPnt[iP] );
287         if (( bordNode1 - borderPnt[iP] ).SquareModulus() < tol * tol )
288           break;
289       }
290       ++iP;
291       bordNode1._node->setIsMarked( true );
292
293       // find the rest nodes located on the hole border
294       boost::container::flat_set< const SMDS_MeshNode* > checkedNodes;
295       gp_XYZ p1 = bordNode1;
296       for ( size_t j = 0; j < borderPnt.size()+1; ++j,  iP = ( iP+1 ) % borderPnt.size() )
297       {
298         // among nodes surrounding bordNode1 find one most close to vec12
299         gp_XYZ vec12 = borderPnt[iP] - p1;
300         bool pntReached = false; // last found node is at iP
301         while ( !pntReached )
302         {
303           const SMDS_MeshNode* bordNode = bordNode1._node;
304           SMDS_ElemIteratorPtr fIt = bordNode->GetInverseElementIterator( SMDSAbs_Face );
305           double minArea = 1e100;
306           checkedNodes.clear();
307           checkedNodes.insert( bordNode );
308           while ( fIt->more() )
309           {
310             const SMDS_MeshElement* f = fIt->next();
311             for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
312             {
313               const SMDS_MeshNode* n = f->GetNode( iN );
314               if ( !checkedNodes.insert( n ).second )
315                 continue;
316               SMESH_NodeXYZ pn = n;
317               gp_XYZ vecPN = pn - bordNode1;
318               if ( vecPN * vec12 <= 0 )
319                 continue;
320               gp_XYZ vec1N = pn - p1;
321               double     a = vec12.CrossSquareMagnitude( vec1N );
322               if ( a < minArea )
323               {
324                 bordNode = n;
325                 minArea = a;
326               }
327             }
328             if ( minArea < std::numeric_limits<double>::min() )
329               break;
330           }
331           if ( bordNode == bordNode1._node )
332             return; // bug in the loop above
333
334           SMESH_NodeXYZ bordNode2 = bordNode;
335           gp_XYZ            vec1N = bordNode2 - p1;
336           double u = ( vec12 * vec1N ) / vec12.SquareModulus(); // param [0,1] of bordNode on vec12
337           if ( u < 1 + tol )
338           {
339             bordNode->setIsMarked( true );
340             //cout << bordNode->GetID() << " ";
341
342             if ( const SMDS_MeshElement* edge = myMeshDS->FindEdge( bordNode1._node, bordNode ))
343               edgesToRemove.push_back( edge );
344             else
345               edgesToRemove.push_back( myMeshDS->AddEdge( bordNode1._node, bordNode ));
346             edgesToRemove.back()->setIsMarked( true );
347
348             if ( minArea > std::numeric_limits<double>::min() &&
349                  minArea / vec12.SquareModulus() > tol * tol )
350             {
351               // node is far from the border, move it
352               gp_XYZ p = p1 + u * vec12;
353               myMeshDS->MoveNode( bordNode, p.X(), p.Y(), p.Z() );
354             }
355             bordNode1 = bordNode2;
356           }
357           //else -- there must be another border point between bordNode1 and bordNode
358           pntReached = ( u > 1 - tol );
359         }
360         p1 = borderPnt[iP];
361
362       }
363       //cout << endl << endl;
364
365       // remove all faces starting from inHolePos
366
367       // get a starting face
368       std::vector< const SMDS_MeshNode* >     nodesToRemove;
369       std::vector< const SMDS_MeshElement* >  facesToRemove;
370       const SMDS_MeshNode* inHoleNode = nodeSearcher->FindClosestTo( inHolePos );
371       if ( inHoleNode && ! inHoleNode->isMarked() )
372       {
373         SMDS_ElemIteratorPtr fIt = inHoleNode->GetInverseElementIterator( SMDSAbs_Face );
374         while ( fIt->more() )
375           facesToRemove.push_back( fIt->next() );
376       }
377       else
378       {
379         SMESHUtils::Deleter< SMESH_ElementSearcher > faceSearcher
380           ( SMESH_MeshAlgos::GetElementSearcher( *myMeshDS ));
381         if ( const SMDS_MeshElement* f = faceSearcher->FindClosestTo( inHolePos, SMDSAbs_Face ))
382           facesToRemove.push_back( f );
383         else
384           continue;
385       }
386       for ( size_t iF = 0; iF < facesToRemove.size(); ++iF )
387         facesToRemove[iF]->setIsMarked( true );
388
389       // remove faces and nodes
390       TIDSortedElemSet elemSet, avoidSet;
391       const SMDS_MeshElement* e;
392       while ( !facesToRemove.empty() )
393       {
394         const SMDS_MeshElement* inHoleFace = facesToRemove.back();
395         facesToRemove.pop_back();
396
397         // add adjacent faces into facesToRemove
398         for ( int iN = 0, nbN = inHoleFace->NbNodes(); iN < nbN; ++iN )
399         {
400           const SMDS_MeshNode* n1 = inHoleFace->GetNode( iN );
401           if ( !n1->isMarked() )
402           {
403             SMDS_ElemIteratorPtr eIt = n1->GetInverseElementIterator();
404             while ( eIt->more() )
405             {
406               e = eIt->next();
407               if ( e->GetType() == SMDSAbs_Face )
408               {
409                 if ( !e->isMarked() )
410                   facesToRemove.push_back( e );
411                 e->setIsMarked( true );
412               }
413               else if ( e->GetType() == SMDSAbs_Edge )
414               {
415                 myMeshDS->RemoveFreeElement( e, 0, /*fromGroups=*/false );
416               }
417             }
418             if ( n1->NbInverseElements() == 1 )
419               nodesToRemove.push_back( n1 );
420           }
421           else
422           {
423             const SMDS_MeshNode* n2 = inHoleFace->GetNodeWrap( iN+1 );
424             if (( n2->isMarked() ) &&
425                 ( !(e = myMeshDS->FindEdge( n1, n2 )) || !e->isMarked() )) // n1-n2 not hole border
426             {
427               if ( e ) // remove edge
428                 myMeshDS->RemoveFreeElement( e, 0, /*fromGroups=*/false );
429               avoidSet.clear();
430               avoidSet.insert( inHoleFace );
431               if (( e = SMESH_MeshAlgos::FindFaceInSet( n1, n2, elemSet, avoidSet )))
432               {
433                 if ( !e->isMarked() )
434                   facesToRemove.push_back( e );
435                 e->setIsMarked( true );
436               }
437             }
438           }
439         }
440         myMeshDS->RemoveFreeElement( inHoleFace, 0, /*fromGroups=*/false );
441
442         for ( size_t iN = 0; iN < nodesToRemove.size(); ++iN )
443           myMeshDS->RemoveFreeNode( nodesToRemove[iN], 0, /*fromGroups=*/false );
444         nodesToRemove.clear();
445       }
446
447       // remove edges from the hole border
448       // for ( size_t iE = 0; iE < edgesToRemove.size(); ++iE )
449       //   myMeshDS->RemoveFreeElement( edgesToRemove[iE], 0, /*fromGroups=*/false );
450
451     } // loop on holes
452
453     return;
454   } // ~HoleFiller()
455
456 } // namespace
457
458 //=============================================================================
459 /*!
460  * Constructor
461  */
462 //=============================================================================
463
464 NETGENPlugin_Remesher_2D::NETGENPlugin_Remesher_2D(int hypId, SMESH_Gen* gen)
465   : SMESH_2D_Algo(hypId, gen)
466 {
467   _name = "NETGEN_Remesher_2D";
468   _shapeType = (1 << TopAbs_FACE); // 1 bit /shape type
469   _compatibleHypothesis.push_back("NETGEN_RemesherParameters_2D");
470   _requireShape = false;
471
472   _hypothesis = 0;
473 }
474
475 //=============================================================================
476 /*!
477  * Check assigned hypotheses
478  */
479 //=============================================================================
480
481 bool NETGENPlugin_Remesher_2D::CheckHypothesis (SMESH_Mesh&         theMesh,
482                                                 const TopoDS_Shape& theShape,
483                                                 Hypothesis_Status&  theStatus)
484 {
485   _hypothesis = 0;
486
487   // can work with no hypothesis
488   theStatus = SMESH_Hypothesis::HYP_OK;
489
490   const list<const SMESHDS_Hypothesis*>& hyps =
491     GetUsedHypothesis( theMesh, theShape, /*skipAux=*/true );
492
493   switch ( hyps.size() ) {
494   case 0:
495     break;
496   case 1:
497     _hypothesis = hyps.front();
498     break;
499   default:
500     theStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
501   }
502
503   return theStatus == SMESH_Hypothesis::HYP_OK;
504 }
505
506 //=============================================================================
507 /*!
508  * Compute mesh on an input mesh
509  */
510 //=============================================================================
511
512 bool NETGENPlugin_Remesher_2D::Compute(SMESH_Mesh&         theMesh,
513                                        SMESH_MesherHelper* theHelper)
514 {
515   if ( theMesh.NbFaces() == 0 )
516     return !error( COMPERR_WARNING, "No faces in input mesh");
517
518   NETGENPlugin_Mesher mesher( &theMesh, theMesh.GetShapeToMesh(), /*isVol=*/false);
519   NETGENPlugin_NetgenLibWrapper ngLib;
520   netgen::Mesh *        ngMesh = (netgen::Mesh*) ngLib._ngMesh;
521   Ng_STL_Geometry *   ngStlGeo = Ng_STL_NewGeometry();
522   netgen::STLTopology* stlTopo = (netgen::STLTopology*) ngStlGeo;
523   netgen::multithread.terminate = 0;
524
525   const NETGENPlugin_RemesherHypothesis_2D* hyp =
526     dynamic_cast<const NETGENPlugin_RemesherHypothesis_2D*>( _hypothesis );
527   mesher.SetParameters( hyp );// for holeFiller
528
529   SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
530   HoleFiller holeFiller( theMesh );
531   //theHelper->SetIsQuadratic( theMesh.NbFaces( ORDER_QUADRATIC ));
532
533   // fill ngStlGeo with triangles
534   SMDS_ElemIteratorPtr fIt = meshDS->elementsIterator( SMDSAbs_Face );
535   while ( fIt->more() )
536   {
537     const SMDS_MeshElement* f = fIt->next();
538     SMESH_NodeXYZ n1 = f->GetNode( 0 );
539     SMESH_NodeXYZ n2 = f->GetNode( 1 );
540     SMESH_NodeXYZ n3 = f->GetNode( 2 );
541     Ng_STL_AddTriangle( ngStlGeo,
542                         n1.ChangeData(),
543                         n2.ChangeData(),
544                         n3.ChangeData() );
545     if ( f->NbNodes() > 3 )
546     {
547       n2.Set( f->GetNode( 3 ));
548       Ng_STL_AddTriangle( ngStlGeo,
549                           n1.ChangeData(),
550                           n3.ChangeData(),
551                           n2.ChangeData());
552     }
553   }
554   // add edges
555   holeFiller.AddHoleBorders( ngStlGeo );
556
557   // init stl DS
558   Ng_Result ng_res = Ng_STL_InitSTLGeometry( ngStlGeo );
559   if ( ng_res != NG_OK )
560   {
561 #ifdef _DEBUG_
562     holeFiller.KeepHole();
563 #endif
564     std::string txt = "Error Initialising the STL Geometry";
565     if ( !stlTopo->GetStatusText().empty() )
566       txt += ". " + stlTopo->GetStatusText();
567     return error( COMPERR_BAD_INPUT_MESH, txt );
568   }
569
570   Ng_Meshing_Parameters ngParams;
571   ng_res = Ng_STL_MakeEdges( ngStlGeo, ngLib._ngMesh, &ngParams );
572   if ( ng_res != NG_OK )
573     return error( "Error in Edge Meshing" );
574
575   // set parameters
576   if ( hyp )
577   {
578     ngParams.maxh              = hyp->GetMaxSize();
579     ngParams.minh              = hyp->GetMinSize();
580     ngParams.meshsize_filename = (char*) hyp->GetMeshSizeFile().c_str();
581     ngParams.quad_dominated    = hyp->GetQuadAllowed();
582     netgen::stlparam.yangle    = hyp->GetRidgeAngle();
583     mesher.SetParameters( hyp );
584   }
585   else
586   {
587     double diagSize = Dist( stlTopo->GetBoundingBox().PMin(), stlTopo->GetBoundingBox().PMax());
588     netgen::mparam.maxh = diagSize / GetGen()->GetBoundaryBoxSegmentation();
589     netgen::mparam.minh = netgen::mparam.maxh;
590   }
591
592   double h = netgen::mparam.maxh;
593   ngMesh->SetGlobalH( h );
594   ngMesh->SetMinimalH( netgen::mparam.minh );
595   ngMesh->SetLocalH( stlTopo->GetBoundingBox().PMin() - netgen::Vec3d(h, h, h),
596                      stlTopo->GetBoundingBox().PMax() + netgen::Vec3d(h, h, h),
597                      netgen::mparam.grading );
598   ngMesh->LoadLocalMeshSize( ngParams.meshsize_filename );
599
600   netgen::OCCGeometry occgeo;
601   mesher.SetLocalSize( occgeo, *ngMesh );
602
603   // meshing
604   try
605   {
606     ng_res = Ng_STL_GenerateSurfaceMesh( ngStlGeo, ngLib._ngMesh, &ngParams );
607   }
608   catch (netgen::NgException & ex)
609   {
610     if ( netgen::multithread.terminate )
611       return false;
612   }
613   if ( ng_res != NG_OK )
614     return error( "Error in Surface Meshing" );
615
616   int nbN = ngMesh->GetNP();
617   int nbE = ngMesh->GetNSeg();
618   int nbF = ngMesh->GetNSE();
619   if ( nbF == 0 )
620     return error( "Error in Surface Meshing" );
621
622   // remove existing mesh
623   holeFiller.ClearCapElements();
624   SMDS_ElemIteratorPtr eIt = meshDS->elementsIterator();
625   while ( eIt->more() )
626     meshDS->RemoveFreeElement( eIt->next(), /*sm=*/0 );
627   SMDS_NodeIteratorPtr nIt = meshDS->nodesIterator();
628   while ( nIt->more() )
629     meshDS->RemoveFreeNode( nIt->next(), /*sm=*/0 );
630
631   // retrieve new mesh
632
633   // add nodes
634   std::vector< const SMDS_MeshNode* > newNodes( nbN+1 );
635   for ( int i = 1; i <= nbN; ++i )
636   {
637     const netgen::MeshPoint& p = ngMesh->Point(i);
638     newNodes[i] = meshDS->AddNode( p(0),p(1),p(2) );
639   }
640
641   // add edges
642   std::vector<const SMDS_MeshNode*> nodes(4);
643   for ( int i = 1; i <= nbE; ++i )
644   {
645     const netgen::Segment& seg = ngMesh->LineSegment(i);
646     nodes.clear();
647     for ( int j = 0; j < 2; ++j )
648     {
649       size_t pind = seg.pnums[j];
650       if ( pind > 0 && pind < newNodes.size() )
651         nodes.push_back( newNodes[ pind ]);
652       else
653         break;
654     }
655     if ( nodes.size() == 2 && !meshDS->FindEdge( nodes[0], nodes[1] ))
656       meshDS->AddEdge( nodes[0], nodes[1] );
657   }
658
659   // add faces
660   for ( int i = 1; i <= nbF; ++i )
661   {
662     const netgen::Element2d& elem = ngMesh->SurfaceElement(i);
663     nodes.clear();
664     for ( int j = 1; j <= elem.GetNP(); ++j )
665     {
666       size_t pind = elem.PNum(j);
667       if ( pind > 0 && pind < newNodes.size() )
668         nodes.push_back( newNodes[ pind ]);
669       else
670         break;
671     }
672     switch( nodes.size() )
673     {
674     case 3: meshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
675     case 4: meshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
676     }
677   }
678
679   // as we don't assign the new triangles to a shape (the pseudo-shape),
680   // to avoid their removal at hypothesis modification,
681   // we mark the shape as always computed to avoid the error messages
682   // that no elements assigned to the shape
683   theMesh.GetSubMesh( theHelper->GetSubShape() )->SetIsAlwaysComputed( true );
684
685   return true;
686 }
687
688 //=============================================================================
689 /*!
690  * Do not compute mesh on geometry
691  */
692 //=============================================================================
693
694 bool NETGENPlugin_Remesher_2D::Compute(SMESH_Mesh&         theMesh,
695                                        const TopoDS_Shape& theShape)
696 {
697   return false;
698 }
699
700 //=============================================================================
701 /*!
702  * Terminate Compute()
703  */
704 //=============================================================================
705
706 void NETGENPlugin_Remesher_2D::CancelCompute()
707 {
708   SMESH_Algo::CancelCompute();
709   netgen::multithread.terminate = 1;
710 }
711
712 //================================================================================
713 /*!
714  * \brief Return progress of Compute() [0.,1]
715  */
716 //================================================================================
717
718 double NETGENPlugin_Remesher_2D::GetProgress() const
719 {
720   return netgen::multithread.percent / 100.;
721 }
722
723 //=============================================================================
724 /*!
725  *
726  */
727 //=============================================================================
728
729 bool NETGENPlugin_Remesher_2D::Evaluate(SMESH_Mesh&         aMesh,
730                                         const TopoDS_Shape& aShape,
731                                         MapShapeNbElems& aResMap)
732 {
733   return false;
734 }