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 // TODO: remove use of netgen_param
36 #include "NETGENPlugin_DriverParam.hxx"
38 #include <SMDS_MeshElement.hxx>
39 #include <SMDS_MeshNode.hxx>
40 #include <SMESHDS_Mesh.hxx>
41 #include <SMESH_Comment.hxx>
42 #include <SMESH_ControlsDef.hxx>
43 #include <SMESH_Gen.hxx>
44 #include <SMESH_Mesh.hxx>
45 #include <SMESH_MeshEditor.hxx>
46 #include <SMESH_MesherHelper.hxx>
47 #include <SMESH_subMesh.hxx>
48 #include <StdMeshers_MaxElementVolume.hxx>
49 #include <StdMeshers_QuadToTriaAdaptor.hxx>
50 #include <StdMeshers_ViscousLayers.hxx>
51 #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>
80 #include <occgeom.hpp>
83 #include <ngexception.hpp>
86 #include <core/exception.hpp>
94 NETGENPLUGIN_DLL_HEADER
95 extern MeshingParameters mparam;
97 NETGENPLUGIN_DLL_HEADER
98 extern volatile multithreadt multithread;
100 using namespace nglib;
103 //=============================================================================
107 //=============================================================================
109 NETGENPlugin_NETGEN_3D::NETGENPlugin_NETGEN_3D(int hypId, SMESH_Gen* gen)
110 : SMESH_3D_Algo(hypId, gen)
113 _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
114 _compatibleHypothesis.push_back("MaxElementVolume");
115 _compatibleHypothesis.push_back("NETGEN_Parameters");
116 _compatibleHypothesis.push_back("ViscousLayers");
118 _maxElementVolume = 0.;
120 _hypMaxElementVolume = NULL;
121 _hypParameters = NULL;
122 _viscousLayersHyp = NULL;
124 _requireShape = false; // can work without shape
127 //=============================================================================
131 //=============================================================================
133 NETGENPlugin_NETGEN_3D::~NETGENPlugin_NETGEN_3D()
137 //=============================================================================
141 //=============================================================================
143 bool NETGENPlugin_NETGEN_3D::CheckHypothesis (SMESH_Mesh& aMesh,
144 const TopoDS_Shape& aShape,
145 Hypothesis_Status& aStatus)
147 _hypMaxElementVolume = NULL;
148 _hypParameters = NULL;
149 _viscousLayersHyp = NULL;
150 _maxElementVolume = DBL_MAX;
152 // for correct work of GetProgress():
153 //netgen::multithread.percent = 0.;
154 //netgen::multithread.task = "Volume meshing";
155 _progressByTic = -1.;
157 list<const SMESHDS_Hypothesis*>::const_iterator itl;
158 //const SMESHDS_Hypothesis* theHyp;
160 const list<const SMESHDS_Hypothesis*>& hyps =
161 GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
162 list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
163 if ( h == hyps.end())
165 aStatus = SMESH_Hypothesis::HYP_OK;
166 return true; // can work with no hypothesis
170 for ( ; h != hyps.end(); ++h )
172 if ( !_hypMaxElementVolume )
173 _hypMaxElementVolume = dynamic_cast< const StdMeshers_MaxElementVolume*> ( *h );
174 if ( !_viscousLayersHyp ) // several _viscousLayersHyp's allowed
175 _viscousLayersHyp = dynamic_cast< const StdMeshers_ViscousLayers*> ( *h );
176 if ( ! _hypParameters )
177 _hypParameters = dynamic_cast< const NETGENPlugin_Hypothesis*> ( *h );
179 if ( *h != _hypMaxElementVolume &&
180 *h != _viscousLayersHyp &&
181 *h != _hypParameters &&
182 !dynamic_cast< const StdMeshers_ViscousLayers*>(*h)) // several VL hyps allowed
183 aStatus = HYP_INCOMPATIBLE;
185 if ( _hypMaxElementVolume && _hypParameters )
186 aStatus = HYP_INCOMPATIBLE;
187 else if ( aStatus == HYP_OK && _viscousLayersHyp )
188 error( _viscousLayersHyp->CheckHypothesis( aMesh, aShape, aStatus ));
190 if ( _hypMaxElementVolume )
191 _maxElementVolume = _hypMaxElementVolume->GetMaxVolume();
193 return aStatus == HYP_OK;
198 //=============================================================================
200 *Here we are going to use the NETGEN mesher
202 //=============================================================================
205 * @brief Get an iterator on the Surface element with their orientation
209 bool NETGENPlugin_NETGEN_3D::getSurfaceElements(
211 const TopoDS_Shape& aShape,
212 SMESH_ProxyMesh::Ptr proxyMesh,
213 NETGENPlugin_Internals &internals,
214 SMESH_MesherHelper &helper,
215 netgen_params &aParams,
216 std::map<const SMDS_MeshElement*, tuple<bool, bool>>& listElements
219 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
220 TopAbs_ShapeEnum mainType = aMesh.GetShapeToMesh().ShapeType();
221 bool checkReverse = ( mainType == TopAbs_COMPOUND || mainType == TopAbs_COMPSOLID );
223 for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
225 const TopoDS_Shape& aShapeFace = exFa.Current();
226 int faceID = meshDS->ShapeToIndex( aShapeFace );
227 bool isInternalFace = internals.isInternalShape( faceID );
229 if ( checkReverse && !isInternalFace &&
230 helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
231 // IsReversedSubMesh() can work wrong on strongly curved faces,
232 // so we use it as less as possible
233 isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
235 const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
236 if ( !aSubMeshDSFace ) continue;
238 SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
239 if ( aParams._quadraticMesh &&
240 dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
242 // add medium nodes of proxy triangles to helper (#16843)
243 while ( iteratorElem->more() )
244 helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
246 iteratorElem = aSubMeshDSFace->GetElements();
248 while(iteratorElem->more()){
249 const SMDS_MeshElement* elem = iteratorElem->next();
252 aParams._error = COMPERR_BAD_INPUT_MESH;
253 aParams._comment = "Null element encounters";
256 if ( elem->NbCornerNodes() != 3 ){
257 aParams._error = COMPERR_BAD_INPUT_MESH;
258 aParams._comment = "Not triangle element encounters";
261 listElements[elem] = tuple(isRev, isInternalFace);
269 bool NETGENPlugin_NETGEN_3D::computeFillNgMesh(
271 const TopoDS_Shape& aShape,
272 vector< const SMDS_MeshNode* > &nodeVec,
273 NETGENPlugin_NetgenLibWrapper &ngLib,
274 SMESH_MesherHelper &helper,
275 netgen_params &aParams,
276 int &Netgen_NbOfNodes)
278 netgen::multithread.terminate = 0;
279 netgen::multithread.task = "Volume meshing";
280 aParams._progressByTic = -1.;
282 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
284 aParams._quadraticMesh = helper.IsQuadraticSubMesh(aShape);
285 helper.SetElementsOnShape( true );
287 Netgen_NbOfNodes = 0;
288 double Netgen_point[3];
289 int Netgen_triangle[3];
291 Ng_Mesh * Netgen_mesh = (Ng_Mesh*)ngLib._ngMesh;
294 const int invalid_ID = -1;
296 SMESH::Controls::Area areaControl;
297 SMESH::Controls::TSequenceOfXYZ nodesCoords;
299 // maps nodes to ng ID
300 typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
301 typedef TNodeToIDMap::value_type TN2ID;
302 TNodeToIDMap nodeToNetgenID;
304 // find internal shapes
305 NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
307 // ---------------------------------
308 // Feed the Netgen with surface mesh
309 // ---------------------------------
311 bool isInternalFace=false;
313 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
314 if ( aParams._viscousLayersHyp )
316 netgen::multithread.percent = 3;
317 proxyMesh = aParams._viscousLayersHyp->Compute( aMesh, aShape );
321 if ( aMesh.NbQuadrangles() > 0 )
323 netgen::multithread.percent = 6;
324 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
325 Adaptor->Compute(aMesh,aShape,proxyMesh.get());
326 proxyMesh.reset( Adaptor );
329 std::map<const SMDS_MeshElement*, tuple<bool, bool>> listElements;
330 bool ret = getSurfaceElements(aMesh, aShape, proxyMesh, internals, helper, aParams, listElements);
334 for ( auto const& [elem, info] : listElements ) // loop on elements on a geom face
336 isRev = get<0>(info);
337 isInternalFace = get<1>(info);
338 // Add nodes of triangles and triangles them-selves to netgen mesh
340 // add three nodes of triangle
341 bool hasDegen = false;
342 for ( int iN = 0; iN < 3; ++iN )
344 const SMDS_MeshNode* node = elem->GetNode( iN );
345 const int shapeID = node->getshapeId();
346 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE &&
347 helper.IsDegenShape( shapeID ))
349 // ignore all nodes on degeneraged edge and use node on its vertex instead
350 TopoDS_Shape vertex = TopoDS_Iterator( meshDS->IndexToShape( shapeID )).Value();
351 node = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), meshDS );
354 int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
355 if ( ngID == invalid_ID )
357 ngID = ++Netgen_NbOfNodes;
358 Netgen_point [ 0 ] = node->X();
359 Netgen_point [ 1 ] = node->Y();
360 Netgen_point [ 2 ] = node->Z();
361 Ng_AddPoint(Netgen_mesh, Netgen_point);
363 Netgen_triangle[ isRev ? 2-iN : iN ] = ngID;
366 if ( hasDegen && (Netgen_triangle[0] == Netgen_triangle[1] ||
367 Netgen_triangle[0] == Netgen_triangle[2] ||
368 Netgen_triangle[2] == Netgen_triangle[1] ))
371 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
373 if ( isInternalFace && !proxyMesh->IsTemporary( elem ))
375 swap( Netgen_triangle[1], Netgen_triangle[2] );
376 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
378 } // loop on elements on a face
380 // insert old nodes into nodeVec
381 nodeVec.resize( nodeToNetgenID.size() + 1, 0 );
382 TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
383 for ( ; n_id != nodeToNetgenID.end(); ++n_id )
384 nodeVec[ n_id->second ] = n_id->first;
385 nodeToNetgenID.clear();
387 if ( internals.hasInternalVertexInSolid() )
389 netgen::OCCGeometry occgeo;
390 NETGENPlugin_Mesher::AddIntVerticesInSolids( occgeo,
391 (netgen::Mesh&) *Netgen_mesh,
396 Netgen_NbOfNodes = Ng_GetNP( Netgen_mesh );
400 bool NETGENPlugin_NETGEN_3D::computePrepareParam(
402 NETGENPlugin_NetgenLibWrapper &ngLib,
403 netgen::OCCGeometry &occgeo,
404 SMESH_MesherHelper &helper,
405 netgen_params &aParams,
409 netgen::multithread.terminate = 0;
411 netgen::Mesh* ngMesh = ngLib._ngMesh;
413 NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
416 if ( aParams._hypParameters )
418 aMesher.SetParameters( aParams._hypParameters );
420 if ( !aParams._hypParameters->GetLocalSizesAndEntries().empty() ||
421 !aParams._hypParameters->GetMeshSizeFile().empty() )
423 if ( ! &ngMesh->LocalHFunction() )
425 netgen::Point3d pmin, pmax;
426 ngMesh->GetBox( pmin, pmax, 0 );
427 ngMesh->SetLocalH( pmin, pmax, aParams._hypParameters->GetGrowthRate() );
429 aMesher.SetLocalSize( occgeo, *ngMesh );
432 ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
433 } catch (netgen::NgException & ex) {
434 aParams._error = COMPERR_BAD_PARMETERS;
435 aParams._comment = ex.What();
439 if ( !aParams._hypParameters->GetOptimize() )
440 endWith = netgen::MESHCONST_MESHVOLUME;
442 else if ( aParams._hypMaxElementVolume )
444 netgen::mparam.maxh = pow( 72, 1/6. ) * pow( aParams.maxElementVolume, 1/3. );
445 // limitVolumeSize( ngMesh, mparam.maxh ); // result is unpredictable
447 else if ( aMesh.HasShapeToMesh() )
449 aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
450 netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
454 netgen::Point3d pmin, pmax;
455 ngMesh->GetBox (pmin, pmax);
456 netgen::mparam.maxh = Dist(pmin, pmax)/2;
459 if ( !aParams._hypParameters && aMesh.HasShapeToMesh() )
461 netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
466 bool NETGENPlugin_NETGEN_3D::computeRunMesher(
467 netgen::OCCGeometry &occgeo,
468 vector< const SMDS_MeshNode* > &nodeVec,
469 netgen::Mesh* ngMesh,
470 NETGENPlugin_NetgenLibWrapper &ngLib,
471 netgen_params &aParams,
472 int &startWith, int &endWith)
480 ngLib.CalcLocalH(ngMesh);
481 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
483 if(netgen::multithread.terminate)
486 aParams._comment = SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
490 catch (Standard_Failure& ex)
492 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
493 str << " at " << netgen::multithread.task
494 << ": " << ex.DynamicType()->Name();
495 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
496 str << ": " << ex.GetMessageString();
497 aParams._comment = str;
500 catch (netgen::NgException& exc)
502 SMESH_Comment str("NgException");
503 if ( strlen( netgen::multithread.task ) > 0 )
504 str << " at " << netgen::multithread.task;
505 str << ": " << exc.What();
506 aParams._comment = str;
511 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
512 if ( strlen( netgen::multithread.task ) > 0 )
513 str << " at " << netgen::multithread.task;
514 aParams._comment = str;
520 SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
521 if ( ce && ce->HasBadElems() ){
522 aParams._error = ce->myName;
523 aParams._comment = ce->myComment;
531 bool NETGENPlugin_NETGEN_3D::computeFillMesh(
532 vector< const SMDS_MeshNode* > &nodeVec,
533 NETGENPlugin_NetgenLibWrapper &ngLib,
534 SMESH_MesherHelper &helper,
535 int &Netgen_NbOfNodes
538 Ng_Mesh* Netgen_mesh = ngLib.ngMesh();
540 int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
541 int Netgen_NbOfTetra = Ng_GetNE(Netgen_mesh);
543 bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
546 double Netgen_point[3];
547 int Netgen_tetrahedron[4];
549 // create and insert new nodes into nodeVec
550 nodeVec.resize( Netgen_NbOfNodesNew + 1, 0 );
551 int nodeIndex = Netgen_NbOfNodes + 1;
552 for ( ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
554 Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
555 nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0], Netgen_point[1], Netgen_point[2]);
558 // create tetrahedrons
559 for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
561 Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
564 helper.AddVolume (nodeVec.at( Netgen_tetrahedron[0] ),
565 nodeVec.at( Netgen_tetrahedron[1] ),
566 nodeVec.at( Netgen_tetrahedron[2] ),
567 nodeVec.at( Netgen_tetrahedron[3] ));
577 bool NETGENPlugin_NETGEN_3D::Compute(
579 const TopoDS_Shape& aShape)
581 // vector of nodes in which node index == netgen ID
582 vector< const SMDS_MeshNode* > nodeVec;
583 NETGENPlugin_NetgenLibWrapper ngLib;
584 SMESH_MesherHelper helper(aMesh);
585 int startWith = netgen::MESHCONST_MESHVOLUME;
586 int endWith = netgen::MESHCONST_OPTVOLUME;
587 int Netgen_NbOfNodes;
589 netgen_params aParams;
591 aParams._hypParameters = const_cast<NETGENPlugin_Hypothesis*>(_hypParameters);
592 aParams._hypMaxElementVolume = const_cast<StdMeshers_MaxElementVolume*>(_hypMaxElementVolume);
593 aParams.maxElementVolume = _maxElementVolume;
594 aParams._progressByTic = _progressByTic;
595 aParams._quadraticMesh = _quadraticMesh;
596 aParams._viscousLayersHyp = const_cast<StdMeshers_ViscousLayers*>(_viscousLayersHyp);
599 ret = computeFillNgMesh(aMesh, aShape, nodeVec, ngLib, helper, aParams, Netgen_NbOfNodes);
601 return error( aParams._error, aParams._comment);
603 netgen::OCCGeometry occgeo;
604 computePrepareParam(aMesh, ngLib, occgeo, helper, aParams, endWith);
605 ret = computeRunMesher(occgeo, nodeVec, ngLib._ngMesh, ngLib, aParams, startWith, endWith);
608 return error(aParams._error, aParams._comment);
610 error(aParams._comment);
613 computeFillMesh(nodeVec, ngLib, helper, Netgen_NbOfNodes);
619 //================================================================================
621 * \brief set parameters and generate the volume mesh
623 //================================================================================
625 bool NETGENPlugin_NETGEN_3D::compute(SMESH_Mesh& aMesh,
626 SMESH_MesherHelper& helper,
627 vector< const SMDS_MeshNode* >& nodeVec,
628 NETGENPlugin_NetgenLibWrapper& ngLib)
630 auto time0 = std::chrono::high_resolution_clock::now();
632 netgen::multithread.terminate = 0;
634 netgen::Mesh* ngMesh = ngLib._ngMesh;
635 Ng_Mesh* Netgen_mesh = ngLib.ngMesh();
636 int Netgen_NbOfNodes = Ng_GetNP( Netgen_mesh );
638 int startWith = netgen::MESHCONST_MESHVOLUME;
639 int endWith = netgen::MESHCONST_OPTVOLUME;
642 NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
643 netgen::OCCGeometry occgeo;
645 if ( _hypParameters )
647 aMesher.SetParameters( _hypParameters );
649 if ( !_hypParameters->GetLocalSizesAndEntries().empty() ||
650 !_hypParameters->GetMeshSizeFile().empty() )
652 if ( ! &ngMesh->LocalHFunction() )
654 netgen::Point3d pmin, pmax;
655 ngMesh->GetBox( pmin, pmax, 0 );
656 ngMesh->SetLocalH( pmin, pmax, _hypParameters->GetGrowthRate() );
658 aMesher.SetLocalSize( occgeo, *ngMesh );
661 ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
662 } catch (netgen::NgException & ex) {
663 return error( COMPERR_BAD_PARMETERS, ex.What() );
666 if ( !_hypParameters->GetOptimize() )
667 endWith = netgen::MESHCONST_MESHVOLUME;
669 else if ( _hypMaxElementVolume )
671 netgen::mparam.maxh = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
672 // limitVolumeSize( ngMesh, mparam.maxh ); // result is unpredictable
674 else if ( aMesh.HasShapeToMesh() )
676 aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
677 netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
681 netgen::Point3d pmin, pmax;
682 ngMesh->GetBox (pmin, pmax);
683 netgen::mparam.maxh = Dist(pmin, pmax)/2;
686 if ( !_hypParameters && aMesh.HasShapeToMesh() )
688 netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
694 auto time0 = std::chrono::high_resolution_clock::now();
696 ngLib.CalcLocalH(ngMesh);
697 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
699 if(netgen::multithread.terminate)
702 error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
704 catch (Standard_Failure& ex)
706 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
707 str << " at " << netgen::multithread.task
708 << ": " << ex.DynamicType()->Name();
709 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
710 str << ": " << ex.GetMessageString();
713 catch (netgen::NgException& exc)
715 SMESH_Comment str("NgException");
716 if ( strlen( netgen::multithread.task ) > 0 )
717 str << " at " << netgen::multithread.task;
718 str << ": " << exc.What();
723 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
724 if ( strlen( netgen::multithread.task ) > 0 )
725 str << " at " << netgen::multithread.task;
728 auto time1 = std::chrono::high_resolution_clock::now();
729 auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time1-time0);
730 std::cout << "Time for seq:compute: " << elapsed.count() * 1e-9 << std::endl;
732 int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
733 int Netgen_NbOfTetra = Ng_GetNE(Netgen_mesh);
735 // -------------------------------------------------------------------
736 // Feed back the SMESHDS with the generated Nodes and Volume Elements
737 // -------------------------------------------------------------------
741 SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
742 if ( ce && ce->HasBadElems() )
746 bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
749 double Netgen_point[3];
750 int Netgen_tetrahedron[4];
752 // create and insert new nodes into nodeVec
753 nodeVec.resize( Netgen_NbOfNodesNew + 1, 0 );
754 int nodeIndex = Netgen_NbOfNodes + 1;
755 for ( ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
757 Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
758 nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0], Netgen_point[1], Netgen_point[2]);
761 // create tetrahedrons
762 for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
764 Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
767 helper.AddVolume (nodeVec.at( Netgen_tetrahedron[0] ),
768 nodeVec.at( Netgen_tetrahedron[1] ),
769 nodeVec.at( Netgen_tetrahedron[2] ),
770 nodeVec.at( Netgen_tetrahedron[3] ));
777 auto time2 = std::chrono::high_resolution_clock::now();
778 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time2-time1);
779 std::cout << "Time for seq:compute: " << elapsed.count() * 1e-9 << std::endl;
785 //================================================================================
787 * \brief Compute tetrahedral mesh from 2D mesh without geometry
789 //================================================================================
791 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh& aMesh,
792 SMESH_MesherHelper* aHelper)
794 const int invalid_ID = -1;
796 netgen::multithread.terminate = 0;
797 _progressByTic = -1.;
799 SMESH_MesherHelper::MType MeshType = aHelper->IsQuadraticMesh();
800 if ( MeshType == SMESH_MesherHelper::COMP )
801 return error( COMPERR_BAD_INPUT_MESH,
802 SMESH_Comment("Mesh with linear and quadratic elements given"));
804 aHelper->SetIsQuadratic( MeshType == SMESH_MesherHelper::QUADRATIC );
806 // ---------------------------------
807 // Feed the Netgen with surface mesh
808 // ---------------------------------
810 int Netgen_NbOfNodes = 0;
811 double Netgen_point[3];
812 int Netgen_triangle[3];
814 NETGENPlugin_NetgenLibWrapper ngLib;
815 Ng_Mesh * Netgen_mesh = ngLib.ngMesh();
817 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
818 if ( aMesh.NbQuadrangles() > 0 )
820 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
821 Adaptor->Compute(aMesh);
822 proxyMesh.reset( Adaptor );
824 if ( aHelper->IsQuadraticMesh() )
826 SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
828 aHelper->AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
832 // maps nodes to ng ID
833 typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
834 typedef TNodeToIDMap::value_type TN2ID;
835 TNodeToIDMap nodeToNetgenID;
837 SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
841 const SMDS_MeshElement* elem = fIt->next();
843 return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
844 if ( elem->NbCornerNodes() != 3 )
845 return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
847 // add three nodes of triangle
848 for ( int iN = 0; iN < 3; ++iN )
850 const SMDS_MeshNode* node = elem->GetNode( iN );
851 int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
852 if ( ngID == invalid_ID )
854 ngID = ++Netgen_NbOfNodes;
855 Netgen_point [ 0 ] = node->X();
856 Netgen_point [ 1 ] = node->Y();
857 Netgen_point [ 2 ] = node->Z();
858 Ng_AddPoint(Netgen_mesh, Netgen_point);
860 Netgen_triangle[ iN ] = ngID;
862 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
864 proxyMesh.reset(); // delete tmp faces
866 // vector of nodes in which node index == netgen ID
867 vector< const SMDS_MeshNode* > nodeVec ( nodeToNetgenID.size() + 1 );
868 // insert old nodes into nodeVec
869 TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
870 for ( ; n_id != nodeToNetgenID.end(); ++n_id )
871 nodeVec.at( n_id->second ) = n_id->first;
872 nodeToNetgenID.clear();
874 // -------------------------
875 // Generate the volume mesh
876 // -------------------------
878 return ( ngLib._isComputeOk = compute( aMesh, *aHelper, nodeVec, ngLib ));
881 void NETGENPlugin_NETGEN_3D::CancelCompute()
883 SMESH_Algo::CancelCompute();
884 netgen::multithread.terminate = 1;
887 //================================================================================
889 * \brief Return Compute progress
891 //================================================================================
893 double NETGENPlugin_NETGEN_3D::GetProgress() const
896 const char* volMeshing = "Volume meshing";
897 const char* dlnMeshing = "Delaunay meshing";
898 const double meshingRatio = 0.15;
899 const_cast<NETGENPlugin_NETGEN_3D*>( this )->_progressTic++;
901 if ( _progressByTic < 0. &&
902 ( strncmp( netgen::multithread.task, dlnMeshing, 3 ) == 0 ||
903 strncmp( netgen::multithread.task, volMeshing, 3 ) == 0 ))
905 res = 0.001 + meshingRatio * netgen::multithread.percent / 100.;
906 //cout << netgen::multithread.task << " " <<_progressTic << "-" << netgen::multithread.percent << endl;
908 else // different otimizations
910 if ( _progressByTic < 0. )
911 ((NETGENPlugin_NETGEN_3D*)this)->_progressByTic = meshingRatio / _progressTic;
912 res = _progressByTic * _progressTic;
913 //cout << netgen::multithread.task << " " << _progressTic << " " << res << endl;
915 return Min ( res, 0.98 );
918 //=============================================================================
922 //=============================================================================
924 bool NETGENPlugin_NETGEN_3D::Evaluate(SMESH_Mesh& aMesh,
925 const TopoDS_Shape& aShape,
926 MapShapeNbElems& aResMap)
928 smIdType nbtri = 0, nbqua = 0;
929 double fullArea = 0.0;
930 for (TopExp_Explorer expF(aShape, TopAbs_FACE); expF.More(); expF.Next()) {
931 TopoDS_Face F = TopoDS::Face( expF.Current() );
932 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
933 MapShapeNbElemsItr anIt = aResMap.find(sm);
934 if( anIt==aResMap.end() ) {
935 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
936 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
939 std::vector<smIdType> aVec = (*anIt).second;
940 nbtri += std::max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
941 nbqua += std::max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
943 BRepGProp::SurfaceProperties(F,G);
944 double anArea = G.Mass();
948 // collect info from edges
949 smIdType nb0d_e = 0, nb1d_e = 0;
950 bool IsQuadratic = false;
952 TopTools_MapOfShape tmpMap;
953 for (TopExp_Explorer expF(aShape, TopAbs_EDGE); expF.More(); expF.Next()) {
954 TopoDS_Edge E = TopoDS::Edge(expF.Current());
955 if( tmpMap.Contains(E) )
958 SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(expF.Current());
959 MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
960 if( anIt==aResMap.end() ) {
961 SMESH_ComputeErrorPtr& smError = aSubMesh->GetComputeError();
962 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
963 "Submesh can not be evaluated",this));
966 std::vector<smIdType> aVec = (*anIt).second;
967 nb0d_e += aVec[SMDSEntity_Node];
968 nb1d_e += std::max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
970 IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
976 double ELen_face = sqrt(2.* ( fullArea/double(nbtri+nbqua*2) ) / sqrt(3.0) );
977 double ELen_vol = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
978 double ELen = Min(ELen_vol,ELen_face*2);
981 BRepGProp::VolumeProperties(aShape,G);
982 double aVolume = G.Mass();
983 double tetrVol = 0.1179*ELen*ELen*ELen;
984 double CoeffQuality = 0.9;
985 smIdType nbVols = (smIdType)( aVolume/tetrVol/CoeffQuality );
986 smIdType nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
987 smIdType nb1d_in = (nbVols*6 - nb1d_e - nb1d_f ) / 5;
988 std::vector<smIdType> aVec(SMDSEntity_Last);
989 for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
991 aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
992 aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
993 aVec[SMDSEntity_Quad_Pyramid] = nbqua;
996 aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
997 aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
998 aVec[SMDSEntity_Pyramid] = nbqua;
1000 SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
1001 aResMap.insert(std::make_pair(sm,aVec));