Salome HOME
NETGEN_2D_Remote.Paramters was returning a 3D Hypotesis
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_2D_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_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(SMESH_Mesh& aMesh,
152                                                       const TopoDS_Shape& aShape,
153                                                       const std::string output_file)
154 {
155   std::ofstream df(output_file, ios::out|ios::binary);
156   int size=0;
157   df.write((char*)&size, sizeof(int));
158   df.close();
159 }
160
161 /**
162  * @brief Compute mesh associate to shape
163  *
164  * @param aMesh The mesh
165  * @param aShape The shape
166  * @return true fi there are some error
167  */
168 bool NETGENPlugin_NETGEN_2D_Remote::Compute(SMESH_Mesh&         aMesh,
169                                            const TopoDS_Shape& aShape)
170 {
171   {
172     SMESH_MeshLocker myLocker(&aMesh);
173     SMESH_Hypothesis::Hypothesis_Status hypStatus;
174     NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis(aMesh, aShape, hypStatus);
175   }
176   SMESH_ParallelMesh& aParMesh = dynamic_cast<SMESH_ParallelMesh&>(aMesh);
177
178   // Temporary folder for run
179 #ifdef WIN32
180   fs::path tmp_folder = aParMesh.GetTmpFolder() / fs::path("Volume-%%%%-%%%%");
181 #else
182   fs::path tmp_folder = aParMesh.GetTmpFolder() / fs::unique_path(fs::path("Volume-%%%%-%%%%"));
183 #endif
184   fs::create_directories(tmp_folder);
185   // Using MESH2D generated after all triangles where created.
186   fs::path mesh_file=aParMesh.GetTmpFolder() / fs::path("Mesh1D.med"); // read the premeshed elements from 2D version
187   fs::path element_orientation_file=tmp_folder / fs::path("element_orientation.dat");
188   fs::path new_element_file=tmp_folder / fs::path("new_elements.dat");
189   // Not used kept for debug
190   //fs::path output_mesh_file=tmp_folder / fs::path("output_mesh.med");
191   fs::path shape_file=tmp_folder / fs::path("shape.brep");
192   fs::path param_file=tmp_folder / fs::path("netgen_lenghtfromedge.txt"); /*becuase name contain 'lenghtfromedge' set length of 2D from premeshed 1D elements*/
193   fs::path log_file=tmp_folder / fs::path("run.log");
194   fs::path cmd_file=tmp_folder / fs::path("cmd.txt");
195   std::string mesh_name = "MESH";
196
197   {
198     SMESH_MeshLocker myLocker(&aMesh);
199     //Writing Shape
200     SMESH_DriverShape::exportShape(shape_file.string(), aShape);
201
202     //Writing hypo
203     // netgen_params aParams;
204     // fillParameters(_hypParameters, aParams);
205     // exportNetgenParams(param_file.string(), aParams);
206     {
207       // Simply write the file with the proper name
208       std::ofstream myfile(param_file);
209       myfile << 1 << std::endl;
210       myfile.close();
211     }
212       
213     // Exporting element orientation
214     exportElementOrientation(aMesh, aShape, element_orientation_file.string());
215   }
216
217   // Calling run_mesher
218   // Path to mesher script
219   fs::path mesher_launcher = fs::path(std::getenv("SMESH_ROOT_DIR"))/
220        fs::path("bin")/
221        fs::path("salome")/
222        fs::path("mesher_launcher.py");
223
224
225   std::string s_program="python3";
226   std::list<std::string> params;
227   params.push_back(mesher_launcher.string());
228   params.push_back("NETGEN2D");
229   params.push_back(mesh_file.string());
230   params.push_back(shape_file.string());
231   params.push_back(param_file.string());
232   params.push_back("--elem-orient-file=" + element_orientation_file.string());
233   params.push_back("--new-element-file=" + new_element_file.string());
234   // params.push_back("--output-mesh-file=" + output_mesh_file.string());
235
236   // Parallelism method parameters
237   int method = aParMesh.GetParallelismMethod();
238   if(method == ParallelismMethod::MultiThread){
239     params.push_back("--method=local");
240   } else if (method == ParallelismMethod::MultiNode){
241     params.push_back("--method=cluster");
242     params.push_back("--resource="+aParMesh.GetResource());
243     params.push_back("--wc-key="+aParMesh.GetWcKey());
244     params.push_back("--nb-proc=1");
245     params.push_back("--nb-proc-per-node="+to_string(aParMesh.GetNbProcPerNode()));
246     params.push_back("--nb-node="+to_string(aParMesh.GetNbNode()));
247     params.push_back("--walltime="+aParMesh.GetWalltime());
248   } else {
249     throw SALOME_Exception("Unknown parallelism method "+method);
250   }
251   std::string cmd = "";
252   cmd += s_program;
253   for(auto arg: params){
254     cmd += " " + arg;
255   }
256   MESSAGE("Running command: ");
257   MESSAGE(cmd);
258   // Writing command in cmd.log
259   {
260     std::ofstream flog(cmd_file.string());
261     flog << cmd << endl;
262   }
263
264   // Building arguments for QProcess
265   QString program = QString::fromStdString(s_program);
266   QStringList arguments;
267   for(auto arg : params){
268     arguments << arg.c_str();
269   }
270
271   QString out_file = log_file.string().c_str();
272   QProcess myProcess;
273   // myProcess.setProcessChannelMode(QProcess::MergedChannels);
274   myProcess.setProcessChannelMode(QProcess::ForwardedChannels);
275   myProcess.setStandardOutputFile(out_file);
276
277   myProcess.start(program, arguments);
278   // Waiting for process to finish (argument -1 make it wait until the end of
279   // the process otherwise it just waits 30 seconds)
280   bool finished = myProcess.waitForFinished(-1);
281   int ret = myProcess.exitCode();
282   if(ret != 0 || !finished){
283     // Run crahed
284     std::string msg = "Issue with mesh_launcher: \n";
285     msg += "See log for more details: " + log_file.string() + "\n";
286     msg += cmd + "\n";
287     throw SALOME_Exception(msg);
288   }
289
290   {
291     SMESH_MeshLocker myLocker(&aMesh);
292     std::ifstream df(new_element_file.string(), ios::binary);
293
294     int totalPremeshedNodes;
295     int NetgenNbOfNodes;
296     int NetgenNbOfNodesNew;
297     int NetgenNbOfTriangles;
298     double NetgenPoint[3];
299     int    NetgenTriangle[3];
300     int nodeID;
301
302     SMESH_MesherHelper helper(aMesh);
303     // This function is mandatory for setElementsOnShape to work
304     helper.IsQuadraticSubMesh(aShape);
305     helper.SetElementsOnShape( true );
306
307     df.read((char*) &totalPremeshedNodes, sizeof(int));
308     // Number of nodes in intial mesh
309     df.read((char*) &NetgenNbOfNodes, sizeof(int));
310     // Number of nodes added by netgen
311     df.read((char*) &NetgenNbOfNodesNew, sizeof(int));
312
313     // Filling nodevec (correspondence netgen numbering mesh numbering)
314     vector< const SMDS_MeshNode* > nodeVec ( NetgenNbOfNodesNew + 2 );
315     SMESHDS_Mesh * meshDS = helper.GetMeshDS();
316     for (int nodeIndex = 1; nodeIndex <= NetgenNbOfNodes; ++nodeIndex )
317     {
318       //Id of the point
319       df.read((char*) &nodeID, sizeof(int));
320       nodeVec.at(nodeID) = meshDS->FindNode(nodeID);
321     }
322
323     // Add new points and update nodeVec
324     for (int nodeIndex = totalPremeshedNodes + 1; nodeIndex <= NetgenNbOfNodesNew; ++nodeIndex )
325     {
326       df.read((char *) &NetgenPoint, sizeof(double)*3);
327       nodeVec.at(nodeIndex) = helper.AddNode(NetgenPoint[0], NetgenPoint[1], NetgenPoint[2]);
328     }
329
330     // Add triangles
331     df.read((char*) &NetgenNbOfTriangles, sizeof(int));
332     for ( int elemIndex = 1; elemIndex <= NetgenNbOfTriangles; ++elemIndex )
333     {
334       df.read((char*) &NetgenTriangle, sizeof(int)*3);
335       if ( nodeVec.at( NetgenTriangle[0] ) && nodeVec.at( NetgenTriangle[1] ) && nodeVec.at( NetgenTriangle[2] ) )
336         helper.AddFace(nodeVec.at( NetgenTriangle[0] ), nodeVec.at( NetgenTriangle[1] ), nodeVec.at( NetgenTriangle[2] ) );            
337     }
338   }
339
340   return true;
341 }
342
343 /**
344  * @brief Assign submeshes to compute
345  *
346  * @param aSubMesh submesh to add
347  */
348 void NETGENPlugin_NETGEN_2D_Remote::setSubMeshesToCompute(SMESH_subMesh * aSubMesh)
349 {
350   SMESH_MeshLocker myLocker(aSubMesh->GetFather());
351   SMESH_Algo::setSubMeshesToCompute(aSubMesh);
352 }