1 // Copyright (C) 2007-2023 CEA, EDF, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
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.
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.
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
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 //=============================================================================
24 // File : NETGENPlugin_NETGEN_3D_Remote.cxx
25 // Created : lundi 19 Septembre 2022
26 // Author : Yoann AUDOUIN (CEA)
28 //=============================================================================
31 #include "NETGENPlugin_NETGEN_3D_Remote.hxx"
33 #include "NETGENPlugin_NETGEN_3D.hxx"
35 #include "NETGENPlugin_DriverParam.hxx"
36 #include "NETGENPlugin_Hypothesis.hxx"
38 #include "Utils_SALOME_Exception.hxx"
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>
52 #include <boost/filesystem.hpp>
53 namespace fs = boost::filesystem;
61 #include <occgeom.hpp>
64 #include <ngexception.hpp>
67 #include <core/exception.hpp>
75 NETGENPLUGIN_DLL_HEADER
76 extern MeshingParameters mparam;
78 NETGENPLUGIN_DLL_HEADER
79 extern volatile multithreadt multithread;
81 using namespace nglib;
83 //=============================================================================
87 //=============================================================================
89 NETGENPlugin_NETGEN_3D_Remote::NETGENPlugin_NETGEN_3D_Remote(int hypId, SMESH_Gen * gen)
90 : NETGENPlugin_NETGEN_3D(hypId, gen)
92 _name = "NETGEN_3D_Remote";
95 //=============================================================================
99 //=============================================================================
101 NETGENPlugin_NETGEN_3D_Remote::~NETGENPlugin_NETGEN_3D_Remote()
106 * @brief Fill the structure netgen_param with the information from the hypothesis
108 * @param hyp the hypothesis
109 * @param aParams the netgen_param structure
111 void NETGENPlugin_NETGEN_3D_Remote::fillParameters(const NETGENPlugin_Hypothesis* hyp, netgen_params &aParams)
113 aParams.myType = hypoType::Hypo;
114 aParams.maxh = hyp->GetMaxSize();
115 aParams.minh = hyp->GetMinSize();
116 aParams.segmentsperedge = hyp->GetNbSegPerEdge();
117 aParams.grading = hyp->GetGrowthRate();
118 aParams.curvaturesafety = hyp->GetNbSegPerRadius();
119 aParams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
120 aParams.quad = hyp->GetQuadAllowed() ? 1 : 0;
121 aParams.optimize = hyp->GetOptimize();
122 aParams.fineness = hyp->GetFineness();
123 aParams.uselocalh = hyp->GetSurfaceCurvature();
124 aParams.merge_solids = hyp->GetFuseEdges();
125 aParams.chordalError = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
126 aParams.optsteps2d = aParams.optimize ? hyp->GetNbSurfOptSteps() : 0;
127 aParams.optsteps3d = aParams.optimize ? hyp->GetNbVolOptSteps() : 0;
128 aParams.elsizeweight = hyp->GetElemSizeWeight();
129 aParams.opterrpow = hyp->GetWorstElemMeasure();
130 aParams.delaunay = hyp->GetUseDelauney();
131 aParams.checkoverlap = hyp->GetCheckOverlapping();
132 aParams.checkchartboundary = hyp->GetCheckChartBoundary();
135 aParams.meshsizefilename = hyp->GetMeshSizeFile();
136 aParams.closeedgefac = 2;
137 aParams.nbThreads = hyp->GetNbThreads();
140 aParams.meshsizefilename = hyp->GetMeshSizeFile();
141 aParams.closeedgefac = 0;
142 aParams.nbThreads = 0;
149 * @brief write in a binary file the orientation for each surface element of the mesh
151 * @param aMesh The mesh
152 * @param aShape the shape associated to the mesh
153 * @param output_file name of the binary file
155 void NETGENPlugin_NETGEN_3D_Remote::exportElementOrientation(SMESH_Mesh& aMesh,
156 const TopoDS_Shape& aShape,
157 const std::string output_file)
159 SMESH_MesherHelper helper(aMesh);
160 NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
161 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
162 std::map<vtkIdType, bool> elemOrientation;
164 for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
166 const TopoDS_Shape& aShapeFace = exFa.Current();
167 int faceID = aMesh.GetMeshDS()->ShapeToIndex( aShapeFace );
168 bool isInternalFace = internals.isInternalShape( faceID );
170 if ( !isInternalFace &&
171 helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
172 // IsReversedSubMesh() can work wrong on strongly curved faces,
173 // so we use it as less as possible
174 isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
176 const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
177 if ( !aSubMeshDSFace ) continue;
179 SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
180 if ( _quadraticMesh &&
181 dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
183 // add medium nodes of proxy triangles to helper (#16843)
184 while ( iteratorElem->more() )
185 helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
187 iteratorElem = aSubMeshDSFace->GetElements();
189 while ( iteratorElem->more() ) // loop on elements on a geom face
192 const SMDS_MeshElement* elem = iteratorElem->next();
194 error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
195 if ( elem->NbCornerNodes() != 3 )
196 error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
197 elemOrientation[elem->GetID()] = isRev;
198 } // loop on elements on a face
199 } // loop on faces of a SOLID or SHELL
202 std::ofstream df(output_file, ios::out|ios::binary);
203 int size=elemOrientation.size();
205 df.write((char*)&size, sizeof(int));
206 for(auto const& [id, orient]:elemOrientation){
207 df.write((char*)&id, sizeof(vtkIdType));
208 df.write((char*)&orient, sizeof(bool));
214 * @brief Compute mesh associate to shape
216 * @param aMesh The mesh
217 * @param aShape The shape
218 * @return true fi there are some error
220 bool NETGENPlugin_NETGEN_3D_Remote::Compute(SMESH_Mesh& aMesh,
221 const TopoDS_Shape& aShape)
224 SMESH_MeshLocker myLocker(&aMesh);
225 SMESH_Hypothesis::Hypothesis_Status hypStatus;
226 NETGENPlugin_NETGEN_3D::CheckHypothesis(aMesh, aShape, hypStatus);
228 SMESH_ParallelMesh& aParMesh = dynamic_cast<SMESH_ParallelMesh&>(aMesh);
230 // Temporary folder for run
232 fs::path tmp_folder = aParMesh.GetTmpFolder() / fs::path("Volume-%%%%-%%%%");
234 fs::path tmp_folder = aParMesh.GetTmpFolder() / fs::unique_path(fs::path("Volume-%%%%-%%%%"));
236 fs::create_directories(tmp_folder);
237 // Using MESH2D generated after all triangles where created.
238 fs::path mesh_file=aParMesh.GetTmpFolder() / fs::path("Mesh2D.med");
239 fs::path element_orientation_file=tmp_folder / fs::path("element_orientation.dat");
240 fs::path new_element_file=tmp_folder / fs::path("new_elements.dat");
241 fs::path tmp_mesh_file=tmp_folder / fs::path("tmp_mesh.med");
242 // Not used kept for debug
243 //fs::path output_mesh_file=tmp_folder / fs::path("output_mesh.med");
244 fs::path shape_file=tmp_folder / fs::path("shape.brep");
245 fs::path param_file=tmp_folder / fs::path("netgen3d_param.txt");
246 fs::path log_file=tmp_folder / fs::path("run.log");
247 fs::path cmd_file=tmp_folder / fs::path("cmd.txt");
248 // TODO: See if we can retreived name from aMesh ?
249 std::string mesh_name = "MESH";
252 SMESH_MeshLocker myLocker(&aMesh);
254 SMESH_DriverShape::exportShape(shape_file.string(), aShape);
257 netgen_params aParams;
258 fillParameters(_hypParameters, aParams);
260 exportNetgenParams(param_file.string(), aParams);
262 // Exporting element orientation
263 exportElementOrientation(aMesh, aShape, element_orientation_file.string());
266 // Calling run_mesher
267 // Path to mesher script
268 fs::path mesher_launcher = fs::path(std::getenv("SMESH_ROOT_DIR"))/
271 fs::path("mesher_launcher.py");
274 std::string s_program="python3";
275 std::list<std::string> params;
276 params.push_back(mesher_launcher.string());
277 params.push_back("NETGEN3D");
278 params.push_back(mesh_file.string());
279 params.push_back(shape_file.string());
280 params.push_back(param_file.string());
281 params.push_back("--elem-orient-file=" + element_orientation_file.string());
282 params.push_back("--new-element-file=" + new_element_file.string());
284 // Parallelism method parameters
285 int method = aParMesh.GetParallelismMethod();
286 if(method == ParallelismMethod::MultiThread){
287 params.push_back("--method=local");
288 } else if (method == ParallelismMethod::MultiNode){
289 params.push_back("--method=cluster");
290 params.push_back("--resource="+aParMesh.GetResource());
291 params.push_back("--wc-key="+aParMesh.GetWcKey());
292 params.push_back("--nb-proc=1");
293 params.push_back("--nb-proc-per-node="+to_string(aParMesh.GetNbProcPerNode()));
294 params.push_back("--nb-node="+to_string(aParMesh.GetNbNode()));
295 params.push_back("--walltime="+aParMesh.GetWalltime());
297 throw SALOME_Exception("Unknown parallelism method "+method);
299 std::string cmd = "";
301 for(auto arg: params){
304 MESSAGE("Running command: ");
306 // Writing command in cmd.log
308 std::ofstream flog(cmd_file.string());
312 // Building arguments for QProcess
313 QString program = QString::fromStdString(s_program);
314 QStringList arguments;
315 for(auto arg : params){
316 arguments << arg.c_str();
319 QString out_file = log_file.string().c_str();
321 myProcess.setProcessChannelMode(QProcess::MergedChannels);
322 myProcess.setStandardOutputFile(out_file);
324 myProcess.start(program, arguments);
325 // Waiting for process to finish (argument -1 make it wait until the end of
326 // the process otherwise it just waits 30 seconds)
327 bool finished = myProcess.waitForFinished(-1);
328 int ret = myProcess.exitCode();
330 if(ret != 0 || !finished){
332 std::string msg = "Issue with mesh_launcher: \n";
333 msg += "See log for more details: " + log_file.string() + "\n";
335 throw SALOME_Exception(msg);
339 SMESH_MeshLocker myLocker(&aMesh);
340 std::ifstream df(new_element_file.string(), ios::binary);
342 int Netgen_NbOfNodes;
343 int Netgen_NbOfNodesNew;
344 int Netgen_NbOfTetra;
345 double Netgen_point[3];
346 int Netgen_tetrahedron[4];
349 SMESH_MesherHelper helper(aMesh);
350 // This function is mandatory for setElementsOnShape to work
351 helper.IsQuadraticSubMesh(aShape);
352 helper.SetElementsOnShape( true );
354 // Number of nodes in intial mesh
355 df.read((char*) &Netgen_NbOfNodes, sizeof(int));
356 // Number of nodes added by netgen
357 df.read((char*) &Netgen_NbOfNodesNew, sizeof(int));
359 // Filling nodevec (correspondence netgen numbering mesh numbering)
360 vector< const SMDS_MeshNode* > nodeVec ( Netgen_NbOfNodesNew + 1 );
361 //vector<int> nodeTmpVec ( Netgen_NbOfNodesNew + 1 );
362 SMESHDS_Mesh * meshDS = helper.GetMeshDS();
363 for (int nodeIndex = 1 ; nodeIndex <= Netgen_NbOfNodes; ++nodeIndex )
366 df.read((char*) &nodeID, sizeof(int));
367 nodeVec.at(nodeIndex) = meshDS->FindNode(nodeID);
370 // Add new points and update nodeVec
371 for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
373 df.read((char *) &Netgen_point, sizeof(double)*3);
375 nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
381 df.read((char*) &Netgen_NbOfTetra, sizeof(int));
383 for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
385 df.read((char*) &Netgen_tetrahedron, sizeof(int)*4);
387 nodeVec.at( Netgen_tetrahedron[0] ),
388 nodeVec.at( Netgen_tetrahedron[1] ),
389 nodeVec.at( Netgen_tetrahedron[2] ),
390 nodeVec.at( Netgen_tetrahedron[3] ));
398 * @brief Assign submeshes to compute
400 * @param aSubMesh submesh to add
402 void NETGENPlugin_NETGEN_3D_Remote::setSubMeshesToCompute(SMESH_subMesh * aSubMesh)
404 SMESH_MeshLocker myLocker(aSubMesh->GetFather());
405 SMESH_Algo::setSubMeshesToCompute(aSubMesh);