]> SALOME platform Git repositories - plugins/netgenplugin.git/blob - src/NETGENPlugin/NETGENPlugin_NETGEN_2D_Remote.cxx
Salome HOME
Merge branch 'V9_13_BR'
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_2D_Remote.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_2D_Remote.cxx
25 // Created   : mardi 12 Decembre 2023
26 // Author    : Cesar Conopoima (OCC)
27 // Project   : SALOME
28 //=============================================================================
29 //
30 //
31 #include "NETGENPlugin_NETGEN_2D_Remote.hxx"
32
33 #include "NETGENPlugin_DriverParam.hxx"
34 #include "NETGENPlugin_Hypothesis.hxx"
35
36 #include "Utils_SALOME_Exception.hxx"
37
38 #include <SMESH_Gen.hxx>
39 #include <SMESH_Mesh.hxx>
40 #include <SMESH_ParallelMesh.hxx>
41 #include <SMESH_MesherHelper.hxx>
42 #include <SMESH_DriverShape.hxx>
43 #include <SMESH_DriverMesh.hxx>
44 #include <SMESHDS_Mesh.hxx>
45 #include <SMESH_MeshLocker.hxx>
46
47 #include <QString>
48 #include <QProcess>
49
50 #include <boost/filesystem.hpp>
51 namespace fs = boost::filesystem;
52 /*
53   Netgen include files
54 */
55
56 #ifndef OCCGEOMETRY
57 #define OCCGEOMETRY
58 #endif
59 #include <occgeom.hpp>
60
61 #ifdef NETGEN_V5
62 #include <ngexception.hpp>
63 #endif
64 #ifdef NETGEN_V6
65 #include <core/exception.hpp>
66 #endif
67
68 namespace nglib {
69 #include <nglib.h>
70 }
71 namespace netgen {
72
73   NETGENPLUGIN_DLL_HEADER
74   extern MeshingParameters mparam;
75
76   NETGENPLUGIN_DLL_HEADER
77   extern volatile multithreadt multithread;
78 }
79 using namespace nglib;
80
81 //=============================================================================
82 /*!
83  * Constructor
84  */
85 //=============================================================================
86
87 NETGENPlugin_NETGEN_2D_Remote::NETGENPlugin_NETGEN_2D_Remote(int hypId, SMESH_Gen * gen)
88   : NETGENPlugin_NETGEN_2D_ONLY(hypId, gen)
89 {
90   _name = "NETGEN_2D_Remote";
91 }
92
93 //=============================================================================
94 /*!
95  * Destructor
96  */
97 //=============================================================================
98
99 NETGENPlugin_NETGEN_2D_Remote::~NETGENPlugin_NETGEN_2D_Remote()
100 {
101 }
102
103 /**
104  * @brief Fill the structure netgen_param with the information from the hypothesis
105  *
106  * @param hyp the hypothesis
107  * @param aParams the netgen_param structure
108  */
109 void NETGENPlugin_NETGEN_2D_Remote::fillParameters(const NETGENPlugin_Hypothesis* hyp, netgen_params &aParams)
110 {
111   aParams.myType             = hypoType::Hypo;
112   aParams.maxh               = hyp->GetMaxSize();
113   aParams.minh               = hyp->GetMinSize();
114   aParams.segmentsperedge    = hyp->GetNbSegPerEdge();
115   aParams.grading            = hyp->GetGrowthRate();
116   aParams.curvaturesafety    = hyp->GetNbSegPerRadius();
117   aParams.secondorder        = hyp->GetSecondOrder() ? 1 : 0;
118   aParams.quad               = hyp->GetQuadAllowed() ? 1 : 0;
119   aParams.optimize           = hyp->GetOptimize();
120   aParams.fineness           = hyp->GetFineness();
121   aParams.uselocalh          = hyp->GetSurfaceCurvature();
122   aParams.merge_solids       = hyp->GetFuseEdges();
123   aParams.chordalError       = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
124   aParams.optsteps2d         = aParams.optimize ? hyp->GetNbSurfOptSteps() : 0;
125   aParams.optsteps3d         = aParams.optimize ? hyp->GetNbVolOptSteps()  : 0;
126   aParams.elsizeweight       = hyp->GetElemSizeWeight();
127   aParams.opterrpow          = hyp->GetWorstElemMeasure();
128   aParams.delaunay           = hyp->GetUseDelauney();
129   aParams.checkoverlap       = hyp->GetCheckOverlapping();
130   aParams.checkchartboundary = hyp->GetCheckChartBoundary();
131 #ifdef NETGEN_V6
132   // std::string
133   aParams.meshsizefilename = hyp->GetMeshSizeFile();
134   aParams.closeedgefac = 2;
135   aParams.nbThreads = hyp->GetNbThreads();
136 #else
137   // const char*
138   aParams.meshsizefilename = hyp->GetMeshSizeFile();
139   aParams.closeedgefac = 0;
140   aParams.nbThreads = 0;
141 #endif
142 }
143
144 /**
145  * @brief write in a binary file the orientation for each surface element of the mesh
146  *
147  * @param aMesh The mesh
148  * @param aShape the shape associated to the mesh
149  * @param output_file name of the binary file
150  */
151 void NETGENPlugin_NETGEN_2D_Remote::exportElementOrientation(const std::string output_file)
152 {
153   std::ofstream df(output_file, ios::out|ios::binary);
154   int size=0;
155   df.write((char*)&size, sizeof(int));
156   df.close();
157 }
158
159 /**
160  * @brief Compute mesh associate to shape
161  *
162  * @param aMesh The mesh
163  * @param aShape The shape
164  * @return true fi there are some error
165  */
166 bool NETGENPlugin_NETGEN_2D_Remote::Compute(SMESH_Mesh&         aMesh,
167                                            const TopoDS_Shape& aShape)
168 {
169   {
170     SMESH_MeshLocker myLocker(&aMesh);
171     SMESH_Hypothesis::Hypothesis_Status hypStatus;
172     NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis(aMesh, aShape, hypStatus);
173   }
174   SMESH_ParallelMesh& aParMesh = dynamic_cast<SMESH_ParallelMesh&>(aMesh);
175
176   // Temporary folder for run
177 #ifdef WIN32
178   fs::path tmp_folder = aParMesh.GetTmpFolder() / fs::path("Volume-%%%%-%%%%");
179 #else
180   fs::path tmp_folder = aParMesh.GetTmpFolder() / fs::unique_path(fs::path("Volume-%%%%-%%%%"));
181 #endif
182   fs::create_directories(tmp_folder);
183   // Using MESH2D generated after all triangles where created.
184   fs::path mesh_file=aParMesh.GetTmpFolder() / fs::path("Mesh1D.med"); // read the premeshed elements from 2D version
185   fs::path element_orientation_file=tmp_folder / fs::path("element_orientation.dat");
186   fs::path new_element_file=tmp_folder / fs::path("new_elements.dat");
187   // Not used kept for debug
188   //fs::path output_mesh_file=tmp_folder / fs::path("output_mesh.med");
189   fs::path shape_file=tmp_folder / fs::path("shape.brep");
190   fs::path param_file=tmp_folder / fs::path("netgen_lenghtfromedge.txt"); /*becuase name contain 'lenghtfromedge' set length of 2D from premeshed 1D elements*/
191   fs::path log_file=tmp_folder / fs::path("run.log");
192   fs::path cmd_file=tmp_folder / fs::path("cmd.txt");
193   std::string mesh_name = "MESH";
194
195   {
196     SMESH_MeshLocker myLocker(&aMesh);
197     //Writing Shape
198     SMESH_DriverShape::exportShape(shape_file.string(), aShape);
199
200     //Writing hypo
201     // netgen_params aParams;
202     // fillParameters(_hypParameters, aParams);
203     // exportNetgenParams(param_file.string(), aParams);
204     {
205       // Simply write the file with the proper name
206       std::ofstream myfile(param_file.string());
207       myfile << 1 << std::endl;
208       myfile.close();
209     }
210       
211     // Exporting element orientation
212     exportElementOrientation(element_orientation_file.string());
213   }
214
215   // Calling run_mesher
216   // Path to mesher script
217   fs::path mesher_launcher = fs::path(std::getenv("SMESH_ROOT_DIR"))/
218        fs::path("bin")/
219        fs::path("salome")/
220        fs::path("mesher_launcher.py");
221
222
223   std::string s_program="python3";
224   std::list<std::string> params;
225   params.push_back(mesher_launcher.string());
226   params.push_back("NETGEN2D");
227   params.push_back(mesh_file.string());
228   params.push_back(shape_file.string());
229   params.push_back(param_file.string());
230   params.push_back("--elem-orient-file=" + element_orientation_file.string());
231   params.push_back("--new-element-file=" + new_element_file.string());
232   // params.push_back("--output-mesh-file=" + output_mesh_file.string());
233
234   // Parallelism method parameters
235   int method = aParMesh.GetParallelismMethod();
236   if(method == ParallelismMethod::MultiThread){
237     params.push_back("--method=local");
238   } else if (method == ParallelismMethod::MultiNode){
239     params.push_back("--method=cluster");
240     params.push_back("--resource="+aParMesh.GetResource());
241     params.push_back("--wc-key="+aParMesh.GetWcKey());
242     params.push_back("--nb-proc=1");
243     params.push_back("--nb-proc-per-node="+to_string(aParMesh.GetNbProcPerNode()));
244     params.push_back("--nb-node="+to_string(aParMesh.GetNbNode()));
245     params.push_back("--walltime="+aParMesh.GetWalltime());
246   } else {
247     throw SALOME_Exception("Unknown parallelism method "+method);
248   }
249   std::string cmd = "";
250   cmd += s_program;
251   for(auto arg: params){
252     cmd += " " + arg;
253   }
254   MESSAGE("Running command: ");
255   MESSAGE(cmd);
256   // Writing command in cmd.log
257   {
258     std::ofstream flog(cmd_file.string());
259     flog << cmd << endl;
260   }
261
262   // Building arguments for QProcess
263   QString program = QString::fromStdString(s_program);
264   QStringList arguments;
265   for(auto arg : params){
266     arguments << arg.c_str();
267   }
268
269   QString out_file = log_file.string().c_str();
270   QProcess myProcess;
271   // myProcess.setProcessChannelMode(QProcess::MergedChannels);
272   myProcess.setProcessChannelMode(QProcess::ForwardedChannels);
273   myProcess.setStandardOutputFile(out_file);
274
275   myProcess.start(program, arguments);
276   // Waiting for process to finish (argument -1 make it wait until the end of
277   // the process otherwise it just waits 30 seconds)
278   bool finished = myProcess.waitForFinished(-1);
279   int ret = myProcess.exitCode();
280   if(ret != 0 || !finished){
281     // Run crahed
282     std::string msg = "Issue with mesh_launcher: \n";
283     msg += "See log for more details: " + log_file.string() + "\n";
284     msg += cmd + "\n";
285     throw SALOME_Exception(msg);
286   }
287
288   {
289     SMESH_MeshLocker myLocker(&aMesh);
290     std::ifstream df(new_element_file.string(), ios::binary);
291
292     int totalPremeshedNodes;
293     int NetgenNbOfNodes;
294     int NetgenNbOfNodesNew;
295     int NetgenNbOfTriangles;
296     double NetgenPoint[3];
297     int    NetgenTriangle[3];
298     int nodeID;
299
300     SMESH_MesherHelper helper(aMesh);
301     // This function is mandatory for setElementsOnShape to work
302     helper.IsQuadraticSubMesh(aShape);
303     helper.SetElementsOnShape( true );
304
305     df.read((char*) &totalPremeshedNodes, sizeof(int));
306     // Number of nodes in intial mesh
307     df.read((char*) &NetgenNbOfNodes, sizeof(int));
308     // Number of nodes added by netgen
309     df.read((char*) &NetgenNbOfNodesNew, sizeof(int));
310
311     // Filling nodevec (correspondence netgen numbering mesh numbering)
312     vector< const SMDS_MeshNode* > nodeVec ( NetgenNbOfNodesNew + 2 );
313     SMESHDS_Mesh * meshDS = helper.GetMeshDS();
314     for (int nodeIndex = 1; nodeIndex <= NetgenNbOfNodes; ++nodeIndex )
315     {
316       //Id of the point
317       df.read((char*) &nodeID, sizeof(int));
318       nodeVec.at(nodeID) = meshDS->FindNode(nodeID);
319     }
320
321     // Add new points and update nodeVec
322     for (int nodeIndex = totalPremeshedNodes + 1; nodeIndex <= NetgenNbOfNodesNew; ++nodeIndex )
323     {
324       df.read((char *) &NetgenPoint, sizeof(double)*3);
325       nodeVec.at(nodeIndex) = helper.AddNode(NetgenPoint[0], NetgenPoint[1], NetgenPoint[2]);
326     }
327
328     // Add triangles
329     df.read((char*) &NetgenNbOfTriangles, sizeof(int));
330     for ( int elemIndex = 1; elemIndex <= NetgenNbOfTriangles; ++elemIndex )
331     {
332       df.read((char*) &NetgenTriangle, sizeof(int)*3);
333       if ( nodeVec.at( NetgenTriangle[0] ) && nodeVec.at( NetgenTriangle[1] ) && nodeVec.at( NetgenTriangle[2] ) )
334         helper.AddFace(nodeVec.at( NetgenTriangle[0] ), nodeVec.at( NetgenTriangle[1] ), nodeVec.at( NetgenTriangle[2] ) );            
335     }
336   }
337
338   return true;
339 }
340
341 /**
342  * @brief Assign submeshes to compute
343  *
344  * @param aSubMesh submesh to add
345  */
346 void NETGENPlugin_NETGEN_2D_Remote::setSubMeshesToCompute(SMESH_subMesh * aSubMesh)
347 {
348   SMESH_MeshLocker myLocker(aSubMesh->GetFather());
349   SMESH_Algo::setSubMeshesToCompute(aSubMesh);
350 }