]> SALOME platform Git repositories - plugins/netgenplugin.git/blob - src/NETGENPlugin/NETGENPlugin_NETGEN_3D_Remote.cxx
Salome HOME
Cleanup use of netgen_params + restoring use of netgen error functions
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_3D_Remote.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_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_MesherHelper.hxx>
43 #include <SMESH_DriverShape.hxx>
44 #include <SMESH_DriverMesh.hxx>
45 #include <SMESHDS_Mesh.hxx>
46 #include <SMESH_MeshLocker.hxx>
47
48 #include <QString>
49 #include <QProcess>
50
51 #include <boost/filesystem.hpp>
52 namespace fs = boost::filesystem;
53
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  *
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  *
98  */
99 //=============================================================================
100
101 NETGENPlugin_NETGEN_3D_Remote::~NETGENPlugin_NETGEN_3D_Remote()
102 {
103 }
104
105
106 void NETGENPlugin_NETGEN_3D_Remote::fillParameters(const NETGENPlugin_Hypothesis* hyp, netgen_params &aParams)
107 {
108   aParams.maxh               = hyp->GetMaxSize();
109   aParams.minh               = hyp->GetMinSize();
110   aParams.segmentsperedge    = hyp->GetNbSegPerEdge();
111   aParams.grading            = hyp->GetGrowthRate();
112   aParams.curvaturesafety    = hyp->GetNbSegPerRadius();
113   aParams.secondorder        = hyp->GetSecondOrder() ? 1 : 0;
114   aParams.quad               = hyp->GetQuadAllowed() ? 1 : 0;
115   aParams.optimize           = hyp->GetOptimize();
116   aParams.fineness           = hyp->GetFineness();
117   aParams.uselocalh          = hyp->GetSurfaceCurvature();
118   aParams.merge_solids       = hyp->GetFuseEdges();
119   aParams.chordalError       = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
120   aParams.optsteps2d         = aParams.optimize ? hyp->GetNbSurfOptSteps() : 0;
121   aParams.optsteps3d         = aParams.optimize ? hyp->GetNbVolOptSteps()  : 0;
122   aParams.elsizeweight       = hyp->GetElemSizeWeight();
123   aParams.opterrpow          = hyp->GetWorstElemMeasure();
124   aParams.delaunay           = hyp->GetUseDelauney();
125   aParams.checkoverlap       = hyp->GetCheckOverlapping();
126   aParams.checkchartboundary = hyp->GetCheckChartBoundary();
127 #ifdef NETGEN_V6
128   // std::string
129   aParams.meshsizefilename = hyp->GetMeshSizeFile();
130 #else
131   // const char*
132   aParams.meshsizefilename = hyp->GetMeshSizeFile();
133 #endif
134 #ifdef NETGEN_V6
135   aParams.closeedgefac = 2;
136 #else
137   aParams.closeedgefac = 0;
138 #endif
139 }
140
141 // write in a binary file the orientation for each 2D element of the mesh
142 void NETGENPlugin_NETGEN_3D_Remote::exportElementOrientation(SMESH_Mesh& aMesh,
143                                                       const TopoDS_Shape& aShape,
144                                                       const std::string output_file)
145 {
146   SMESH_MesherHelper helper(aMesh);
147   NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
148   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
149   std::map<vtkIdType, bool> elemOrientation;
150
151   for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
152   {
153     const TopoDS_Shape& aShapeFace = exFa.Current();
154     int faceID = aMesh.GetMeshDS()->ShapeToIndex( aShapeFace );
155     bool isInternalFace = internals.isInternalShape( faceID );
156     bool isRev = false;
157     if ( !isInternalFace &&
158           helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
159       // IsReversedSubMesh() can work wrong on strongly curved faces,
160       // so we use it as less as possible
161       isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
162
163     const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
164     if ( !aSubMeshDSFace ) continue;
165
166     SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
167     if ( _quadraticMesh &&
168           dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
169     {
170       // add medium nodes of proxy triangles to helper (#16843)
171       while ( iteratorElem->more() )
172         helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
173
174       iteratorElem = aSubMeshDSFace->GetElements();
175     }
176     while ( iteratorElem->more() ) // loop on elements on a geom face
177     {
178       // check mesh face
179       const SMDS_MeshElement* elem = iteratorElem->next();
180       if ( !elem )
181         error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
182       if ( elem->NbCornerNodes() != 3 )
183         error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
184       elemOrientation[elem->GetID()] = isRev;
185     } // loop on elements on a face
186   } // loop on faces of a SOLID or SHELL
187
188   {
189     std::ofstream df(output_file, ios::out|ios::binary);
190     int size=elemOrientation.size();
191
192     df.write((char*)&size, sizeof(int));
193     for(auto const& [id, orient]:elemOrientation){
194       df.write((char*)&id, sizeof(vtkIdType));
195       df.write((char*)&orient, sizeof(bool));
196     }
197   }
198 }
199
200
201 bool NETGENPlugin_NETGEN_3D_Remote::Compute(SMESH_Mesh&         aMesh,
202                                            const TopoDS_Shape& aShape)
203 {
204   {
205     SMESH_MeshLocker myLocker(&aMesh);
206     SMESH_Hypothesis::Hypothesis_Status hypStatus;
207     NETGENPlugin_NETGEN_3D::CheckHypothesis(aMesh, aShape, hypStatus);
208   }
209
210
211   // Temporary folder for run
212   fs::path tmp_folder = aMesh.tmp_folder / fs::unique_path(fs::path("Volume-%%%%-%%%%"));
213   fs::create_directories(tmp_folder);
214   // Using MESH2D generated after all triangles where created.
215   fs::path mesh_file=aMesh.tmp_folder / fs::path("Mesh2D.med");
216   fs::path element_orientation_file=tmp_folder / fs::path("element_orientation.dat");
217   fs::path new_element_file=tmp_folder / fs::path("new_elements.dat");
218   fs::path tmp_mesh_file=tmp_folder / fs::path("tmp_mesh.med");
219   // Not used kept for debug
220   //fs::path output_mesh_file=tmp_folder / fs::path("output_mesh.med");
221   fs::path shape_file=tmp_folder / fs::path("shape.brep");
222   fs::path param_file=tmp_folder / fs::path("netgen3d_param.txt");
223   fs::path log_file=tmp_folder / fs::path("run.log");
224   fs::path cmd_file=tmp_folder / fs::path("cmd.log");
225   //TODO: Handle variable mesh_name
226   std::string mesh_name = "MESH";
227
228   {
229     SMESH_MeshLocker myLocker(&aMesh);
230     //Writing Shape
231     exportShape(shape_file.string(), aShape);
232
233     //Writing hypo
234     netgen_params aParams;
235     fillParameters(_hypParameters, aParams);
236
237     exportNetgenParams(param_file.string(), aParams);
238
239     // Exporting element orientation
240     exportElementOrientation(aMesh, aShape, element_orientation_file.string());
241   }
242
243   // Calling run_mesher
244   // TODO: check if we need to handle the .exe for windows
245   std::string cmd;
246   fs::path run_mesher_exe =
247     fs::path(std::getenv("NETGENPLUGIN_ROOT_DIR"))/
248     fs::path("bin")/
249     fs::path("salome")/
250     fs::path("NETGENPlugin_Runner");
251
252   cmd = run_mesher_exe.string() +
253                   " NETGEN3D " + mesh_file.string() + " "
254                                + shape_file.string() + " "
255                                + param_file.string() + " "
256                                + element_orientation_file.string() + " "
257                                + std::to_string(aMesh.GetMesherNbThreads()) + " "
258                                + new_element_file.string() + " "
259                                + "NONE";
260   // Writing command in log
261   {
262     std::ofstream flog(cmd_file.string());
263     flog << cmd << endl;
264     flog << endl;
265   }
266   MESSAGE("Running command: ");
267   MESSAGE(cmd);
268
269
270   // Building arguments for QProcess
271   QString program = run_mesher_exe.c_str();
272   QStringList arguments;
273   arguments << "NETGEN3D";
274   arguments << mesh_file.c_str();
275   arguments << shape_file.c_str();
276   arguments << param_file.c_str();
277   arguments << element_orientation_file.c_str();
278   arguments << std::to_string(aMesh.GetMesherNbThreads()).c_str();
279   arguments << new_element_file.c_str();
280   arguments << "NONE";
281   QString out_file = log_file.c_str();
282   QProcess myProcess;
283   myProcess.setStandardOutputFile(out_file);
284
285   myProcess.start(program, arguments);
286   myProcess.waitForFinished();
287   int ret = myProcess.exitStatus();
288
289   if(ret != 0){
290     // Run crahed
291     std::string msg = "Issue with command: \n";
292     msg += "See log for more details: " + log_file.string() + "\n";
293     msg += cmd + "\n";
294     throw SALOME_Exception(msg);
295   }
296
297   {
298     SMESH_MeshLocker myLocker(&aMesh);
299     std::ifstream df(new_element_file.string(), ios::binary);
300
301     int Netgen_NbOfNodes;
302     int Netgen_NbOfNodesNew;
303     int Netgen_NbOfTetra;
304     double Netgen_point[3];
305     int    Netgen_tetrahedron[4];
306     int nodeID;
307
308     SMESH_MesherHelper helper(aMesh);
309     // This function is mandatory for setElementsOnShape to work
310     helper.IsQuadraticSubMesh(aShape);
311     helper.SetElementsOnShape( true );
312
313     // Number of nodes in intial mesh
314     df.read((char*) &Netgen_NbOfNodes, sizeof(int));
315     // Number of nodes added by netgen
316     df.read((char*) &Netgen_NbOfNodesNew, sizeof(int));
317
318     // Filling nodevec (correspondence netgen numbering mesh numbering)
319     vector< const SMDS_MeshNode* > nodeVec ( Netgen_NbOfNodesNew + 1 );
320     //vector<int> nodeTmpVec ( Netgen_NbOfNodesNew + 1 );
321     SMESHDS_Mesh * meshDS = helper.GetMeshDS();
322     for (int nodeIndex = 1 ; nodeIndex <= Netgen_NbOfNodes; ++nodeIndex )
323     {
324       //Id of the point
325       df.read((char*) &nodeID, sizeof(int));
326       nodeVec.at(nodeIndex) = meshDS->FindNode(nodeID);
327     }
328
329     // Add new points and update nodeVec
330     for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
331     {
332       df.read((char *) &Netgen_point, sizeof(double)*3);
333
334       nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
335                                  Netgen_point[1],
336                                  Netgen_point[2]);
337     }
338
339     // Add tetrahedrons
340     df.read((char*) &Netgen_NbOfTetra, sizeof(int));
341
342     for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
343     {
344       df.read((char*) &Netgen_tetrahedron, sizeof(int)*4);
345       helper.AddVolume(
346                     nodeVec.at( Netgen_tetrahedron[0] ),
347                     nodeVec.at( Netgen_tetrahedron[1] ),
348                     nodeVec.at( Netgen_tetrahedron[2] ),
349                     nodeVec.at( Netgen_tetrahedron[3] ));
350     }
351   }
352
353   return true;
354 }
355
356
357 void NETGENPlugin_NETGEN_3D_Remote::setSubMeshesToCompute(SMESH_subMesh * aSubMesh)
358 {
359   SMESH_MeshLocker myLocker(aSubMesh->GetFather());
360   SMESH_Algo::setSubMeshesToCompute(aSubMesh);
361 }