Salome HOME
Fix preprocessor instructions for GCC
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_3D.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
23 //=============================================================================
24 // File      : NETGENPlugin_NETGEN_3D.cxx
25 //             Moved here from SMESH_NETGEN_3D.cxx
26 // Created   : lundi 27 Janvier 2003
27 // Author    : Nadir BOUHAMOU (CEA)
28 // Project   : SALOME
29 //=============================================================================
30 //
31 #include "NETGENPlugin_NETGEN_3D.hxx"
32
33 #include "NETGENPlugin_Hypothesis.hxx"
34
35 #include <SMDS_MeshElement.hxx>
36 #include <SMDS_MeshNode.hxx>
37 #include <SMESHDS_Mesh.hxx>
38 #include <SMESH_Comment.hxx>
39 #include <SMESH_ControlsDef.hxx>
40 #include <SMESH_Gen.hxx>
41 #include <SMESH_Mesh.hxx>
42 #include <SMESH_MeshEditor.hxx>
43 #include <SMESH_MesherHelper.hxx>
44 #include <SMESH_subMesh.hxx>
45 #include <StdMeshers_MaxElementVolume.hxx>
46 #include <StdMeshers_QuadToTriaAdaptor.hxx>
47 #include <StdMeshers_ViscousLayers.hxx>
48
49 #include <BRepGProp.hxx>
50 #include <BRep_Tool.hxx>
51 #include <GProp_GProps.hxx>
52 #include <TopExp.hxx>
53 #include <TopExp_Explorer.hxx>
54 #include <TopTools_ListIteratorOfListOfShape.hxx>
55 #include <TopoDS.hxx>
56
57 #include <Standard_Failure.hxx>
58 #include <Standard_ErrorHandler.hxx>
59
60 #include <utilities.h>
61
62 #include <list>
63 #include <vector>
64 #include <map>
65
66 /*
67   Netgen include files
68 */
69
70 #ifndef OCCGEOMETRY
71 #define OCCGEOMETRY
72 #endif
73 #include <occgeom.hpp>
74 #include <ngexception.hpp>
75 namespace nglib {
76 #include <nglib.h>
77 }
78 namespace netgen {
79 #ifdef NETGEN_V5
80   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, MeshingParameters&, int, int);
81 #else
82   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
83 #endif
84 #if defined(NETGEN_V5) && defined(WIN32)
85   DLL_HEADER 
86 #endif
87 extern MeshingParameters mparam;
88 #if defined(NETGEN_V5) && defined(WIN32)
89   DLL_HEADER
90 #endif
91   extern volatile multithreadt multithread;
92 }
93 using namespace nglib;
94 using namespace std;
95
96 //=============================================================================
97 /*!
98  *  
99  */
100 //=============================================================================
101
102 NETGENPlugin_NETGEN_3D::NETGENPlugin_NETGEN_3D(int hypId, int studyId,
103                              SMESH_Gen* gen)
104   : SMESH_3D_Algo(hypId, studyId, gen)
105 {
106   _name = "NETGEN_3D";
107   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
108   _compatibleHypothesis.push_back("MaxElementVolume");
109   _compatibleHypothesis.push_back("NETGEN_Parameters");
110   _compatibleHypothesis.push_back("ViscousLayers");
111
112   _maxElementVolume = 0.;
113
114   _hypMaxElementVolume = NULL;
115   _hypParameters = NULL;
116   _viscousLayersHyp = NULL;
117
118   _requireShape = false; // can work without shape
119 }
120
121 //=============================================================================
122 /*!
123  *  
124  */
125 //=============================================================================
126
127 NETGENPlugin_NETGEN_3D::~NETGENPlugin_NETGEN_3D()
128 {
129 }
130
131 //=============================================================================
132 /*!
133  *  
134  */
135 //=============================================================================
136
137 bool NETGENPlugin_NETGEN_3D::CheckHypothesis (SMESH_Mesh&         aMesh,
138                                               const TopoDS_Shape& aShape,
139                                               Hypothesis_Status&  aStatus)
140 {
141   _hypMaxElementVolume = NULL;
142   _hypParameters = NULL;
143   _viscousLayersHyp = NULL;
144   _maxElementVolume = DBL_MAX;
145
146   // for correct work of GetProgress():
147   netgen::multithread.percent = 0.;
148   netgen::multithread.task = "Volume meshing";
149   _progressByTic = -1.;
150
151   list<const SMESHDS_Hypothesis*>::const_iterator itl;
152   //const SMESHDS_Hypothesis* theHyp;
153
154   const list<const SMESHDS_Hypothesis*>& hyps =
155     GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
156   list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
157   if ( h == hyps.end())
158   {
159     aStatus = SMESH_Hypothesis::HYP_OK;
160     return true;  // can work with no hypothesis
161   }
162
163   aStatus = HYP_OK;
164   for ( ; h != hyps.end(); ++h )
165   {
166     if ( !_hypMaxElementVolume )
167       _hypMaxElementVolume = dynamic_cast< const StdMeshers_MaxElementVolume*> ( *h );
168     if ( !_viscousLayersHyp ) // several _viscousLayersHyp's allowed
169       _viscousLayersHyp = dynamic_cast< const StdMeshers_ViscousLayers*> ( *h );
170     if ( ! _hypParameters )
171       _hypParameters = dynamic_cast< const NETGENPlugin_Hypothesis*> ( *h );
172
173     if ( *h != _hypMaxElementVolume &&
174          *h != _viscousLayersHyp &&
175          *h != _hypParameters &&
176          !dynamic_cast< const StdMeshers_ViscousLayers*>(*h)) // several VL hyps allowed
177       aStatus = HYP_INCOMPATIBLE;
178   }
179   if ( _hypMaxElementVolume && _hypParameters )
180     aStatus = HYP_INCOMPATIBLE;
181   else if ( aStatus == HYP_OK && _viscousLayersHyp )
182     error( _viscousLayersHyp->CheckHypothesis( aMesh, aShape, aStatus ));
183
184   if ( _hypMaxElementVolume )
185     _maxElementVolume = _hypMaxElementVolume->GetMaxVolume();
186
187   return aStatus == HYP_OK;
188 }
189
190 //=============================================================================
191 /*!
192  *Here we are going to use the NETGEN mesher
193  */
194 //=============================================================================
195
196 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh&         aMesh,
197                                      const TopoDS_Shape& aShape)
198 {
199   netgen::multithread.terminate = 0;
200   netgen::multithread.task = "Volume meshing";
201   _progressByTic = -1.;
202
203   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
204
205   SMESH_MesherHelper helper(aMesh);
206   _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
207   helper.SetElementsOnShape( true );
208
209   int Netgen_NbOfNodes = 0;
210   double Netgen_point[3];
211   int Netgen_triangle[3];
212
213   NETGENPlugin_NetgenLibWrapper ngLib;
214   Ng_Mesh * Netgen_mesh = ngLib._ngMesh;
215
216   // vector of nodes in which node index == netgen ID
217   vector< const SMDS_MeshNode* > nodeVec;
218   {
219     const int invalid_ID = -1;
220
221     SMESH::Controls::Area areaControl;
222     SMESH::Controls::TSequenceOfXYZ nodesCoords;
223
224     // maps nodes to ng ID
225     typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
226     typedef TNodeToIDMap::value_type                     TN2ID;
227     TNodeToIDMap nodeToNetgenID;
228
229     // find internal shapes
230     NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
231
232     // ---------------------------------
233     // Feed the Netgen with surface mesh
234     // ---------------------------------
235
236     TopAbs_ShapeEnum mainType = aMesh.GetShapeToMesh().ShapeType();
237     bool checkReverse = ( mainType == TopAbs_COMPOUND || mainType == TopAbs_COMPSOLID );
238
239     SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
240     if ( _viscousLayersHyp )
241     {
242       netgen::multithread.percent = 3;
243       proxyMesh = _viscousLayersHyp->Compute( aMesh, aShape );
244       if ( !proxyMesh )
245         return false;
246     }
247     if ( aMesh.NbQuadrangles() > 0 )
248     {
249       netgen::multithread.percent = 6;
250       StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
251       Adaptor->Compute(aMesh,aShape,proxyMesh.get());
252       proxyMesh.reset( Adaptor );
253     }
254
255     for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
256     {
257       const TopoDS_Shape& aShapeFace = exFa.Current();
258       int faceID = meshDS->ShapeToIndex( aShapeFace );
259       bool isInternalFace = internals.isInternalShape( faceID );
260       bool isRev = false;
261       if ( checkReverse && !isInternalFace &&
262            helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
263         // IsReversedSubMesh() can work wrong on strongly curved faces,
264         // so we use it as less as possible
265         isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
266
267       const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
268       if ( !aSubMeshDSFace ) continue;
269       SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
270       while ( iteratorElem->more() ) // loop on elements on a geom face
271       {
272         // check mesh face
273         const SMDS_MeshElement* elem = iteratorElem->next();
274         if ( !elem )
275           return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
276         if ( elem->NbCornerNodes() != 3 )
277           return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
278
279         // Add nodes of triangles and triangles them-selves to netgen mesh
280
281         // add three nodes of triangle
282         bool hasDegen = false;
283         for ( int iN = 0; iN < 3; ++iN )
284         {
285           const SMDS_MeshNode* node = elem->GetNode( iN );
286           const int shapeID = node->getshapeId();
287           if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE &&
288                helper.IsDegenShape( shapeID ))
289           {
290             // ignore all nodes on degeneraged edge and use node on its vertex instead
291             TopoDS_Shape vertex = TopoDS_Iterator( meshDS->IndexToShape( shapeID )).Value();
292             node = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), meshDS );
293             hasDegen = true;
294           }
295           int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
296           if ( ngID == invalid_ID )
297           {
298             ngID = ++Netgen_NbOfNodes;
299             Netgen_point [ 0 ] = node->X();
300             Netgen_point [ 1 ] = node->Y();
301             Netgen_point [ 2 ] = node->Z();
302             Ng_AddPoint(Netgen_mesh, Netgen_point);
303           }
304           Netgen_triangle[ isRev ? 2-iN : iN ] = ngID;
305         }
306         // add triangle
307         if ( hasDegen && (Netgen_triangle[0] == Netgen_triangle[1] ||
308                           Netgen_triangle[0] == Netgen_triangle[2] ||
309                           Netgen_triangle[2] == Netgen_triangle[1] ))
310           continue;
311
312         Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
313
314         if ( isInternalFace && !proxyMesh->IsTemporary( elem ))
315         {
316           swap( Netgen_triangle[1], Netgen_triangle[2] );
317           Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
318         }
319       } // loop on elements on a face
320     } // loop on faces of a SOLID or SHELL
321
322     // insert old nodes into nodeVec
323     nodeVec.resize( nodeToNetgenID.size() + 1, 0 );
324     TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
325     for ( ; n_id != nodeToNetgenID.end(); ++n_id )
326       nodeVec[ n_id->second ] = n_id->first;
327     nodeToNetgenID.clear();
328
329     if ( internals.hasInternalVertexInSolid() )
330     {
331       netgen::OCCGeometry occgeo;
332       NETGENPlugin_Mesher::AddIntVerticesInSolids( occgeo,
333                                                    (netgen::Mesh&) *Netgen_mesh,
334                                                    nodeVec,
335                                                    internals);
336     }
337   }
338
339   // -------------------------
340   // Generate the volume mesh
341   // -------------------------
342
343   return ( ngLib._isComputeOk = compute( aMesh, helper, nodeVec, Netgen_mesh));
344 }
345
346 // namespace
347 // {
348 //   void limitVolumeSize( netgen::Mesh* ngMesh,
349 //                         double        maxh )
350 //   {
351 //     // get average h of faces
352 //     double faceh = 0;
353 //     int nbh = 0;
354 //     for (int i = 1; i <= ngMesh->GetNSE(); i++)
355 //     {
356 //       const netgen::Element2d& face = ngMesh->SurfaceElement(i);
357 //       for (int j=1; j <= face.GetNP(); ++j)
358 //       {
359 //         const netgen::PointIndex & i1 = face.PNumMod(j);
360 //         const netgen::PointIndex & i2 = face.PNumMod(j+1);
361 //         if ( i1 < i2 )
362 //         {
363 //           const netgen::Point3d & p1 = ngMesh->Point( i1 );
364 //           const netgen::Point3d & p2 = ngMesh->Point( i2 );
365 //           faceh += netgen::Dist2( p1, p2 );
366 //           nbh++;
367 //         }
368 //       }
369 //     }
370 //     faceh = Sqrt( faceh / nbh );
371
372 //     double compareh;
373 //     if      ( faceh < 0.5 * maxh ) compareh = -1;
374 //     else if ( faceh > 1.5 * maxh ) compareh = 1;
375 //     else                           compareh = 0;
376 //     // cerr << "faceh " << faceh << endl;
377 //     // cerr << "init maxh " << maxh << endl;
378 //     // cerr << "compareh " << compareh << endl;
379
380 //     if ( compareh > 0 )
381 //       maxh *= 1.2;
382 //     else
383 //       maxh *= 0.8;
384 //     // cerr << "maxh " << maxh << endl;
385
386 //     // get bnd box
387 //     netgen::Point3d pmin, pmax;
388 //     ngMesh->GetBox( pmin, pmax, 0 );
389 //     const double dx = pmax.X() - pmin.X();
390 //     const double dy = pmax.Y() - pmin.Y();
391 //     const double dz = pmax.Z() - pmin.Z();
392
393 //     if ( ! & ngMesh->LocalHFunction() )
394 //       ngMesh->SetLocalH( pmin, pmax, compareh <= 0 ? 0.1 : 0.5 );
395
396 //     // adjusted by SALOME_TESTS/Grids/smesh/bugs_08/I8
397 //     const int nbX = Max( 2, int( dx / maxh * 2 ));
398 //     const int nbY = Max( 2, int( dy / maxh * 2 ));
399 //     const int nbZ = Max( 2, int( dz / maxh * 2 ));
400
401 //     netgen::Point3d p;
402 //     for ( int i = 0; i <= nbX; ++i )
403 //     {
404 //       p.X() = pmin.X() +  i * dx / nbX;
405 //       for ( int j = 0; j <= nbY; ++j )
406 //       {
407 //         p.Y() = pmin.Y() +  j * dy / nbY;
408 //         for ( int k = 0; k <= nbZ; ++k )
409 //         {
410 //           p.Z() = pmin.Z() +  k * dz / nbZ;
411 //           ngMesh->RestrictLocalH( p, maxh );
412 //         }
413 //       }
414 //     }
415 //   }
416 // }
417
418 //================================================================================
419 /*!
420  * \brief set parameters and generate the volume mesh
421  */
422 //================================================================================
423
424 bool NETGENPlugin_NETGEN_3D::compute(SMESH_Mesh&                     aMesh,
425                                      SMESH_MesherHelper&             helper,
426                                      vector< const SMDS_MeshNode* >& nodeVec,
427                                      Ng_Mesh *                       Netgen_mesh)
428 {
429   netgen::multithread.terminate = 0;
430
431   netgen::Mesh* ngMesh = (netgen::Mesh*)Netgen_mesh;
432   int Netgen_NbOfNodes = Ng_GetNP(Netgen_mesh);
433
434 #ifndef NETGEN_V5
435   char *optstr = 0;
436 #endif
437   int startWith = netgen::MESHCONST_MESHVOLUME;
438   int endWith   = netgen::MESHCONST_OPTVOLUME;
439   int err = 1;
440
441   NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
442   netgen::OCCGeometry occgeo;
443
444   if ( _hypParameters )
445   {
446     aMesher.SetParameters( _hypParameters );
447
448     if ( !_hypParameters->GetLocalSizesAndEntries().empty() ||
449          !_hypParameters->GetMeshSizeFile().empty() )
450     {
451       if ( ! &ngMesh->LocalHFunction() )
452       {
453         netgen::Point3d pmin, pmax;
454         ngMesh->GetBox( pmin, pmax, 0 );
455         ngMesh->SetLocalH( pmin, pmax, _hypParameters->GetGrowthRate() );
456       }
457       aMesher.SetLocalSize( occgeo, *ngMesh );
458
459       try {
460         ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
461       } catch (netgen::NgException & ex) {
462         return error( COMPERR_BAD_PARMETERS, ex.What() );
463       }
464     }
465     if ( !_hypParameters->GetOptimize() )
466       endWith = netgen::MESHCONST_MESHVOLUME;
467   }
468   else if ( _hypMaxElementVolume )
469   {
470     netgen::mparam.maxh = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
471     // limitVolumeSize( ngMesh, netgen::mparam.maxh ); // result is unpredictable
472   }
473   else if ( aMesh.HasShapeToMesh() )
474   {
475     aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
476     netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
477   }
478   else
479   {
480     netgen::Point3d pmin, pmax;
481     ngMesh->GetBox (pmin, pmax);
482     netgen::mparam.maxh = Dist(pmin, pmax)/2;
483   }
484
485   if ( !_hypParameters && aMesh.HasShapeToMesh() )
486   {
487     netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
488   }
489
490   try
491   {
492     OCC_CATCH_SIGNALS;
493
494 #ifdef NETGEN_V5
495     ngMesh->CalcLocalH(netgen::mparam.grading);
496     err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
497 #else
498     ngMesh->CalcLocalH();
499     err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
500 #endif
501     if(netgen::multithread.terminate)
502       return false;
503     if ( err )
504       error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
505   }
506   catch (Standard_Failure& ex)
507   {
508     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
509     str << " at " << netgen::multithread.task
510         << ": " << ex.DynamicType()->Name();
511     if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
512       str << ": " << ex.GetMessageString();
513     error(str);
514   }
515   catch (netgen::NgException exc)
516   {
517     SMESH_Comment str("NgException");
518     if ( strlen( netgen::multithread.task ) > 0 )
519       str << " at " << netgen::multithread.task;
520     str << ": " << exc.What();
521     error(str);
522   }
523   catch (...)
524   {
525     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
526     if ( strlen( netgen::multithread.task ) > 0 )
527       str << " at " << netgen::multithread.task;
528     error(str);
529   }
530
531   int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
532   int Netgen_NbOfTetra    = Ng_GetNE(Netgen_mesh);
533
534   MESSAGE("End of Volume Mesh Generation. err=" << err <<
535           ", nb new nodes: " << Netgen_NbOfNodesNew - Netgen_NbOfNodes <<
536           ", nb tetra: " << Netgen_NbOfTetra);
537
538   // -------------------------------------------------------------------
539   // Feed back the SMESHDS with the generated Nodes and Volume Elements
540   // -------------------------------------------------------------------
541
542   if ( err )
543   {
544     SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
545     if ( ce && !ce->myBadElements.empty() )
546       error( ce );
547   }
548
549   bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
550   if ( isOK )
551   {
552     double Netgen_point[3];
553     int    Netgen_tetrahedron[4];
554
555     // create and insert new nodes into nodeVec
556     nodeVec.resize( Netgen_NbOfNodesNew + 1, 0 );
557     int nodeIndex = Netgen_NbOfNodes + 1;
558     for ( ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
559     {
560       Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
561       nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0], Netgen_point[1], Netgen_point[2]);
562     }
563
564     // create tetrahedrons
565     for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
566     {
567       Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
568       try
569       {
570         helper.AddVolume (nodeVec.at( Netgen_tetrahedron[0] ),
571                           nodeVec.at( Netgen_tetrahedron[1] ),
572                           nodeVec.at( Netgen_tetrahedron[2] ),
573                           nodeVec.at( Netgen_tetrahedron[3] ));
574       }
575       catch (...)
576       {
577       }
578     }
579   }
580
581   return !err;
582 }
583
584 //================================================================================
585 /*!
586  * \brief Compute tetrahedral mesh from 2D mesh without geometry
587  */
588 //================================================================================
589
590 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh&         aMesh,
591                                      SMESH_MesherHelper* aHelper)
592 {
593   const int invalid_ID = -1;
594
595   netgen::multithread.terminate = 0;
596   _progressByTic = -1.;
597
598   SMESH_MesherHelper::MType MeshType = aHelper->IsQuadraticMesh();
599   if ( MeshType == SMESH_MesherHelper::COMP )
600     return error( COMPERR_BAD_INPUT_MESH,
601                   SMESH_Comment("Mesh with linear and quadratic elements given"));
602
603   aHelper->SetIsQuadratic( MeshType == SMESH_MesherHelper::QUADRATIC );
604
605   // ---------------------------------
606   // Feed the Netgen with surface mesh
607   // ---------------------------------
608
609   int Netgen_NbOfNodes = 0;
610   double Netgen_point[3];
611   int Netgen_triangle[3];
612
613   NETGENPlugin_NetgenLibWrapper ngLib;
614   Ng_Mesh * Netgen_mesh = ngLib._ngMesh;
615
616   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
617   if ( aMesh.NbQuadrangles() > 0 )
618   {
619     StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
620     Adaptor->Compute(aMesh);
621     proxyMesh.reset( Adaptor );
622   }
623
624   // maps nodes to ng ID
625   typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
626   typedef TNodeToIDMap::value_type                     TN2ID;
627   TNodeToIDMap nodeToNetgenID;
628
629   SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
630   while( fIt->more())
631   {
632     // check element
633     const SMDS_MeshElement* elem = fIt->next();
634     if ( !elem )
635       return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
636     if ( elem->NbCornerNodes() != 3 )
637       return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
638       
639     // add three nodes of triangle
640     for ( int iN = 0; iN < 3; ++iN )
641     {
642       const SMDS_MeshNode* node = elem->GetNode( iN );
643       int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
644       if ( ngID == invalid_ID )
645       {
646         ngID = ++Netgen_NbOfNodes;
647         Netgen_point [ 0 ] = node->X();
648         Netgen_point [ 1 ] = node->Y();
649         Netgen_point [ 2 ] = node->Z();
650         Ng_AddPoint(Netgen_mesh, Netgen_point);
651       }
652       Netgen_triangle[ iN ] = ngID;
653     }
654     Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
655   }
656   proxyMesh.reset(); // delete tmp faces
657
658   // vector of nodes in which node index == netgen ID
659   vector< const SMDS_MeshNode* > nodeVec ( nodeToNetgenID.size() + 1 );
660   // insert old nodes into nodeVec
661   TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
662   for ( ; n_id != nodeToNetgenID.end(); ++n_id )
663     nodeVec.at( n_id->second ) = n_id->first;
664   nodeToNetgenID.clear();
665
666   // -------------------------
667   // Generate the volume mesh
668   // -------------------------
669
670   return ( ngLib._isComputeOk = compute( aMesh, *aHelper, nodeVec, Netgen_mesh));
671 }
672
673 void NETGENPlugin_NETGEN_3D::CancelCompute()
674 {
675   SMESH_Algo::CancelCompute();
676   netgen::multithread.terminate = 1;
677 }
678
679 //================================================================================
680 /*!
681  * \brief Return Compute progress
682  */
683 //================================================================================
684
685 double NETGENPlugin_NETGEN_3D::GetProgress() const
686 {
687   double res;
688   const char* volMeshing = "Volume meshing";
689   const char* dlnMeshing = "Delaunay meshing";
690   const double meshingRatio = 0.15;
691   const_cast<NETGENPlugin_NETGEN_3D*>( this )->_progressTic++;
692
693   if ( _progressByTic < 0. &&
694        ( strncmp( netgen::multithread.task, dlnMeshing, 3 ) == 0 ||
695          strncmp( netgen::multithread.task, volMeshing, 3 ) == 0 ))
696   {
697     res = 0.001 + meshingRatio * netgen::multithread.percent / 100.;
698     //cout << netgen::multithread.task << " " <<_progressTic << "-" << netgen::multithread.percent << endl;
699   }
700   else // different otimizations
701   {
702     if ( _progressByTic < 0. )
703       ((NETGENPlugin_NETGEN_3D*)this)->_progressByTic = meshingRatio / _progressTic;
704     res = _progressByTic * _progressTic;
705     //cout << netgen::multithread.task << " " << _progressTic << " " << res << endl;
706   }
707   return Min ( res, 0.98 );
708 }
709
710 //=============================================================================
711 /*!
712  *
713  */
714 //=============================================================================
715
716 bool NETGENPlugin_NETGEN_3D::Evaluate(SMESH_Mesh& aMesh,
717                                       const TopoDS_Shape& aShape,
718                                       MapShapeNbElems& aResMap)
719 {
720   int nbtri = 0, nbqua = 0;
721   double fullArea = 0.0;
722   for (TopExp_Explorer expF(aShape, TopAbs_FACE); expF.More(); expF.Next()) {
723     TopoDS_Face F = TopoDS::Face( expF.Current() );
724     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
725     MapShapeNbElemsItr anIt = aResMap.find(sm);
726     if( anIt==aResMap.end() ) {
727       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
728       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
729       return false;
730     }
731     std::vector<int> aVec = (*anIt).second;
732     nbtri += Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
733     nbqua += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
734     GProp_GProps G;
735     BRepGProp::SurfaceProperties(F,G);
736     double anArea = G.Mass();
737     fullArea += anArea;
738   }
739
740   // collect info from edges
741   int nb0d_e = 0, nb1d_e = 0;
742   bool IsQuadratic = false;
743   bool IsFirst = true;
744   TopTools_MapOfShape tmpMap;
745   for (TopExp_Explorer expF(aShape, TopAbs_EDGE); expF.More(); expF.Next()) {
746     TopoDS_Edge E = TopoDS::Edge(expF.Current());
747     if( tmpMap.Contains(E) )
748       continue;
749     tmpMap.Add(E);
750     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(expF.Current());
751     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
752     if( anIt==aResMap.end() ) {
753       SMESH_ComputeErrorPtr& smError = aSubMesh->GetComputeError();
754       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
755                                             "Submesh can not be evaluated",this));
756       return false;
757     }
758     std::vector<int> aVec = (*anIt).second;
759     nb0d_e += aVec[SMDSEntity_Node];
760     nb1d_e += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
761     if(IsFirst) {
762       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
763       IsFirst = false;
764     }
765   }
766   tmpMap.Clear();
767
768   double ELen_face = sqrt(2.* ( fullArea/(nbtri+nbqua*2) ) / sqrt(3.0) );
769   double ELen_vol = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
770   double ELen = Min(ELen_vol,ELen_face*2);
771
772   GProp_GProps G;
773   BRepGProp::VolumeProperties(aShape,G);
774   double aVolume = G.Mass();
775   double tetrVol = 0.1179*ELen*ELen*ELen;
776   double CoeffQuality = 0.9;
777   int nbVols = int( aVolume/tetrVol/CoeffQuality );
778   int nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
779   int nb1d_in = (nbVols*6 - nb1d_e - nb1d_f ) / 5;
780   std::vector<int> aVec(SMDSEntity_Last);
781   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
782   if( IsQuadratic ) {
783     aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
784     aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
785     aVec[SMDSEntity_Quad_Pyramid] = nbqua;
786   }
787   else {
788     aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
789     aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
790     aVec[SMDSEntity_Pyramid] = nbqua;
791   }
792   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
793   aResMap.insert(std::make_pair(sm,aVec));
794   
795   return true;
796 }
797
798