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