Salome HOME
#BOS 37851: cast tuple types for compilation on FD38
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_3D_Remote.cxx
1 // Copyright (C) 2007-2023  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_Remote.cxx
25 // Created   : lundi 19 Septembre 2022
26 // Author    : Yoann AUDOUIN (CEA)
27 // Project   : SALOME
28 //=============================================================================
29 //
30 //
31 #include "NETGENPlugin_NETGEN_3D_Remote.hxx"
32
33 #include "NETGENPlugin_NETGEN_3D.hxx"
34
35 #include "NETGENPlugin_DriverParam.hxx"
36 #include "NETGENPlugin_Hypothesis.hxx"
37
38 #include "Utils_SALOME_Exception.hxx"
39
40 #include <SMESH_Gen.hxx>
41 #include <SMESH_Mesh.hxx>
42 #include <SMESH_ParallelMesh.hxx>
43 #include <SMESH_MesherHelper.hxx>
44 #include <SMESH_DriverShape.hxx>
45 #include <SMESH_DriverMesh.hxx>
46 #include <SMESHDS_Mesh.hxx>
47 #include <SMESH_MeshLocker.hxx>
48
49 #include <QString>
50 #include <QProcess>
51
52 #include <boost/filesystem.hpp>
53 namespace fs = boost::filesystem;
54 /*
55   Netgen include files
56 */
57
58 #ifndef OCCGEOMETRY
59 #define OCCGEOMETRY
60 #endif
61 #include <occgeom.hpp>
62
63 #ifdef NETGEN_V5
64 #include <ngexception.hpp>
65 #endif
66 #ifdef NETGEN_V6
67 #include <core/exception.hpp>
68 #endif
69
70 namespace nglib {
71 #include <nglib.h>
72 }
73 namespace netgen {
74
75   NETGENPLUGIN_DLL_HEADER
76   extern MeshingParameters mparam;
77
78   NETGENPLUGIN_DLL_HEADER
79   extern volatile multithreadt multithread;
80 }
81 using namespace nglib;
82
83 //=============================================================================
84 /*!
85  * Constructor
86  */
87 //=============================================================================
88
89 NETGENPlugin_NETGEN_3D_Remote::NETGENPlugin_NETGEN_3D_Remote(int hypId, SMESH_Gen * gen)
90   : NETGENPlugin_NETGEN_3D(hypId, gen)
91 {
92   _name = "NETGEN_3D_Remote";
93 }
94
95 //=============================================================================
96 /*!
97  * Destructor
98  */
99 //=============================================================================
100
101 NETGENPlugin_NETGEN_3D_Remote::~NETGENPlugin_NETGEN_3D_Remote()
102 {
103 }
104
105 /**
106  * @brief Fill the structure netgen_param with the information from the hypothesis
107  *
108  * @param hyp the hypothesis
109  * @param aParams the netgen_param structure
110  */
111 void NETGENPlugin_NETGEN_3D_Remote::fillParameters(const NETGENPlugin_Hypothesis* hyp, netgen_params &aParams)
112 {
113   aParams.maxh               = hyp->GetMaxSize();
114   aParams.minh               = hyp->GetMinSize();
115   aParams.segmentsperedge    = hyp->GetNbSegPerEdge();
116   aParams.grading            = hyp->GetGrowthRate();
117   aParams.curvaturesafety    = hyp->GetNbSegPerRadius();
118   aParams.secondorder        = hyp->GetSecondOrder() ? 1 : 0;
119   aParams.quad               = hyp->GetQuadAllowed() ? 1 : 0;
120   aParams.optimize           = hyp->GetOptimize();
121   aParams.fineness           = hyp->GetFineness();
122   aParams.uselocalh          = hyp->GetSurfaceCurvature();
123   aParams.merge_solids       = hyp->GetFuseEdges();
124   aParams.chordalError       = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
125   aParams.optsteps2d         = aParams.optimize ? hyp->GetNbSurfOptSteps() : 0;
126   aParams.optsteps3d         = aParams.optimize ? hyp->GetNbVolOptSteps()  : 0;
127   aParams.elsizeweight       = hyp->GetElemSizeWeight();
128   aParams.opterrpow          = hyp->GetWorstElemMeasure();
129   aParams.delaunay           = hyp->GetUseDelauney();
130   aParams.checkoverlap       = hyp->GetCheckOverlapping();
131   aParams.checkchartboundary = hyp->GetCheckChartBoundary();
132 #ifdef NETGEN_V6
133   // std::string
134   aParams.meshsizefilename = hyp->GetMeshSizeFile();
135   aParams.closeedgefac = 2;
136   aParams.nbThreads = hyp->GetNbThreads();
137 #else
138   // const char*
139   aParams.meshsizefilename = hyp->GetMeshSizeFile();
140   aParams.closeedgefac = 0;
141   aParams.nbThreads = 0;
142 #endif
143 }
144
145 //
146
147 /**
148  * @brief write in a binary file the orientation for each surface element of the mesh
149  *
150  * @param aMesh The mesh
151  * @param aShape the shape associated to the mesh
152  * @param output_file name of the binary file
153  */
154 void NETGENPlugin_NETGEN_3D_Remote::exportElementOrientation(SMESH_Mesh& aMesh,
155                                                       const TopoDS_Shape& aShape,
156                                                       const std::string output_file)
157 {
158   SMESH_MesherHelper helper(aMesh);
159   NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
160   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
161   std::map<vtkIdType, bool> elemOrientation;
162
163   for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
164   {
165     const TopoDS_Shape& aShapeFace = exFa.Current();
166     int faceID = aMesh.GetMeshDS()->ShapeToIndex( aShapeFace );
167     bool isInternalFace = internals.isInternalShape( faceID );
168     bool isRev = false;
169     if ( !isInternalFace &&
170           helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
171       // IsReversedSubMesh() can work wrong on strongly curved faces,
172       // so we use it as less as possible
173       isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
174
175     const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
176     if ( !aSubMeshDSFace ) continue;
177
178     SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
179     if ( _quadraticMesh &&
180           dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
181     {
182       // add medium nodes of proxy triangles to helper (#16843)
183       while ( iteratorElem->more() )
184         helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
185
186       iteratorElem = aSubMeshDSFace->GetElements();
187     }
188     while ( iteratorElem->more() ) // loop on elements on a geom face
189     {
190       // check mesh face
191       const SMDS_MeshElement* elem = iteratorElem->next();
192       if ( !elem )
193         error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
194       if ( elem->NbCornerNodes() != 3 )
195         error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
196       elemOrientation[elem->GetID()] = isRev;
197     } // loop on elements on a face
198   } // loop on faces of a SOLID or SHELL
199
200   {
201     std::ofstream df(output_file, ios::out|ios::binary);
202     int size=elemOrientation.size();
203
204     df.write((char*)&size, sizeof(int));
205     for(auto const& [id, orient]:elemOrientation){
206       df.write((char*)&id, sizeof(vtkIdType));
207       df.write((char*)&orient, sizeof(bool));
208     }
209   }
210 }
211
212 /**
213  * @brief Compute mesh associate to shape
214  *
215  * @param aMesh The mesh
216  * @param aShape The shape
217  * @return true fi there are some error
218  */
219 bool NETGENPlugin_NETGEN_3D_Remote::Compute(SMESH_Mesh&         aMesh,
220                                            const TopoDS_Shape& aShape)
221 {
222   {
223     SMESH_MeshLocker myLocker(&aMesh);
224     SMESH_Hypothesis::Hypothesis_Status hypStatus;
225     NETGENPlugin_NETGEN_3D::CheckHypothesis(aMesh, aShape, hypStatus);
226   }
227   SMESH_ParallelMesh& aParMesh = dynamic_cast<SMESH_ParallelMesh&>(aMesh);
228
229   // Temporary folder for run
230 #ifdef WIN32
231   fs::path tmp_folder = aParMesh.GetTmpFolder() / fs::path("Volume-%%%%-%%%%");
232 #else
233   fs::path tmp_folder = aParMesh.GetTmpFolder() / fs::unique_path(fs::path("Volume-%%%%-%%%%"));
234 #endif
235   fs::create_directories(tmp_folder);
236   // Using MESH2D generated after all triangles where created.
237   fs::path mesh_file=aParMesh.GetTmpFolder() / fs::path("Mesh2D.med");
238   fs::path element_orientation_file=tmp_folder / fs::path("element_orientation.dat");
239   fs::path new_element_file=tmp_folder / fs::path("new_elements.dat");
240   fs::path tmp_mesh_file=tmp_folder / fs::path("tmp_mesh.med");
241   // Not used kept for debug
242   //fs::path output_mesh_file=tmp_folder / fs::path("output_mesh.med");
243   fs::path shape_file=tmp_folder / fs::path("shape.brep");
244   fs::path param_file=tmp_folder / fs::path("netgen3d_param.txt");
245   fs::path log_file=tmp_folder / fs::path("run.log");
246   fs::path cmd_file=tmp_folder / fs::path("cmd.txt");
247   // TODO: See if we can retreived name from aMesh ?
248   std::string mesh_name = "MESH";
249
250   {
251     SMESH_MeshLocker myLocker(&aMesh);
252     //Writing Shape
253     SMESH_DriverShape::exportShape(shape_file.string(), aShape);
254
255     //Writing hypo
256     netgen_params aParams;
257     fillParameters(_hypParameters, aParams);
258
259     exportNetgenParams(param_file.string(), aParams);
260
261     // Exporting element orientation
262     exportElementOrientation(aMesh, aShape, element_orientation_file.string());
263   }
264
265   // Calling run_mesher
266   // Path to mesher script
267   fs::path mesher_launcher = fs::path(std::getenv("SMESH_ROOT_DIR"))/
268        fs::path("bin")/
269        fs::path("salome")/
270        fs::path("mesher_launcher.py");
271
272
273   std::string s_program="python3";
274   std::list<std::string> params;
275   params.push_back(mesher_launcher.string());
276   params.push_back("NETGEN3D");
277   params.push_back(mesh_file.string());
278   params.push_back(shape_file.string());
279   params.push_back(param_file.string());
280   params.push_back("--elem-orient-file=" + element_orientation_file.string());
281   params.push_back("--new-element-file=" + new_element_file.string());
282
283   // Parallelism method parameters
284   int method = aParMesh.GetParallelismMethod();
285   if(method == ParallelismMethod::MultiThread){
286     params.push_back("--method=local");
287   } else if (method == ParallelismMethod::MultiNode){
288     params.push_back("--method=cluster");
289     params.push_back("--resource="+aParMesh.GetResource());
290     params.push_back("--wc-key="+aParMesh.GetWcKey());
291     params.push_back("--nb-proc=1");
292     params.push_back("--nb-proc-per-node="+to_string(aParMesh.GetNbProcPerNode()));
293     params.push_back("--nb-node="+to_string(aParMesh.GetNbNode()));
294     params.push_back("--walltime="+aParMesh.GetWalltime());
295   } else {
296     throw SALOME_Exception("Unknown parallelism method "+method);
297   }
298   std::string cmd = "";
299   cmd += s_program;
300   for(auto arg: params){
301     cmd += " " + arg;
302   }
303   MESSAGE("Running command: ");
304   MESSAGE(cmd);
305   // Writing command in cmd.log
306   {
307     std::ofstream flog(cmd_file.string());
308     flog << cmd << endl;
309   }
310
311   // Building arguments for QProcess
312   QString program = QString::fromStdString(s_program);
313   QStringList arguments;
314   for(auto arg : params){
315     arguments << arg.c_str();
316   }
317
318   QString out_file = log_file.string().c_str();
319   QProcess myProcess;
320   myProcess.setProcessChannelMode(QProcess::MergedChannels);
321   myProcess.setStandardOutputFile(out_file);
322
323   myProcess.start(program, arguments);
324   // Waiting for process to finish (argument -1 make it wait until the end of
325   // the process otherwise it just waits 30 seconds)
326   bool finished = myProcess.waitForFinished(-1);
327   int ret = myProcess.exitCode();
328
329   if(ret != 0 || !finished){
330     // Run crahed
331     std::string msg = "Issue with mesh_launcher: \n";
332     msg += "See log for more details: " + log_file.string() + "\n";
333     msg += cmd + "\n";
334     throw SALOME_Exception(msg);
335   }
336
337   {
338     SMESH_MeshLocker myLocker(&aMesh);
339     std::ifstream df(new_element_file.string(), ios::binary);
340
341     int Netgen_NbOfNodes;
342     int Netgen_NbOfNodesNew;
343     int Netgen_NbOfTetra;
344     double Netgen_point[3];
345     int    Netgen_tetrahedron[4];
346     int nodeID;
347
348     SMESH_MesherHelper helper(aMesh);
349     // This function is mandatory for setElementsOnShape to work
350     helper.IsQuadraticSubMesh(aShape);
351     helper.SetElementsOnShape( true );
352
353     // Number of nodes in intial mesh
354     df.read((char*) &Netgen_NbOfNodes, sizeof(int));
355     // Number of nodes added by netgen
356     df.read((char*) &Netgen_NbOfNodesNew, sizeof(int));
357
358     // Filling nodevec (correspondence netgen numbering mesh numbering)
359     vector< const SMDS_MeshNode* > nodeVec ( Netgen_NbOfNodesNew + 1 );
360     //vector<int> nodeTmpVec ( Netgen_NbOfNodesNew + 1 );
361     SMESHDS_Mesh * meshDS = helper.GetMeshDS();
362     for (int nodeIndex = 1 ; nodeIndex <= Netgen_NbOfNodes; ++nodeIndex )
363     {
364       //Id of the point
365       df.read((char*) &nodeID, sizeof(int));
366       nodeVec.at(nodeIndex) = meshDS->FindNode(nodeID);
367     }
368
369     // Add new points and update nodeVec
370     for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
371     {
372       df.read((char *) &Netgen_point, sizeof(double)*3);
373
374       nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
375                                  Netgen_point[1],
376                                  Netgen_point[2]);
377     }
378
379     // Add tetrahedrons
380     df.read((char*) &Netgen_NbOfTetra, sizeof(int));
381
382     for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
383     {
384       df.read((char*) &Netgen_tetrahedron, sizeof(int)*4);
385       helper.AddVolume(
386                     nodeVec.at( Netgen_tetrahedron[0] ),
387                     nodeVec.at( Netgen_tetrahedron[1] ),
388                     nodeVec.at( Netgen_tetrahedron[2] ),
389                     nodeVec.at( Netgen_tetrahedron[3] ));
390     }
391   }
392
393   return true;
394 }
395
396 /**
397  * @brief Assign submeshes to compute
398  *
399  * @param aSubMesh submesh to add
400  */
401 void NETGENPlugin_NETGEN_3D_Remote::setSubMeshesToCompute(SMESH_subMesh * aSubMesh)
402 {
403   SMESH_MeshLocker myLocker(aSubMesh->GetFather());
404   SMESH_Algo::setSubMeshesToCompute(aSubMesh);
405 }