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