Salome HOME
cout replaced by MESSAGE + clean up
[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 // TODO: remove use of netgen_param
36 #include "NETGENPlugin_DriverParam.hxx"
37
38 #include <SMDS_MeshElement.hxx>
39 #include <SMDS_MeshNode.hxx>
40 #include <SMESHDS_Mesh.hxx>
41 #include <SMESH_Comment.hxx>
42 #include <SMESH_ControlsDef.hxx>
43 #include <SMESH_Gen.hxx>
44 #include <SMESH_Mesh.hxx>
45 #include <SMESH_MeshEditor.hxx>
46 #include <SMESH_MesherHelper.hxx>
47 #include <SMESH_subMesh.hxx>
48 #include <StdMeshers_MaxElementVolume.hxx>
49 #include <StdMeshers_QuadToTriaAdaptor.hxx>
50 #include <StdMeshers_ViscousLayers.hxx>
51 #include <SMESH_subMesh.hxx>
52
53
54 #include <BRepGProp.hxx>
55 #include <BRep_Tool.hxx>
56 #include <GProp_GProps.hxx>
57 #include <TopExp.hxx>
58 #include <TopExp_Explorer.hxx>
59 #include <TopTools_ListIteratorOfListOfShape.hxx>
60 #include <TopoDS.hxx>
61
62 #include <Standard_Failure.hxx>
63 #include <Standard_ErrorHandler.hxx>
64
65 #include <utilities.h>
66
67 #include <list>
68 #include <vector>
69 #include <map>
70
71 #include <cstdlib>
72
73 /*
74   Netgen include files
75 */
76
77 #ifndef OCCGEOMETRY
78 #define OCCGEOMETRY
79 #endif
80 #include <occgeom.hpp>
81
82 #ifdef NETGEN_V5
83 #include <ngexception.hpp>
84 #endif
85 #ifdef NETGEN_V6
86 #include <core/exception.hpp>
87 #endif
88
89 namespace nglib {
90 #include <nglib.h>
91 }
92 namespace netgen {
93
94   NETGENPLUGIN_DLL_HEADER
95   extern MeshingParameters mparam;
96
97   NETGENPLUGIN_DLL_HEADER
98   extern volatile multithreadt multithread;
99 }
100 using namespace nglib;
101 using namespace std;
102
103 //=============================================================================
104 /*!
105  *
106  */
107 //=============================================================================
108
109 NETGENPlugin_NETGEN_3D::NETGENPlugin_NETGEN_3D(int hypId, SMESH_Gen* gen)
110   : SMESH_3D_Algo(hypId, gen)
111 {
112   _name = "NETGEN_3D";
113   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
114   _compatibleHypothesis.push_back("MaxElementVolume");
115   _compatibleHypothesis.push_back("NETGEN_Parameters");
116   _compatibleHypothesis.push_back("ViscousLayers");
117
118   _maxElementVolume = 0.;
119
120   _hypMaxElementVolume = NULL;
121   _hypParameters = NULL;
122   _viscousLayersHyp = NULL;
123
124   _requireShape = false; // can work without shape
125 }
126
127 //=============================================================================
128 /*!
129  *
130  */
131 //=============================================================================
132
133 NETGENPlugin_NETGEN_3D::~NETGENPlugin_NETGEN_3D()
134 {
135 }
136
137 //=============================================================================
138 /*!
139  *
140  */
141 //=============================================================================
142
143 bool NETGENPlugin_NETGEN_3D::CheckHypothesis (SMESH_Mesh&         aMesh,
144                                               const TopoDS_Shape& aShape,
145                                               Hypothesis_Status&  aStatus)
146 {
147   _hypMaxElementVolume = NULL;
148   _hypParameters = NULL;
149   _viscousLayersHyp = NULL;
150   _maxElementVolume = DBL_MAX;
151
152   // for correct work of GetProgress():
153   //netgen::multithread.percent = 0.;
154   //netgen::multithread.task = "Volume meshing";
155   _progressByTic = -1.;
156
157   list<const SMESHDS_Hypothesis*>::const_iterator itl;
158   //const SMESHDS_Hypothesis* theHyp;
159
160   const list<const SMESHDS_Hypothesis*>& hyps =
161     GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
162   list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
163   if ( h == hyps.end())
164   {
165     aStatus = SMESH_Hypothesis::HYP_OK;
166     return true;  // can work with no hypothesis
167   }
168
169   aStatus = HYP_OK;
170   for ( ; h != hyps.end(); ++h )
171   {
172     if ( !_hypMaxElementVolume )
173       _hypMaxElementVolume = dynamic_cast< const StdMeshers_MaxElementVolume*> ( *h );
174     if ( !_viscousLayersHyp ) // several _viscousLayersHyp's allowed
175       _viscousLayersHyp = dynamic_cast< const StdMeshers_ViscousLayers*> ( *h );
176     if ( ! _hypParameters )
177       _hypParameters = dynamic_cast< const NETGENPlugin_Hypothesis*> ( *h );
178
179     if ( *h != _hypMaxElementVolume &&
180          *h != _viscousLayersHyp &&
181          *h != _hypParameters &&
182          !dynamic_cast< const StdMeshers_ViscousLayers*>(*h)) // several VL hyps allowed
183       aStatus = HYP_INCOMPATIBLE;
184   }
185   if ( _hypMaxElementVolume && _hypParameters )
186     aStatus = HYP_INCOMPATIBLE;
187   else if ( aStatus == HYP_OK && _viscousLayersHyp )
188     error( _viscousLayersHyp->CheckHypothesis( aMesh, aShape, aStatus ));
189
190   if ( _hypMaxElementVolume )
191     _maxElementVolume = _hypMaxElementVolume->GetMaxVolume();
192
193   return aStatus == HYP_OK;
194 }
195
196
197
198 //=============================================================================
199 /*!
200  *Here we are going to use the NETGEN mesher
201  */
202 //=============================================================================
203
204 /**
205  * @brief Get an iterator on the Surface element with their orientation
206  *
207  */
208
209 bool NETGENPlugin_NETGEN_3D::getSurfaceElements(
210     SMESH_Mesh&         aMesh,
211     const TopoDS_Shape& aShape,
212     SMESH_ProxyMesh::Ptr proxyMesh,
213     NETGENPlugin_Internals &internals,
214     SMESH_MesherHelper &helper,
215     netgen_params &aParams,
216     std::map<const SMDS_MeshElement*, tuple<bool, bool>>& listElements
217 )
218 {
219   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
220   TopAbs_ShapeEnum mainType = aMesh.GetShapeToMesh().ShapeType();
221   bool checkReverse = ( mainType == TopAbs_COMPOUND || mainType == TopAbs_COMPSOLID );
222
223   for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
224   {
225     const TopoDS_Shape& aShapeFace = exFa.Current();
226     int faceID = meshDS->ShapeToIndex( aShapeFace );
227     bool isInternalFace = internals.isInternalShape( faceID );
228     bool isRev = false;
229     if ( checkReverse && !isInternalFace &&
230           helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
231       // IsReversedSubMesh() can work wrong on strongly curved faces,
232       // so we use it as less as possible
233       isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
234
235     const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
236     if ( !aSubMeshDSFace ) continue;
237
238     SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
239     if ( aParams._quadraticMesh &&
240           dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
241     {
242       // add medium nodes of proxy triangles to helper (#16843)
243       while ( iteratorElem->more() )
244         helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
245
246       iteratorElem = aSubMeshDSFace->GetElements();
247     }
248     while(iteratorElem->more()){
249       const SMDS_MeshElement* elem = iteratorElem->next();
250       // check mesh face
251       if ( !elem ){
252         aParams._error = COMPERR_BAD_INPUT_MESH;
253         aParams._comment = "Null element encounters";
254         return true;
255       }
256       if ( elem->NbCornerNodes() != 3 ){
257         aParams._error = COMPERR_BAD_INPUT_MESH;
258         aParams._comment = "Not triangle element encounters";
259         return true;
260       }
261       listElements[elem] = tuple(isRev, isInternalFace);
262     }
263   }
264
265   return false;
266 }
267
268
269 bool NETGENPlugin_NETGEN_3D::computeFillNgMesh(
270   SMESH_Mesh&         aMesh,
271   const TopoDS_Shape& aShape,
272   vector< const SMDS_MeshNode* > &nodeVec,
273   NETGENPlugin_NetgenLibWrapper &ngLib,
274   SMESH_MesherHelper &helper,
275   netgen_params &aParams,
276   int &Netgen_NbOfNodes)
277 {
278   netgen::multithread.terminate = 0;
279   netgen::multithread.task = "Volume meshing";
280   aParams._progressByTic = -1.;
281
282   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
283
284   aParams._quadraticMesh = helper.IsQuadraticSubMesh(aShape);
285   helper.SetElementsOnShape( true );
286
287   Netgen_NbOfNodes = 0;
288   double Netgen_point[3];
289   int Netgen_triangle[3];
290
291   Ng_Mesh * Netgen_mesh = (Ng_Mesh*)ngLib._ngMesh;
292
293   {
294     const int invalid_ID = -1;
295
296     SMESH::Controls::Area areaControl;
297     SMESH::Controls::TSequenceOfXYZ nodesCoords;
298
299     // maps nodes to ng ID
300     typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
301     typedef TNodeToIDMap::value_type                     TN2ID;
302     TNodeToIDMap nodeToNetgenID;
303
304     // find internal shapes
305     NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
306
307     // ---------------------------------
308     // Feed the Netgen with surface mesh
309     // ---------------------------------
310     bool isRev=false;
311     bool isInternalFace=false;
312
313     SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
314     if ( aParams._viscousLayersHyp )
315     {
316       netgen::multithread.percent = 3;
317       proxyMesh = aParams._viscousLayersHyp->Compute( aMesh, aShape );
318       if ( !proxyMesh )
319         return false;
320     }
321     if ( aMesh.NbQuadrangles() > 0 )
322     {
323       netgen::multithread.percent = 6;
324       StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
325       Adaptor->Compute(aMesh,aShape,proxyMesh.get());
326       proxyMesh.reset( Adaptor );
327     }
328
329     std::map<const SMDS_MeshElement*, tuple<bool, bool>> listElements;
330     bool ret = getSurfaceElements(aMesh, aShape, proxyMesh, internals, helper, aParams, listElements);
331     if(ret)
332       return ret;
333
334     for ( auto const& [elem, info] : listElements ) // loop on elements on a geom face
335     {
336       isRev = get<0>(info);
337       isInternalFace = get<1>(info);
338       // Add nodes of triangles and triangles them-selves to netgen mesh
339
340       // add three nodes of triangle
341       bool hasDegen = false;
342       for ( int iN = 0; iN < 3; ++iN )
343       {
344         const SMDS_MeshNode* node = elem->GetNode( iN );
345         const int shapeID = node->getshapeId();
346         if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE &&
347               helper.IsDegenShape( shapeID ))
348         {
349           // ignore all nodes on degeneraged edge and use node on its vertex instead
350           TopoDS_Shape vertex = TopoDS_Iterator( meshDS->IndexToShape( shapeID )).Value();
351           node = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), meshDS );
352           hasDegen = true;
353         }
354         int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
355         if ( ngID == invalid_ID )
356         {
357           ngID = ++Netgen_NbOfNodes;
358           Netgen_point [ 0 ] = node->X();
359           Netgen_point [ 1 ] = node->Y();
360           Netgen_point [ 2 ] = node->Z();
361           Ng_AddPoint(Netgen_mesh, Netgen_point);
362         }
363         Netgen_triangle[ isRev ? 2-iN : iN ] = ngID;
364       }
365       // add triangle
366       if ( hasDegen && (Netgen_triangle[0] == Netgen_triangle[1] ||
367                         Netgen_triangle[0] == Netgen_triangle[2] ||
368                         Netgen_triangle[2] == Netgen_triangle[1] ))
369         continue;
370
371       Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
372
373       if ( isInternalFace && !proxyMesh->IsTemporary( elem ))
374       {
375         swap( Netgen_triangle[1], Netgen_triangle[2] );
376         Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
377       }
378     } // loop on elements on a face
379
380     // insert old nodes into nodeVec
381     nodeVec.resize( nodeToNetgenID.size() + 1, 0 );
382     TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
383     for ( ; n_id != nodeToNetgenID.end(); ++n_id )
384       nodeVec[ n_id->second ] = n_id->first;
385     nodeToNetgenID.clear();
386
387     if ( internals.hasInternalVertexInSolid() )
388     {
389       netgen::OCCGeometry occgeo;
390       NETGENPlugin_Mesher::AddIntVerticesInSolids( occgeo,
391                                                    (netgen::Mesh&) *Netgen_mesh,
392                                                    nodeVec,
393                                                    internals);
394     }
395   }
396   Netgen_NbOfNodes = Ng_GetNP( Netgen_mesh );
397   return false;
398 }
399
400 bool NETGENPlugin_NETGEN_3D::computePrepareParam(
401   SMESH_Mesh&         aMesh,
402   NETGENPlugin_NetgenLibWrapper &ngLib,
403   netgen::OCCGeometry &occgeo,
404   SMESH_MesherHelper &helper,
405   netgen_params &aParams,
406   int &endWith)
407
408 {
409   netgen::multithread.terminate = 0;
410
411   netgen::Mesh* ngMesh = ngLib._ngMesh;
412
413   NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
414
415
416   if ( aParams._hypParameters )
417   {
418     aMesher.SetParameters( aParams._hypParameters );
419
420     if ( !aParams._hypParameters->GetLocalSizesAndEntries().empty() ||
421          !aParams._hypParameters->GetMeshSizeFile().empty() )
422     {
423       if ( ! &ngMesh->LocalHFunction() )
424       {
425         netgen::Point3d pmin, pmax;
426         ngMesh->GetBox( pmin, pmax, 0 );
427         ngMesh->SetLocalH( pmin, pmax, aParams._hypParameters->GetGrowthRate() );
428       }
429       aMesher.SetLocalSize( occgeo, *ngMesh );
430
431       try {
432         ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
433       } catch (netgen::NgException & ex) {
434         aParams._error = COMPERR_BAD_PARMETERS;
435         aParams._comment = ex.What();
436         return false;
437       }
438     }
439     if ( !aParams._hypParameters->GetOptimize() )
440       endWith = netgen::MESHCONST_MESHVOLUME;
441   }
442   else if ( aParams._hypMaxElementVolume )
443   {
444     netgen::mparam.maxh = pow( 72, 1/6. ) * pow( aParams.maxElementVolume, 1/3. );
445     // limitVolumeSize( ngMesh, mparam.maxh ); // result is unpredictable
446   }
447   else if ( aMesh.HasShapeToMesh() )
448   {
449     aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
450     netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
451   }
452   else
453   {
454     netgen::Point3d pmin, pmax;
455     ngMesh->GetBox (pmin, pmax);
456     netgen::mparam.maxh = Dist(pmin, pmax)/2;
457   }
458
459   if ( !aParams._hypParameters && aMesh.HasShapeToMesh() )
460   {
461     netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
462   }
463   return false;
464 }
465
466 bool NETGENPlugin_NETGEN_3D::computeRunMesher(
467   netgen::OCCGeometry &occgeo,
468   vector< const SMDS_MeshNode* > &nodeVec,
469   netgen::Mesh* ngMesh,
470   NETGENPlugin_NetgenLibWrapper &ngLib,
471   netgen_params &aParams,
472   int &startWith, int &endWith)
473 {
474   int err = 1;
475
476   try
477   {
478     OCC_CATCH_SIGNALS;
479
480     ngLib.CalcLocalH(ngMesh);
481     err = ngLib.GenerateMesh(occgeo, startWith, endWith);
482
483     if(netgen::multithread.terminate)
484       return false;
485     if ( err ){
486       aParams._comment = SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
487       return true;
488     }
489   }
490   catch (Standard_Failure& ex)
491   {
492     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
493     str << " at " << netgen::multithread.task
494         << ": " << ex.DynamicType()->Name();
495     if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
496       str << ": " << ex.GetMessageString();
497     aParams._comment = str;
498     return true;
499   }
500   catch (netgen::NgException& exc)
501   {
502     SMESH_Comment str("NgException");
503     if ( strlen( netgen::multithread.task ) > 0 )
504       str << " at " << netgen::multithread.task;
505     str << ": " << exc.What();
506     aParams._comment = str;
507     return true;
508   }
509   catch (...)
510   {
511     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
512     if ( strlen( netgen::multithread.task ) > 0 )
513       str << " at " << netgen::multithread.task;
514     aParams._comment = str;
515     return true;
516   }
517
518   if ( err )
519   {
520     SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
521     if ( ce && ce->HasBadElems() ){
522       aParams._error = ce->myName;
523       aParams._comment = ce->myComment;
524       return true;
525     }
526   }
527
528   return false;
529 }
530
531 bool NETGENPlugin_NETGEN_3D::computeFillMesh(
532   vector< const SMDS_MeshNode* > &nodeVec,
533   NETGENPlugin_NetgenLibWrapper &ngLib,
534   SMESH_MesherHelper &helper,
535   int &Netgen_NbOfNodes
536   )
537 {
538   Ng_Mesh* Netgen_mesh = ngLib.ngMesh();
539
540   int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
541   int Netgen_NbOfTetra    = Ng_GetNE(Netgen_mesh);
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   return false;
575 }
576
577 bool NETGENPlugin_NETGEN_3D::Compute(
578   SMESH_Mesh&         aMesh,
579   const TopoDS_Shape& aShape)
580 {
581   // vector of nodes in which node index == netgen ID
582   vector< const SMDS_MeshNode* > nodeVec;
583   NETGENPlugin_NetgenLibWrapper ngLib;
584   SMESH_MesherHelper helper(aMesh);
585   int startWith = netgen::MESHCONST_MESHVOLUME;
586   int endWith   = netgen::MESHCONST_OPTVOLUME;
587   int Netgen_NbOfNodes;
588
589   netgen_params aParams;
590
591   aParams._hypParameters = const_cast<NETGENPlugin_Hypothesis*>(_hypParameters);
592   aParams._hypMaxElementVolume = const_cast<StdMeshers_MaxElementVolume*>(_hypMaxElementVolume);
593   aParams.maxElementVolume = _maxElementVolume;
594   aParams._progressByTic = _progressByTic;
595   aParams._quadraticMesh = _quadraticMesh;
596   aParams._viscousLayersHyp = const_cast<StdMeshers_ViscousLayers*>(_viscousLayersHyp);
597
598   bool ret;
599   ret = computeFillNgMesh(aMesh, aShape, nodeVec, ngLib, helper, aParams, Netgen_NbOfNodes);
600   if(ret)
601     return error( aParams._error, aParams._comment);
602
603   netgen::OCCGeometry occgeo;
604   computePrepareParam(aMesh, ngLib, occgeo, helper, aParams, endWith);
605   ret = computeRunMesher(occgeo, nodeVec, ngLib._ngMesh, ngLib, aParams, startWith, endWith);
606   if(ret){
607     if(aParams._error)
608       return error(aParams._error, aParams._comment);
609
610     error(aParams._comment);
611     return true;
612   }
613   computeFillMesh(nodeVec, ngLib, helper, Netgen_NbOfNodes);
614
615   return false;
616
617 }
618
619 //================================================================================
620 /*!
621  * \brief set parameters and generate the volume mesh
622  */
623 //================================================================================
624
625 bool NETGENPlugin_NETGEN_3D::compute(SMESH_Mesh&                     aMesh,
626                                      SMESH_MesherHelper&             helper,
627                                      vector< const SMDS_MeshNode* >& nodeVec,
628                                      NETGENPlugin_NetgenLibWrapper&  ngLib)
629 {
630   netgen::multithread.terminate = 0;
631
632   netgen::Mesh* ngMesh = ngLib._ngMesh;
633   Ng_Mesh* Netgen_mesh = ngLib.ngMesh();
634   int Netgen_NbOfNodes = Ng_GetNP( Netgen_mesh );
635
636   int startWith = netgen::MESHCONST_MESHVOLUME;
637   int endWith   = netgen::MESHCONST_OPTVOLUME;
638   int err = 1;
639
640   NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
641   netgen::OCCGeometry occgeo;
642
643   if ( _hypParameters )
644   {
645     aMesher.SetParameters( _hypParameters );
646
647     if ( !_hypParameters->GetLocalSizesAndEntries().empty() ||
648          !_hypParameters->GetMeshSizeFile().empty() )
649     {
650       if ( ! &ngMesh->LocalHFunction() )
651       {
652         netgen::Point3d pmin, pmax;
653         ngMesh->GetBox( pmin, pmax, 0 );
654         ngMesh->SetLocalH( pmin, pmax, _hypParameters->GetGrowthRate() );
655       }
656       aMesher.SetLocalSize( occgeo, *ngMesh );
657
658       try {
659         ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
660       } catch (netgen::NgException & ex) {
661         return error( COMPERR_BAD_PARMETERS, ex.What() );
662       }
663     }
664     if ( !_hypParameters->GetOptimize() )
665       endWith = netgen::MESHCONST_MESHVOLUME;
666   }
667   else if ( _hypMaxElementVolume )
668   {
669     netgen::mparam.maxh = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
670     // limitVolumeSize( ngMesh, mparam.maxh ); // result is unpredictable
671   }
672   else if ( aMesh.HasShapeToMesh() )
673   {
674     aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
675     netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
676   }
677   else
678   {
679     netgen::Point3d pmin, pmax;
680     ngMesh->GetBox (pmin, pmax);
681     netgen::mparam.maxh = Dist(pmin, pmax)/2;
682   }
683
684   if ( !_hypParameters && aMesh.HasShapeToMesh() )
685   {
686     netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
687   }
688
689   try
690   {
691     OCC_CATCH_SIGNALS;
692
693     ngLib.CalcLocalH(ngMesh);
694     err = ngLib.GenerateMesh(occgeo, startWith, endWith);
695
696     if(netgen::multithread.terminate)
697       return false;
698     if ( err )
699       error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
700   }
701   catch (Standard_Failure& ex)
702   {
703     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
704     str << " at " << netgen::multithread.task
705         << ": " << ex.DynamicType()->Name();
706     if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
707       str << ": " << ex.GetMessageString();
708     error(str);
709   }
710   catch (netgen::NgException& exc)
711   {
712     SMESH_Comment str("NgException");
713     if ( strlen( netgen::multithread.task ) > 0 )
714       str << " at " << netgen::multithread.task;
715     str << ": " << exc.What();
716     error(str);
717   }
718   catch (...)
719   {
720     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
721     if ( strlen( netgen::multithread.task ) > 0 )
722       str << " at " << netgen::multithread.task;
723     error(str);
724   }
725
726   int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
727   int Netgen_NbOfTetra    = Ng_GetNE(Netgen_mesh);
728
729   // -------------------------------------------------------------------
730   // Feed back the SMESHDS with the generated Nodes and Volume Elements
731   // -------------------------------------------------------------------
732
733   if ( err )
734   {
735     SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
736     if ( ce && ce->HasBadElems() )
737       error( ce );
738   }
739
740   bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
741   if ( isOK )
742   {
743     double Netgen_point[3];
744     int    Netgen_tetrahedron[4];
745
746     // create and insert new nodes into nodeVec
747     nodeVec.resize( Netgen_NbOfNodesNew + 1, 0 );
748     int nodeIndex = Netgen_NbOfNodes + 1;
749     for ( ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
750     {
751       Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
752       nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0], Netgen_point[1], Netgen_point[2]);
753     }
754
755     // create tetrahedrons
756     for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
757     {
758       Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
759       try
760       {
761         helper.AddVolume (nodeVec.at( Netgen_tetrahedron[0] ),
762                           nodeVec.at( Netgen_tetrahedron[1] ),
763                           nodeVec.at( Netgen_tetrahedron[2] ),
764                           nodeVec.at( Netgen_tetrahedron[3] ));
765       }
766       catch (...)
767       {
768       }
769     }
770   }
771
772   return !err;
773 }
774
775 //================================================================================
776 /*!
777  * \brief Compute tetrahedral mesh from 2D mesh without geometry
778  */
779 //================================================================================
780
781 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh&         aMesh,
782                                      SMESH_MesherHelper* aHelper)
783 {
784   const int invalid_ID = -1;
785
786   netgen::multithread.terminate = 0;
787   _progressByTic = -1.;
788
789   SMESH_MesherHelper::MType MeshType = aHelper->IsQuadraticMesh();
790   if ( MeshType == SMESH_MesherHelper::COMP )
791     return error( COMPERR_BAD_INPUT_MESH,
792                   SMESH_Comment("Mesh with linear and quadratic elements given"));
793
794   aHelper->SetIsQuadratic( MeshType == SMESH_MesherHelper::QUADRATIC );
795
796   // ---------------------------------
797   // Feed the Netgen with surface mesh
798   // ---------------------------------
799
800   int Netgen_NbOfNodes = 0;
801   double Netgen_point[3];
802   int Netgen_triangle[3];
803
804   NETGENPlugin_NetgenLibWrapper ngLib;
805   Ng_Mesh * Netgen_mesh = ngLib.ngMesh();
806
807   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
808   if ( aMesh.NbQuadrangles() > 0 )
809   {
810     StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
811     Adaptor->Compute(aMesh);
812     proxyMesh.reset( Adaptor );
813
814     if ( aHelper->IsQuadraticMesh() )
815     {
816       SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
817       while( fIt->more())
818         aHelper->AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
819     }
820   }
821
822   // maps nodes to ng ID
823   typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
824   typedef TNodeToIDMap::value_type                     TN2ID;
825   TNodeToIDMap nodeToNetgenID;
826
827   SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
828   while( fIt->more())
829   {
830     // check element
831     const SMDS_MeshElement* elem = fIt->next();
832     if ( !elem )
833       return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
834     if ( elem->NbCornerNodes() != 3 )
835       return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
836
837     // add three nodes of triangle
838     for ( int iN = 0; iN < 3; ++iN )
839     {
840       const SMDS_MeshNode* node = elem->GetNode( iN );
841       int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
842       if ( ngID == invalid_ID )
843       {
844         ngID = ++Netgen_NbOfNodes;
845         Netgen_point [ 0 ] = node->X();
846         Netgen_point [ 1 ] = node->Y();
847         Netgen_point [ 2 ] = node->Z();
848         Ng_AddPoint(Netgen_mesh, Netgen_point);
849       }
850       Netgen_triangle[ iN ] = ngID;
851     }
852     Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
853   }
854   proxyMesh.reset(); // delete tmp faces
855
856   // vector of nodes in which node index == netgen ID
857   vector< const SMDS_MeshNode* > nodeVec ( nodeToNetgenID.size() + 1 );
858   // insert old nodes into nodeVec
859   TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
860   for ( ; n_id != nodeToNetgenID.end(); ++n_id )
861     nodeVec.at( n_id->second ) = n_id->first;
862   nodeToNetgenID.clear();
863
864   // -------------------------
865   // Generate the volume mesh
866   // -------------------------
867
868   return ( ngLib._isComputeOk = compute( aMesh, *aHelper, nodeVec, ngLib ));
869 }
870
871 void NETGENPlugin_NETGEN_3D::CancelCompute()
872 {
873   SMESH_Algo::CancelCompute();
874   netgen::multithread.terminate = 1;
875 }
876
877 //================================================================================
878 /*!
879  * \brief Return Compute progress
880  */
881 //================================================================================
882
883 double NETGENPlugin_NETGEN_3D::GetProgress() const
884 {
885   double res;
886   const char* volMeshing = "Volume meshing";
887   const char* dlnMeshing = "Delaunay meshing";
888   const double meshingRatio = 0.15;
889   const_cast<NETGENPlugin_NETGEN_3D*>( this )->_progressTic++;
890
891   if ( _progressByTic < 0. &&
892        ( strncmp( netgen::multithread.task, dlnMeshing, 3 ) == 0 ||
893          strncmp( netgen::multithread.task, volMeshing, 3 ) == 0 ))
894   {
895     res = 0.001 + meshingRatio * netgen::multithread.percent / 100.;
896   }
897   else // different otimizations
898   {
899     if ( _progressByTic < 0. )
900       ((NETGENPlugin_NETGEN_3D*)this)->_progressByTic = meshingRatio / _progressTic;
901     res = _progressByTic * _progressTic;
902   }
903   return Min ( res, 0.98 );
904 }
905
906 //=============================================================================
907 /*!
908  *
909  */
910 //=============================================================================
911
912 bool NETGENPlugin_NETGEN_3D::Evaluate(SMESH_Mesh& aMesh,
913                                       const TopoDS_Shape& aShape,
914                                       MapShapeNbElems& aResMap)
915 {
916   smIdType nbtri = 0, nbqua = 0;
917   double fullArea = 0.0;
918   for (TopExp_Explorer expF(aShape, TopAbs_FACE); expF.More(); expF.Next()) {
919     TopoDS_Face F = TopoDS::Face( expF.Current() );
920     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
921     MapShapeNbElemsItr anIt = aResMap.find(sm);
922     if( anIt==aResMap.end() ) {
923       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
924       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
925       return false;
926     }
927     std::vector<smIdType> aVec = (*anIt).second;
928     nbtri += std::max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
929     nbqua += std::max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
930     GProp_GProps G;
931     BRepGProp::SurfaceProperties(F,G);
932     double anArea = G.Mass();
933     fullArea += anArea;
934   }
935
936   // collect info from edges
937   smIdType nb0d_e = 0, nb1d_e = 0;
938   bool IsQuadratic = false;
939   bool IsFirst = true;
940   TopTools_MapOfShape tmpMap;
941   for (TopExp_Explorer expF(aShape, TopAbs_EDGE); expF.More(); expF.Next()) {
942     TopoDS_Edge E = TopoDS::Edge(expF.Current());
943     if( tmpMap.Contains(E) )
944       continue;
945     tmpMap.Add(E);
946     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(expF.Current());
947     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
948     if( anIt==aResMap.end() ) {
949       SMESH_ComputeErrorPtr& smError = aSubMesh->GetComputeError();
950       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
951                                             "Submesh can not be evaluated",this));
952       return false;
953     }
954     std::vector<smIdType> aVec = (*anIt).second;
955     nb0d_e += aVec[SMDSEntity_Node];
956     nb1d_e += std::max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
957     if(IsFirst) {
958       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
959       IsFirst = false;
960     }
961   }
962   tmpMap.Clear();
963
964   double ELen_face = sqrt(2.* ( fullArea/double(nbtri+nbqua*2) ) / sqrt(3.0) );
965   double ELen_vol = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
966   double ELen = Min(ELen_vol,ELen_face*2);
967
968   GProp_GProps G;
969   BRepGProp::VolumeProperties(aShape,G);
970   double aVolume = G.Mass();
971   double tetrVol = 0.1179*ELen*ELen*ELen;
972   double CoeffQuality = 0.9;
973   smIdType nbVols = (smIdType)( aVolume/tetrVol/CoeffQuality );
974   smIdType nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
975   smIdType nb1d_in = (nbVols*6 - nb1d_e - nb1d_f ) / 5;
976   std::vector<smIdType> aVec(SMDSEntity_Last);
977   for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
978   if( IsQuadratic ) {
979     aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
980     aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
981     aVec[SMDSEntity_Quad_Pyramid] = nbqua;
982   }
983   else {
984     aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
985     aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
986     aVec[SMDSEntity_Pyramid] = nbqua;
987   }
988   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
989   aResMap.insert(std::make_pair(sm,aVec));
990
991   return true;
992 }
993
994