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