Salome HOME
Corrections for parallel smesh
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_3D_SA.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_SA.cxx
25 // Created   : lundi 19 Septembre 2022
26 // Author    : Yoann AUDOUIN (CEA)
27 // Project   : SALOME
28 //=============================================================================
29 //
30 //
31 #include "NETGENPlugin_NETGEN_3D_SA.hxx"
32
33 #include "NETGENPlugin_DriverParam.hxx"
34 #include "NETGENPlugin_Hypothesis.hxx"
35 #include "StdMeshers_MaxElementVolume.hxx"
36
37 #include <SMESH_Gen.hxx>
38 #include <SMESH_Mesh.hxx>
39 #include <SMESH_MesherHelper.hxx>
40 #include <SMESH_DriverShape.hxx>
41 #include <SMESH_DriverMesh.hxx>
42 #include <SMESHDS_Mesh.hxx>
43
44
45 #include <boost/filesystem.hpp>
46 namespace fs = boost::filesystem;
47
48 /*
49   Netgen include files
50 */
51
52 #ifndef OCCGEOMETRY
53 #define OCCGEOMETRY
54 #endif
55 #include <occgeom.hpp>
56
57 #ifdef NETGEN_V5
58 #include <ngexception.hpp>
59 #endif
60 #ifdef NETGEN_V6
61 #include <core/exception.hpp>
62 #endif
63
64 namespace nglib {
65 #include <nglib.h>
66 }
67 namespace netgen {
68
69   NETGENPLUGIN_DLL_HEADER
70   extern MeshingParameters mparam;
71
72   NETGENPLUGIN_DLL_HEADER
73   extern volatile multithreadt multithread;
74 }
75 using namespace nglib;
76
77 //=============================================================================
78 /*!
79  * Constructor
80  */
81 //=============================================================================
82
83 NETGENPlugin_NETGEN_3D_SA::NETGENPlugin_NETGEN_3D_SA()
84   :  NETGENPlugin_NETGEN_3D(0, new SMESH_Gen())
85 {
86   _name = "NETGEN_3D_SA";
87 }
88
89 //=============================================================================
90 /*!
91  * Destructor
92  */
93 //=============================================================================
94
95 NETGENPlugin_NETGEN_3D_SA::~NETGENPlugin_NETGEN_3D_SA()
96 {
97   if(_gen)
98     delete _gen;
99 }
100
101 /**
102  * @brief fill plugin hypothesis from the netgen_params structure
103  *
104  * @param aParams the structure
105  * @param gen SMESH_Gen associate with the SA
106  */
107 void NETGENPlugin_NETGEN_3D_SA::fillHyp(netgen_params aParams)
108 {
109   if(_gen)
110     std::cout << "_gen is set"  << std::endl;
111   if(aParams.has_netgen_param){
112     NETGENPlugin_Hypothesis * hypParameters = new NETGENPlugin_Hypothesis(0, GetGen());
113
114     hypParameters->SetMaxSize(aParams.maxh);
115     hypParameters->SetMinSize(aParams.minh);
116     hypParameters->SetNbSegPerEdge(aParams.segmentsperedge);
117     hypParameters->SetGrowthRate(aParams.grading);
118     hypParameters->SetNbSegPerRadius(aParams.curvaturesafety);
119     hypParameters->SetSecondOrder(aParams.secondorder);
120     hypParameters->SetQuadAllowed(aParams.quad);
121     hypParameters->SetOptimize(aParams.optimize);
122     hypParameters->SetFineness((NETGENPlugin_Hypothesis::Fineness)aParams.fineness);
123     hypParameters->SetSurfaceCurvature(aParams.uselocalh);
124     hypParameters->SetFuseEdges(aParams.merge_solids);
125     hypParameters->SetChordalErrorEnabled(aParams.chordalError);
126     if(aParams.optimize){
127       hypParameters->SetNbSurfOptSteps(aParams.optsteps2d);
128       hypParameters->SetNbVolOptSteps(aParams.optsteps3d);
129     }
130     hypParameters->SetElemSizeWeight(aParams.elsizeweight);
131     hypParameters->SetWorstElemMeasure(aParams.opterrpow);
132     hypParameters->SetUseDelauney(aParams.delaunay);
133     hypParameters->SetCheckOverlapping(aParams.checkoverlap);
134     hypParameters->SetCheckChartBoundary(aParams.checkchartboundary);
135     hypParameters->SetMeshSizeFile(aParams.meshsizefilename);
136
137     _hypParameters = dynamic_cast< const NETGENPlugin_Hypothesis *> (hypParameters);
138   }
139   if(aParams.has_maxelementvolume_hyp){
140     _hypMaxElementVolume = new StdMeshers_MaxElementVolume(1, GetGen());
141     _maxElementVolume = aParams.maxElementVolume;
142   }
143   // TODO: Handle viscous layer
144 }
145
146 /**
147  * @brief Write a binary file containing information on the elements/nodes
148  *        created by the mesher
149  *
150  * @param nodeVec mapping between the mesh id and the netgen structure id
151  * @param ngLib Wrapper on netgen library
152  * @param new_element_file Name of the output file
153  * @param Netgen_NbOfNodes Number of nodes in the netgen structure
154  * @return true if there are some error
155  */
156 bool NETGENPlugin_NETGEN_3D_SA::computeFillNewElementFile(
157     std::vector< const SMDS_MeshNode* > &nodeVec,
158     NETGENPlugin_NetgenLibWrapper &ngLib,
159     std::string new_element_file,
160     int &Netgen_NbOfNodes
161 )
162 {
163   Ng_Mesh* Netgen_mesh = ngLib.ngMesh();
164
165   int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
166   int Netgen_NbOfTetra    = Ng_GetNE(Netgen_mesh);
167
168   bool isOK = ( Netgen_NbOfTetra > 0 );
169   if ( isOK && !new_element_file.empty() )
170   {
171     std::ofstream df(new_element_file, ios::out|ios::binary);
172
173     double Netgen_point[3];
174     int    Netgen_tetrahedron[4];
175
176     // Writing nodevec (correspondence netgen numbering mesh numbering)
177     // Number of nodes
178     df.write((char*) &Netgen_NbOfNodes, sizeof(int));
179     df.write((char*) &Netgen_NbOfNodesNew, sizeof(int));
180     for (int nodeIndex = 1 ; nodeIndex <= Netgen_NbOfNodes; ++nodeIndex )
181     {
182       //Id of the point
183       int id = nodeVec.at(nodeIndex)->GetID();
184       df.write((char*) &id, sizeof(int));
185     }
186
187     // Writing info on new points
188     for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
189     {
190       Ng_GetPoint(Netgen_mesh, nodeIndex, Netgen_point );
191       // Coordinates of the point
192       df.write((char *) &Netgen_point, sizeof(double)*3);
193     }
194
195     // create tetrahedrons
196     df.write((char*) &Netgen_NbOfTetra, sizeof(int));
197     for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
198     {
199       Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
200       df.write((char*) &Netgen_tetrahedron, sizeof(int)*4);
201     }
202   }
203   return false;
204 }
205
206 /**
207  * @brief Compute mesh associated to shape
208  *
209  * @param aShape the shape
210  * @param aMesh the mesh
211  * @param aParams netgen_params structure
212  * @param new_element_file Name of the file containing new element
213  * @param output_mesh Name of the output mesh (if empty it will not be written)
214  * @return true if there are some error
215  */
216 bool NETGENPlugin_NETGEN_3D_SA::Compute(
217         TopoDS_Shape &aShape,
218         SMESH_Mesh& aMesh,
219         netgen_params& aParams,
220         std::string new_element_file,
221         bool output_mesh)
222 {
223   // vector of nodes in which node index == netgen ID
224   vector< const SMDS_MeshNode* > nodeVec;
225   NETGENPlugin_NetgenLibWrapper ngLib;
226   SMESH_MesherHelper helper(aMesh);
227   int startWith = netgen::MESHCONST_MESHVOLUME;
228   int endWith   = netgen::MESHCONST_OPTVOLUME;
229   int Netgen_NbOfNodes=0;
230
231   // Changing netgen log_file putting it next to new_element_file
232   fs::path netgen_log_file = fs::path(new_element_file).remove_filename() / fs::path("NETGEN.out");
233
234   ngLib.setOutputFile(netgen_log_file.string());
235
236   NETGENPlugin_NETGEN_3D::computeFillNgMesh(aMesh, aShape, nodeVec, ngLib, helper, Netgen_NbOfNodes);
237
238   netgen::OCCGeometry occgeo;
239   NETGENPlugin_NETGEN_3D::computePrepareParam(aMesh, ngLib, occgeo, helper, endWith);
240
241   NETGENPlugin_NETGEN_3D::computeRunMesher(occgeo, nodeVec, ngLib._ngMesh, ngLib, startWith, endWith);
242
243   computeFillNewElementFile(nodeVec, ngLib, new_element_file, Netgen_NbOfNodes);
244
245   if(output_mesh)
246     NETGENPlugin_NETGEN_3D::computeFillMesh(nodeVec, ngLib, helper, Netgen_NbOfNodes);
247
248   return false;
249 }
250
251
252 /**
253  * @brief Running the mesher on the given files
254  *
255  * @param input_mesh_file Mesh file (containing 2D elements)
256  * @param shape_file Shape file (BREP or STEP format)
257  * @param hypo_file Ascii file containing the netgen parameters
258  * @param element_orientation_file Binary file containing the orientation of surface elemnts
259  * @param new_element_file output file containing info the elements created by the mesher
260  * @param output_mesh_file output mesh file (if empty it will not be created)
261  * @return int
262  */
263 int NETGENPlugin_NETGEN_3D_SA::run(const std::string input_mesh_file,
264           const std::string shape_file,
265           const std::string hypo_file,
266           const std::string element_orientation_file,
267           const std::string new_element_file,
268           const std::string output_mesh_file)
269 {
270
271   _element_orientation_file = element_orientation_file;
272
273   std::unique_ptr<SMESH_Mesh> myMesh(_gen->CreateMesh(false));
274
275   importMesh(input_mesh_file, *myMesh);
276
277   // Importing shape
278   TopoDS_Shape myShape;
279   importShape(shape_file, myShape);
280
281   // Importing hypothesis
282   netgen_params myParams;
283
284   importNetgenParams(hypo_file, myParams);
285   fillHyp(myParams);
286
287   MESSAGE("Meshing with netgen3d");
288   int ret = Compute(myShape, *myMesh, myParams,
289                       new_element_file,
290                       !output_mesh_file.empty());
291
292
293   if(ret){
294     std::cerr << "Meshing failed" << std::endl;
295     return ret;
296   }
297
298   if(!output_mesh_file.empty()){
299     std::string meshName = "MESH";
300     exportMesh(output_mesh_file, *myMesh, meshName);
301   }
302
303   return ret;
304 }
305
306 /**
307  * @brief Compute the list of already meshed Surface elements and info
308  *        on their orientation and if they are internal
309  *
310  * @param aMesh Global Mesh
311  * @param aShape Shape associated to the mesh
312  * @param proxyMesh pointer to mesh used fo find the elements
313  * @param internals information on internal sub shapes
314  * @param helper helper associated to the mesh
315  * @param listElements map of surface element associated with
316  *                     their orientation and internal status
317  * @return true if their was some error
318  */
319 bool NETGENPlugin_NETGEN_3D_SA::getSurfaceElements(
320     SMESH_Mesh&         aMesh,
321     const TopoDS_Shape& aShape,
322     SMESH_ProxyMesh::Ptr proxyMesh,
323     NETGENPlugin_Internals &internals,
324     SMESH_MesherHelper &helper,
325     std::map<const SMDS_MeshElement*, tuple<bool, bool>, TIDCompare>& listElements
326     )
327 {
328   // To remove compilation warnings
329   (void) aShape;
330   (void) proxyMesh;
331   (void) internals;
332   (void) helper;
333   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
334
335   // Get list of elements + their orientation from element_orientation file
336   std::map<vtkIdType, bool> elemOrientation;
337   {
338     // Setting all element orientation to false if there no element orientation file
339     if(_element_orientation_file.empty()){
340       MESSAGE("No element orientation file");
341
342       SMDS_ElemIteratorPtr iteratorElem = meshDS->elementsIterator(SMDSAbs_Face);
343       while ( iteratorElem->more() ) // loop on elements on a geom face
344         {
345           // check mesh face
346           const SMDS_MeshElement* elem = iteratorElem->next();
347           elemOrientation[elem->GetID()] = false;
348         }
349     } else {
350       MESSAGE("Reading from elements from file: " << _element_orientation_file);
351       std::ifstream df(_element_orientation_file, ios::binary|ios::in);
352       int nbElement;
353       bool orient;
354
355       // Warning of the use of vtkIdType (I had issue when run_mesher was compiled with internal vtk) and salome not
356       // Sizeof was the same but how he othered the type was different
357       // Maybe using another type (uint64_t) instead would be better
358       vtkIdType id;
359       df.read((char*)&nbElement, sizeof(int));
360
361       for(int ielem=0;ielem<nbElement;++ielem){
362         df.read((char*) &id, sizeof(vtkIdType));
363         df.read((char*) &orient, sizeof(bool));
364         elemOrientation[id] = orient;
365       }
366     }
367   }
368
369   // Adding elements from Mesh
370   SMDS_ElemIteratorPtr iteratorElem = meshDS->elementsIterator(SMDSAbs_Face);
371   bool isRev;
372
373   bool isIn;
374
375   while ( iteratorElem->more() ) // loop on elements on a geom face
376   {
377     // check mesh face
378     const SMDS_MeshElement* elem = iteratorElem->next();
379     if ( !elem ){
380       return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
381     }
382     if ( elem->NbCornerNodes() != 3 ){
383       return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
384     }
385     // Keeping only element that are in the element orientation file
386     isIn = elemOrientation.count(elem->GetID())==1;
387     if(!isIn)
388       continue;
389     // Get orientation
390     // Netgen requires that all the triangle point outside
391     isRev = elemOrientation[elem->GetID()];
392     listElements[elem] = tuple(isRev, false);
393   }
394
395   return false;
396 }