1 // Copyright (C) 2007-2022 CEA/DEN, EDF R&D, 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.cxx
25 // Moved here from SMESH_NETGEN_3D.cxx
26 // Created : lundi 27 Janvier 2003
27 // Author : Nadir BOUHAMOU (CEA)
29 //=============================================================================
31 #include "NETGENPlugin_NETGEN_3D.hxx"
33 #include "NETGENPlugin_Hypothesis.hxx"
35 #include "DriverStep.hxx"
36 #include "DriverMesh.hxx"
37 #include "netgen_param.hxx"
39 #include <SMDS_MeshElement.hxx>
40 #include <SMDS_MeshNode.hxx>
41 #include <SMESHDS_Mesh.hxx>
42 #include <SMESH_Comment.hxx>
43 #include <SMESH_ControlsDef.hxx>
44 #include <SMESH_Gen.hxx>
45 #include <SMESH_Mesh.hxx>
46 #include <SMESH_MeshEditor.hxx>
47 #include <SMESH_MesherHelper.hxx>
48 #include <SMESH_subMesh.hxx>
49 #include <StdMeshers_MaxElementVolume.hxx>
50 #include <StdMeshers_QuadToTriaAdaptor.hxx>
51 #include <StdMeshers_ViscousLayers.hxx>
52 #include <SMESH_subMesh.hxx>
54 #include <BRepGProp.hxx>
55 #include <BRep_Tool.hxx>
56 #include <GProp_GProps.hxx>
58 #include <TopExp_Explorer.hxx>
59 #include <TopTools_ListIteratorOfListOfShape.hxx>
62 #include <Standard_Failure.hxx>
63 #include <Standard_ErrorHandler.hxx>
65 #include <utilities.h>
72 #include <boost/filesystem.hpp>
73 namespace fs = boost::filesystem;
82 #include <occgeom.hpp>
85 #include <ngexception.hpp>
88 #include <core/exception.hpp>
96 NETGENPLUGIN_DLL_HEADER
97 extern MeshingParameters mparam;
99 NETGENPLUGIN_DLL_HEADER
100 extern volatile multithreadt multithread;
102 using namespace nglib;
105 //=============================================================================
109 //=============================================================================
111 NETGENPlugin_NETGEN_3D::NETGENPlugin_NETGEN_3D(int hypId, SMESH_Gen* gen)
112 : SMESH_3D_Algo(hypId, gen)
115 _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
116 _compatibleHypothesis.push_back("MaxElementVolume");
117 _compatibleHypothesis.push_back("NETGEN_Parameters");
118 _compatibleHypothesis.push_back("ViscousLayers");
120 _maxElementVolume = 0.;
122 _hypMaxElementVolume = NULL;
123 _hypParameters = NULL;
124 _viscousLayersHyp = NULL;
126 _requireShape = false; // can work without shape
129 //=============================================================================
133 //=============================================================================
135 NETGENPlugin_NETGEN_3D::~NETGENPlugin_NETGEN_3D()
139 //=============================================================================
143 //=============================================================================
145 bool NETGENPlugin_NETGEN_3D::CheckHypothesis (SMESH_Mesh& aMesh,
146 const TopoDS_Shape& aShape,
147 Hypothesis_Status& aStatus)
149 _hypMaxElementVolume = NULL;
150 _hypParameters = NULL;
151 _viscousLayersHyp = NULL;
152 _maxElementVolume = DBL_MAX;
154 // for correct work of GetProgress():
155 //netgen::multithread.percent = 0.;
156 //netgen::multithread.task = "Volume meshing";
157 _progressByTic = -1.;
159 list<const SMESHDS_Hypothesis*>::const_iterator itl;
160 //const SMESHDS_Hypothesis* theHyp;
162 const list<const SMESHDS_Hypothesis*>& hyps =
163 GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
164 list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
165 if ( h == hyps.end())
167 aStatus = SMESH_Hypothesis::HYP_OK;
168 return true; // can work with no hypothesis
172 for ( ; h != hyps.end(); ++h )
174 if ( !_hypMaxElementVolume )
175 _hypMaxElementVolume = dynamic_cast< const StdMeshers_MaxElementVolume*> ( *h );
176 if ( !_viscousLayersHyp ) // several _viscousLayersHyp's allowed
177 _viscousLayersHyp = dynamic_cast< const StdMeshers_ViscousLayers*> ( *h );
178 if ( ! _hypParameters )
179 _hypParameters = dynamic_cast< const NETGENPlugin_Hypothesis*> ( *h );
181 if ( *h != _hypMaxElementVolume &&
182 *h != _viscousLayersHyp &&
183 *h != _hypParameters &&
184 !dynamic_cast< const StdMeshers_ViscousLayers*>(*h)) // several VL hyps allowed
185 aStatus = HYP_INCOMPATIBLE;
187 if ( _hypMaxElementVolume && _hypParameters )
188 aStatus = HYP_INCOMPATIBLE;
189 else if ( aStatus == HYP_OK && _viscousLayersHyp )
190 error( _viscousLayersHyp->CheckHypothesis( aMesh, aShape, aStatus ));
192 if ( _hypMaxElementVolume )
193 _maxElementVolume = _hypMaxElementVolume->GetMaxVolume();
195 return aStatus == HYP_OK;
199 void NETGENPlugin_NETGEN_3D::FillParameters(const NETGENPlugin_Hypothesis* hyp, netgen_params &aParams)
201 aParams.maxh = hyp->GetMaxSize();
202 aParams.minh = hyp->GetMinSize();
203 aParams.segmentsperedge = hyp->GetNbSegPerEdge();
204 aParams.grading = hyp->GetGrowthRate();
205 aParams.curvaturesafety = hyp->GetNbSegPerRadius();
206 aParams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
207 aParams.quad = hyp->GetQuadAllowed() ? 1 : 0;
208 aParams.optimize = hyp->GetOptimize();
209 aParams.fineness = hyp->GetFineness();
210 aParams.uselocalh = hyp->GetSurfaceCurvature();
211 aParams.merge_solids = hyp->GetFuseEdges();
212 aParams.chordalError = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
213 aParams.optsteps2d = aParams.optimize ? hyp->GetNbSurfOptSteps() : 0;
214 aParams.optsteps3d = aParams.optimize ? hyp->GetNbVolOptSteps() : 0;
215 aParams.elsizeweight = hyp->GetElemSizeWeight();
216 aParams.opterrpow = hyp->GetWorstElemMeasure();
217 aParams.delaunay = hyp->GetUseDelauney();
218 aParams.checkoverlap = hyp->GetCheckOverlapping();
219 aParams.checkchartboundary = hyp->GetCheckChartBoundary();
222 aParams.meshsizefilename = hyp->GetMeshSizeFile();
225 aParams.meshsizefilename = hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
228 aParams.closeedgefac = 2;
230 aParams.closeedgefac = 0;
234 // write in a binary file the orientation for each 2D element of the mesh
235 void NETGENPlugin_NETGEN_3D::exportElementOrientation(SMESH_Mesh& aMesh,
236 const TopoDS_Shape& aShape,
237 netgen_params& aParams,
238 const std::string output_file)
240 SMESH_MesherHelper helper(aMesh);
241 NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
242 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
243 std::map<vtkIdType, bool> elemOrientation;
245 for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
247 const TopoDS_Shape& aShapeFace = exFa.Current();
248 int faceID = aMesh.GetMeshDS()->ShapeToIndex( aShapeFace );
249 bool isInternalFace = internals.isInternalShape( faceID );
251 if ( !isInternalFace &&
252 helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
253 // IsReversedSubMesh() can work wrong on strongly curved faces,
254 // so we use it as less as possible
255 isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
257 const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
258 if ( !aSubMeshDSFace ) continue;
260 SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
261 if ( aParams._quadraticMesh &&
262 dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
264 // add medium nodes of proxy triangles to helper (#16843)
265 while ( iteratorElem->more() )
266 helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
268 iteratorElem = aSubMeshDSFace->GetElements();
270 while ( iteratorElem->more() ) // loop on elements on a geom face
273 const SMDS_MeshElement* elem = iteratorElem->next();
275 error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
276 if ( elem->NbCornerNodes() != 3 )
277 error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
278 elemOrientation[elem->GetID()] = isRev;
279 } // loop on elements on a face
280 } // loop on faces of a SOLID or SHELL
282 std::ofstream df(output_file, ios::out|ios::binary);
283 int size=elemOrientation.size();
285 df.write((char*)&size, sizeof(int));
286 for(auto const& [id, orient]:elemOrientation){
287 df.write((char*)&id, sizeof(vtkIdType));
288 df.write((char*)&orient, sizeof(bool));
293 int NETGENPlugin_NETGEN_3D::RemoteCompute(SMESH_Mesh& aMesh,
294 const TopoDS_Shape& aShape)
297 auto time0 = std::chrono::high_resolution_clock::now();
298 SMESH_Hypothesis::Hypothesis_Status hypStatus;
299 CheckHypothesis(aMesh, aShape, hypStatus);
300 auto time1 = std::chrono::high_resolution_clock::now();
301 auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time1-time0);
302 std::cout << "Time for check_hypo: " << elapsed.count() * 1e-9 << std::endl;
305 // Temporary folder for run
306 fs::path tmp_folder = aMesh.tmp_folder / fs::unique_path(fs::path("Volume-%%%%-%%%%"));
307 fs::create_directories(tmp_folder);
308 // Using MESH2D generated after all triangles where created.
309 fs::path mesh_file=aMesh.tmp_folder / fs::path("Mesh2D.med");
310 fs::path element_orientation_file=tmp_folder / fs::path("element_orientation.dat");
311 fs::path new_element_file=tmp_folder / fs::path("new_elements.dat");
312 fs::path tmp_mesh_file=tmp_folder / fs::path("tmp_mesh.med");
313 // TODO: Remove that file we do not use it
314 fs::path output_mesh_file=tmp_folder / fs::path("output_mesh.med");
315 fs::path shape_file=tmp_folder / fs::path("shape.step");
316 fs::path param_file=tmp_folder / fs::path("netgen3d_param.txt");
317 fs::path log_file=tmp_folder / fs::path("run_mesher.log");
318 //TODO: Handle variable mesh_name
319 std::string mesh_name = "Maillage_1";
322 export_shape(shape_file.string(), aShape);
323 auto time2 = std::chrono::high_resolution_clock::now();
324 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time2-time1);
325 std::cout << "Time for export_shape: " << elapsed.count() * 1e-9 << std::endl;
328 netgen_params aParams;
329 FillParameters(_hypParameters, aParams);
331 export_netgen_params(param_file.string(), aParams);
332 auto time3 = std::chrono::high_resolution_clock::now();
333 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time3-time2);
334 std::cout << "Time for fill+export param: " << elapsed.count() * 1e-9 << std::endl;
336 // Exporting element orientation
337 exportElementOrientation(aMesh, aShape, aParams, element_orientation_file.string());
338 auto time4 = std::chrono::high_resolution_clock::now();
339 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time4-time3);
340 std::cout << "Time for exportElemnOrient: " << elapsed.count() * 1e-9 << std::endl;
343 // Calling run_mesher
344 // TODO: check if we need to handle the .exe for windows
346 fs::path run_mesher_exe =
347 fs::path(std::getenv("NETGENPLUGIN_ROOT_DIR"))/
350 fs::path("run_mesher");
351 cmd = run_mesher_exe.string() +
352 " NETGEN3D " + mesh_file.string() + " "
353 + shape_file.string() + " "
354 + param_file.string() + " "
355 + element_orientation_file.string() + " "
356 + new_element_file.string() + " "
357 + std::to_string(0) + " "
358 + output_mesh_file.string() +
359 " >> " + log_file.string();
361 //std::cout << "Running command: " << std::endl;
362 //std::cout << cmd << std::endl;
364 // Writing command in log
365 std::ofstream flog(log_file.string());
369 // TODO: Replace system by something else to handle redirection for windows
370 int ret = system(cmd.c_str());
371 auto time5 = std::chrono::high_resolution_clock::now();
372 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time5-time4);
373 std::cout << "Time for exec of run_mesher: " << elapsed.count() * 1e-9 << std::endl;
375 // TODO: better error handling (display log ?)
378 std::cerr << "Issue with command: " << std::endl;
379 std::cerr << cmd << std::endl;
384 std::ifstream df(new_element_file.string(), ios::binary);
386 int Netgen_NbOfNodes;
387 int Netgen_NbOfNodesNew;
388 int Netgen_NbOfTetra;
389 double Netgen_point[3];
390 int Netgen_tetrahedron[4];
393 SMESH_MesherHelper helper(aMesh);
395 int _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
396 helper.SetElementsOnShape( true );
398 // Number of nodes in intial mesh
399 df.read((char*) &Netgen_NbOfNodes, sizeof(int));
400 // Number of nodes added by netgen
401 df.read((char*) &Netgen_NbOfNodesNew, sizeof(int));
403 // Filling nodevec (correspondence netgen numbering mesh numbering)
404 vector< const SMDS_MeshNode* > nodeVec ( Netgen_NbOfNodesNew + 1 );
405 //vector<int> nodeTmpVec ( Netgen_NbOfNodesNew + 1 );
406 SMESHDS_Mesh * meshDS = helper.GetMeshDS();
407 for (int nodeIndex = 1 ; nodeIndex <= Netgen_NbOfNodes; ++nodeIndex )
410 df.read((char*) &nodeID, sizeof(int));
411 nodeVec.at(nodeIndex) = meshDS->FindNode(nodeID);
414 auto time6 = std::chrono::high_resolution_clock::now();
415 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time6-time5);
416 std::cout << "Time for exec of nodeVec: " << elapsed.count() * 1e-9 << std::endl;
419 // Add new points and update nodeVec
420 for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
422 df.read((char *) &Netgen_point, sizeof(double)*3);
424 nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
430 df.read((char*) &Netgen_NbOfTetra, sizeof(int));
432 for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
434 df.read((char*) &Netgen_tetrahedron, sizeof(int)*4);
436 nodeVec.at( Netgen_tetrahedron[0] ),
437 nodeVec.at( Netgen_tetrahedron[1] ),
438 nodeVec.at( Netgen_tetrahedron[2] ),
439 nodeVec.at( Netgen_tetrahedron[3] ));
442 auto time7 = std::chrono::high_resolution_clock::now();
443 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time7-time6);
444 std::cout << "Time for exec of add_in_mesh: " << elapsed.count() * 1e-9 << std::endl;
446 fs::remove_all(tmp_folder);
452 //=============================================================================
454 *Here we are going to use the NETGEN mesher
456 //=============================================================================
458 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh& aMesh,
459 const TopoDS_Shape& aShape)
461 if(aMesh.IsParallel())
462 return RemoteCompute(aMesh, aShape);
463 auto time0 = std::chrono::high_resolution_clock::now();
465 netgen::multithread.terminate = 0;
466 netgen::multithread.task = "Volume meshing";
467 _progressByTic = -1.;
469 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
471 SMESH_MesherHelper helper(aMesh);
472 _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
473 helper.SetElementsOnShape( true );
475 int Netgen_NbOfNodes = 0;
476 double Netgen_point[3];
477 int Netgen_triangle[3];
479 NETGENPlugin_NetgenLibWrapper ngLib;
480 Ng_Mesh * Netgen_mesh = (Ng_Mesh*)ngLib._ngMesh;
482 // vector of nodes in which node index == netgen ID
483 vector< const SMDS_MeshNode* > nodeVec;
485 const int invalid_ID = -1;
487 SMESH::Controls::Area areaControl;
488 SMESH::Controls::TSequenceOfXYZ nodesCoords;
490 // maps nodes to ng ID
491 typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
492 typedef TNodeToIDMap::value_type TN2ID;
493 TNodeToIDMap nodeToNetgenID;
495 // find internal shapes
496 NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
498 // ---------------------------------
499 // Feed the Netgen with surface mesh
500 // ---------------------------------
502 TopAbs_ShapeEnum mainType = aMesh.GetShapeToMesh().ShapeType();
503 bool checkReverse = ( mainType == TopAbs_COMPOUND || mainType == TopAbs_COMPSOLID );
505 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
506 if ( _viscousLayersHyp )
508 netgen::multithread.percent = 3;
509 proxyMesh = _viscousLayersHyp->Compute( aMesh, aShape );
513 if ( aMesh.NbQuadrangles() > 0 )
515 netgen::multithread.percent = 6;
516 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
517 Adaptor->Compute(aMesh,aShape,proxyMesh.get());
518 proxyMesh.reset( Adaptor );
521 for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
523 const TopoDS_Shape& aShapeFace = exFa.Current();
524 int faceID = meshDS->ShapeToIndex( aShapeFace );
525 bool isInternalFace = internals.isInternalShape( faceID );
527 if ( checkReverse && !isInternalFace &&
528 helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
529 // IsReversedSubMesh() can work wrong on strongly curved faces,
530 // so we use it as less as possible
531 isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
533 const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
534 if ( !aSubMeshDSFace ) continue;
536 SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
537 if ( _quadraticMesh &&
538 dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
540 // add medium nodes of proxy triangles to helper (#16843)
541 while ( iteratorElem->more() )
542 helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
544 iteratorElem = aSubMeshDSFace->GetElements();
546 while ( iteratorElem->more() ) // loop on elements on a geom face
549 const SMDS_MeshElement* elem = iteratorElem->next();
551 return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
552 if ( elem->NbCornerNodes() != 3 )
553 return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
555 // Add nodes of triangles and triangles them-selves to netgen mesh
557 // add three nodes of triangle
558 bool hasDegen = false;
559 for ( int iN = 0; iN < 3; ++iN )
561 const SMDS_MeshNode* node = elem->GetNode( iN );
562 const int shapeID = node->getshapeId();
563 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE &&
564 helper.IsDegenShape( shapeID ))
566 // ignore all nodes on degeneraged edge and use node on its vertex instead
567 TopoDS_Shape vertex = TopoDS_Iterator( meshDS->IndexToShape( shapeID )).Value();
568 node = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), meshDS );
571 int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
572 if ( ngID == invalid_ID )
574 ngID = ++Netgen_NbOfNodes;
575 Netgen_point [ 0 ] = node->X();
576 Netgen_point [ 1 ] = node->Y();
577 Netgen_point [ 2 ] = node->Z();
578 Ng_AddPoint(Netgen_mesh, Netgen_point);
580 Netgen_triangle[ isRev ? 2-iN : iN ] = ngID;
583 if ( hasDegen && (Netgen_triangle[0] == Netgen_triangle[1] ||
584 Netgen_triangle[0] == Netgen_triangle[2] ||
585 Netgen_triangle[2] == Netgen_triangle[1] ))
588 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
590 if ( isInternalFace && !proxyMesh->IsTemporary( elem ))
592 swap( Netgen_triangle[1], Netgen_triangle[2] );
593 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
595 } // loop on elements on a face
596 } // loop on faces of a SOLID or SHELL
598 // insert old nodes into nodeVec
599 nodeVec.resize( nodeToNetgenID.size() + 1, 0 );
600 TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
601 for ( ; n_id != nodeToNetgenID.end(); ++n_id )
602 nodeVec[ n_id->second ] = n_id->first;
603 nodeToNetgenID.clear();
605 if ( internals.hasInternalVertexInSolid() )
607 netgen::OCCGeometry occgeo;
608 NETGENPlugin_Mesher::AddIntVerticesInSolids( occgeo,
609 (netgen::Mesh&) *Netgen_mesh,
615 // -------------------------
616 // Generate the volume mesh
617 // -------------------------
618 auto time1 = std::chrono::high_resolution_clock::now();
619 auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time1-time0);
620 std::cout << "Time for seq:fill_in_ngmesh: " << elapsed.count() * 1e-9 << std::endl;
622 return (ngLib._isComputeOk = compute( aMesh, helper, nodeVec, ngLib ));
627 // void limitVolumeSize( netgen::Mesh* ngMesh,
630 // // get average h of faces
633 // for (int i = 1; i <= ngMesh->GetNSE(); i++)
635 // const netgen::Element2d& face = ngMesh->SurfaceElement(i);
636 // for (int j=1; j <= face.GetNP(); ++j)
638 // const netgen::PointIndex & i1 = face.PNumMod(j);
639 // const netgen::PointIndex & i2 = face.PNumMod(j+1);
642 // const netgen::Point3d & p1 = ngMesh->Point( i1 );
643 // const netgen::Point3d & p2 = ngMesh->Point( i2 );
644 // faceh += netgen::Dist2( p1, p2 );
649 // faceh = Sqrt( faceh / nbh );
652 // if ( faceh < 0.5 * maxh ) compareh = -1;
653 // else if ( faceh > 1.5 * maxh ) compareh = 1;
654 // else compareh = 0;
655 // // cerr << "faceh " << faceh << endl;
656 // // cerr << "init maxh " << maxh << endl;
657 // // cerr << "compareh " << compareh << endl;
659 // if ( compareh > 0 )
663 // // cerr << "maxh " << maxh << endl;
666 // netgen::Point3d pmin, pmax;
667 // ngMesh->GetBox( pmin, pmax, 0 );
668 // const double dx = pmax.X() - pmin.X();
669 // const double dy = pmax.Y() - pmin.Y();
670 // const double dz = pmax.Z() - pmin.Z();
672 // if ( ! & ngMesh->LocalHFunction() )
673 // ngMesh->SetLocalH( pmin, pmax, compareh <= 0 ? 0.1 : 0.5 );
675 // // adjusted by SALOME_TESTS/Grids/smesh/bugs_08/I8
676 // const int nbX = Max( 2, int( dx / maxh * 2 ));
677 // const int nbY = Max( 2, int( dy / maxh * 2 ));
678 // const int nbZ = Max( 2, int( dz / maxh * 2 ));
680 // netgen::Point3d p;
681 // for ( int i = 0; i <= nbX; ++i )
683 // p.X() = pmin.X() + i * dx / nbX;
684 // for ( int j = 0; j <= nbY; ++j )
686 // p.Y() = pmin.Y() + j * dy / nbY;
687 // for ( int k = 0; k <= nbZ; ++k )
689 // p.Z() = pmin.Z() + k * dz / nbZ;
690 // ngMesh->RestrictLocalH( p, maxh );
697 //================================================================================
699 * \brief set parameters and generate the volume mesh
701 //================================================================================
703 bool NETGENPlugin_NETGEN_3D::compute(SMESH_Mesh& aMesh,
704 SMESH_MesherHelper& helper,
705 vector< const SMDS_MeshNode* >& nodeVec,
706 NETGENPlugin_NetgenLibWrapper& ngLib)
708 auto time0 = std::chrono::high_resolution_clock::now();
710 netgen::multithread.terminate = 0;
712 netgen::Mesh* ngMesh = ngLib._ngMesh;
713 Ng_Mesh* Netgen_mesh = ngLib.ngMesh();
714 int Netgen_NbOfNodes = Ng_GetNP( Netgen_mesh );
716 int startWith = netgen::MESHCONST_MESHVOLUME;
717 int endWith = netgen::MESHCONST_OPTVOLUME;
720 NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
721 netgen::OCCGeometry occgeo;
723 if ( _hypParameters )
725 aMesher.SetParameters( _hypParameters );
727 if ( !_hypParameters->GetLocalSizesAndEntries().empty() ||
728 !_hypParameters->GetMeshSizeFile().empty() )
730 if ( ! &ngMesh->LocalHFunction() )
732 netgen::Point3d pmin, pmax;
733 ngMesh->GetBox( pmin, pmax, 0 );
734 ngMesh->SetLocalH( pmin, pmax, _hypParameters->GetGrowthRate() );
736 aMesher.SetLocalSize( occgeo, *ngMesh );
739 ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
740 } catch (netgen::NgException & ex) {
741 return error( COMPERR_BAD_PARMETERS, ex.What() );
744 if ( !_hypParameters->GetOptimize() )
745 endWith = netgen::MESHCONST_MESHVOLUME;
747 else if ( _hypMaxElementVolume )
749 netgen::mparam.maxh = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
750 // limitVolumeSize( ngMesh, mparam.maxh ); // result is unpredictable
752 else if ( aMesh.HasShapeToMesh() )
754 aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
755 netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
759 netgen::Point3d pmin, pmax;
760 ngMesh->GetBox (pmin, pmax);
761 netgen::mparam.maxh = Dist(pmin, pmax)/2;
764 if ( !_hypParameters && aMesh.HasShapeToMesh() )
766 netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
772 auto time0 = std::chrono::high_resolution_clock::now();
774 ngLib.CalcLocalH(ngMesh);
775 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
777 if(netgen::multithread.terminate)
780 error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
782 catch (Standard_Failure& ex)
784 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
785 str << " at " << netgen::multithread.task
786 << ": " << ex.DynamicType()->Name();
787 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
788 str << ": " << ex.GetMessageString();
791 catch (netgen::NgException& exc)
793 SMESH_Comment str("NgException");
794 if ( strlen( netgen::multithread.task ) > 0 )
795 str << " at " << netgen::multithread.task;
796 str << ": " << exc.What();
801 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
802 if ( strlen( netgen::multithread.task ) > 0 )
803 str << " at " << netgen::multithread.task;
806 auto time1 = std::chrono::high_resolution_clock::now();
807 auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time1-time0);
808 std::cout << "Time for seq:compute: " << elapsed.count() * 1e-9 << std::endl;
810 int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
811 int Netgen_NbOfTetra = Ng_GetNE(Netgen_mesh);
813 // -------------------------------------------------------------------
814 // Feed back the SMESHDS with the generated Nodes and Volume Elements
815 // -------------------------------------------------------------------
819 SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
820 if ( ce && ce->HasBadElems() )
824 bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
827 double Netgen_point[3];
828 int Netgen_tetrahedron[4];
830 // create and insert new nodes into nodeVec
831 nodeVec.resize( Netgen_NbOfNodesNew + 1, 0 );
832 int nodeIndex = Netgen_NbOfNodes + 1;
833 for ( ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
835 Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
836 nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0], Netgen_point[1], Netgen_point[2]);
839 // create tetrahedrons
840 for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
842 Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
845 helper.AddVolume (nodeVec.at( Netgen_tetrahedron[0] ),
846 nodeVec.at( Netgen_tetrahedron[1] ),
847 nodeVec.at( Netgen_tetrahedron[2] ),
848 nodeVec.at( Netgen_tetrahedron[3] ));
855 auto time2 = std::chrono::high_resolution_clock::now();
856 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time2-time1);
857 std::cout << "Time for seq:compute: " << elapsed.count() * 1e-9 << std::endl;
863 //================================================================================
865 * \brief Compute tetrahedral mesh from 2D mesh without geometry
867 //================================================================================
869 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh& aMesh,
870 SMESH_MesherHelper* aHelper)
872 const int invalid_ID = -1;
874 netgen::multithread.terminate = 0;
875 _progressByTic = -1.;
877 SMESH_MesherHelper::MType MeshType = aHelper->IsQuadraticMesh();
878 if ( MeshType == SMESH_MesherHelper::COMP )
879 return error( COMPERR_BAD_INPUT_MESH,
880 SMESH_Comment("Mesh with linear and quadratic elements given"));
882 aHelper->SetIsQuadratic( MeshType == SMESH_MesherHelper::QUADRATIC );
884 // ---------------------------------
885 // Feed the Netgen with surface mesh
886 // ---------------------------------
888 int Netgen_NbOfNodes = 0;
889 double Netgen_point[3];
890 int Netgen_triangle[3];
892 NETGENPlugin_NetgenLibWrapper ngLib;
893 Ng_Mesh * Netgen_mesh = ngLib.ngMesh();
895 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
896 if ( aMesh.NbQuadrangles() > 0 )
898 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
899 Adaptor->Compute(aMesh);
900 proxyMesh.reset( Adaptor );
902 if ( aHelper->IsQuadraticMesh() )
904 SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
906 aHelper->AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
910 // maps nodes to ng ID
911 typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
912 typedef TNodeToIDMap::value_type TN2ID;
913 TNodeToIDMap nodeToNetgenID;
915 SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
919 const SMDS_MeshElement* elem = fIt->next();
921 return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
922 if ( elem->NbCornerNodes() != 3 )
923 return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
925 // add three nodes of triangle
926 for ( int iN = 0; iN < 3; ++iN )
928 const SMDS_MeshNode* node = elem->GetNode( iN );
929 int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
930 if ( ngID == invalid_ID )
932 ngID = ++Netgen_NbOfNodes;
933 Netgen_point [ 0 ] = node->X();
934 Netgen_point [ 1 ] = node->Y();
935 Netgen_point [ 2 ] = node->Z();
936 Ng_AddPoint(Netgen_mesh, Netgen_point);
938 Netgen_triangle[ iN ] = ngID;
940 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
942 proxyMesh.reset(); // delete tmp faces
944 // vector of nodes in which node index == netgen ID
945 vector< const SMDS_MeshNode* > nodeVec ( nodeToNetgenID.size() + 1 );
946 // insert old nodes into nodeVec
947 TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
948 for ( ; n_id != nodeToNetgenID.end(); ++n_id )
949 nodeVec.at( n_id->second ) = n_id->first;
950 nodeToNetgenID.clear();
952 // -------------------------
953 // Generate the volume mesh
954 // -------------------------
956 return ( ngLib._isComputeOk = compute( aMesh, *aHelper, nodeVec, ngLib ));
959 void NETGENPlugin_NETGEN_3D::CancelCompute()
961 SMESH_Algo::CancelCompute();
962 netgen::multithread.terminate = 1;
965 //================================================================================
967 * \brief Return Compute progress
969 //================================================================================
971 double NETGENPlugin_NETGEN_3D::GetProgress() const
974 const char* volMeshing = "Volume meshing";
975 const char* dlnMeshing = "Delaunay meshing";
976 const double meshingRatio = 0.15;
977 const_cast<NETGENPlugin_NETGEN_3D*>( this )->_progressTic++;
979 if ( _progressByTic < 0. &&
980 ( strncmp( netgen::multithread.task, dlnMeshing, 3 ) == 0 ||
981 strncmp( netgen::multithread.task, volMeshing, 3 ) == 0 ))
983 res = 0.001 + meshingRatio * netgen::multithread.percent / 100.;
984 //cout << netgen::multithread.task << " " <<_progressTic << "-" << netgen::multithread.percent << endl;
986 else // different otimizations
988 if ( _progressByTic < 0. )
989 ((NETGENPlugin_NETGEN_3D*)this)->_progressByTic = meshingRatio / _progressTic;
990 res = _progressByTic * _progressTic;
991 //cout << netgen::multithread.task << " " << _progressTic << " " << res << endl;
993 return Min ( res, 0.98 );
996 //=============================================================================
1000 //=============================================================================
1002 bool NETGENPlugin_NETGEN_3D::Evaluate(SMESH_Mesh& aMesh,
1003 const TopoDS_Shape& aShape,
1004 MapShapeNbElems& aResMap)
1006 smIdType nbtri = 0, nbqua = 0;
1007 double fullArea = 0.0;
1008 for (TopExp_Explorer expF(aShape, TopAbs_FACE); expF.More(); expF.Next()) {
1009 TopoDS_Face F = TopoDS::Face( expF.Current() );
1010 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
1011 MapShapeNbElemsItr anIt = aResMap.find(sm);
1012 if( anIt==aResMap.end() ) {
1013 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1014 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
1017 std::vector<smIdType> aVec = (*anIt).second;
1018 nbtri += std::max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
1019 nbqua += std::max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1021 BRepGProp::SurfaceProperties(F,G);
1022 double anArea = G.Mass();
1026 // collect info from edges
1027 smIdType nb0d_e = 0, nb1d_e = 0;
1028 bool IsQuadratic = false;
1029 bool IsFirst = true;
1030 TopTools_MapOfShape tmpMap;
1031 for (TopExp_Explorer expF(aShape, TopAbs_EDGE); expF.More(); expF.Next()) {
1032 TopoDS_Edge E = TopoDS::Edge(expF.Current());
1033 if( tmpMap.Contains(E) )
1036 SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(expF.Current());
1037 MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
1038 if( anIt==aResMap.end() ) {
1039 SMESH_ComputeErrorPtr& smError = aSubMesh->GetComputeError();
1040 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
1041 "Submesh can not be evaluated",this));
1044 std::vector<smIdType> aVec = (*anIt).second;
1045 nb0d_e += aVec[SMDSEntity_Node];
1046 nb1d_e += std::max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
1048 IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
1054 double ELen_face = sqrt(2.* ( fullArea/double(nbtri+nbqua*2) ) / sqrt(3.0) );
1055 double ELen_vol = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
1056 double ELen = Min(ELen_vol,ELen_face*2);
1059 BRepGProp::VolumeProperties(aShape,G);
1060 double aVolume = G.Mass();
1061 double tetrVol = 0.1179*ELen*ELen*ELen;
1062 double CoeffQuality = 0.9;
1063 smIdType nbVols = (smIdType)( aVolume/tetrVol/CoeffQuality );
1064 smIdType nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
1065 smIdType nb1d_in = (nbVols*6 - nb1d_e - nb1d_f ) / 5;
1066 std::vector<smIdType> aVec(SMDSEntity_Last);
1067 for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
1069 aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
1070 aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
1071 aVec[SMDSEntity_Quad_Pyramid] = nbqua;
1074 aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
1075 aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
1076 aVec[SMDSEntity_Pyramid] = nbqua;
1078 SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
1079 aResMap.insert(std::make_pair(sm,aVec));