1 // Copyright (C) 2007-2021 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 // File : NETGENPlugin_Runner.cxx
24 // Author : Yoann AUDOUIN, EDF
28 #include "NETGENPlugin_Runner.hxx"
31 #include "NETGENPlugin_DriverParam.hxx"
35 #include <boost/filesystem.hpp>
36 namespace fs = boost::filesystem;
40 #include <SMESH_Mesh.hxx>
41 #include <SMESH_subMesh.hxx>
42 #include <SMESH_Gen.hxx>
43 #include <SMESH_Algo.hxx>
44 #include <SMESHDS_Mesh.hxx>
45 #include <SMESH_ControlsDef.hxx>
46 #include <SMESH_Comment.hxx>
47 #include <SMESH_ComputeError.hxx>
48 #include <SMESH_MesherHelper.hxx>
49 #include <StdMeshers_MaxElementVolume.hxx>
50 #include <StdMeshers_QuadToTriaAdaptor.hxx>
51 #include <StdMeshers_ViscousLayers.hxx>
52 #include <StdMeshers_ViscousLayers2D.hxx>
53 #include <SMESH_DriverShape.hxx>
54 #include <SMESH_DriverMesh.hxx>
58 // #include <NETGENPlugin_Mesher.hxx>
59 // #include <NETGENPlugin_Hypothesis.hxx>
60 #include "NETGENPlugin_Mesher.hxx"
61 #include "NETGENPlugin_Hypothesis.hxx"
66 #include <BRepClass3d_SolidClassifier.hxx>
67 #include <GProp_GProps.hxx>
68 #include <BRepGProp.hxx>
70 #include <Standard_Failure.hxx>
71 #include <Standard_ErrorHandler.hxx>
79 #include <occgeom.hpp>
80 #include <meshing.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 NETGENPLUGIN_DLL_HEADER
101 extern bool merge_solids;
104 extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
107 using namespace nglib;
109 int error(int error_type, std::string msg)
111 std::cerr << msg << std::endl;
115 int error(const SMESH_Comment& comment)
117 return error(1, "SMESH_Comment error: "+comment);
121 * @brief Set the netgen parameters
123 * @param aParams Internal structure of parameters
124 * @param mparams Netgen strcuture of parameters
126 void set_netgen_parameters(netgen_params& aParams)
129 // Default parameters
132 //netgen::mparam.nthreads = std::thread::hardware_concurrency();
133 netgen::mparam.nthreads = aParams.nbThreads;
134 netgen::mparam.parallel_meshing = aParams.nbThreads > 1;
137 if ( getenv( "SALOME_NETGEN_DISABLE_MULTITHREADING" ))
139 netgen::mparam.nthreads = 1;
140 netgen::mparam.parallel_meshing = false;
145 // Initialize global NETGEN parameters:
146 netgen::mparam.maxh = aParams.maxh;
147 netgen::mparam.minh = aParams.minh;
148 netgen::mparam.segmentsperedge = aParams.segmentsperedge;
149 netgen::mparam.grading = aParams.grading;
150 netgen::mparam.curvaturesafety = aParams.curvaturesafety;
151 netgen::mparam.secondorder = aParams.secondorder;
152 netgen::mparam.quad = aParams.quad;
153 netgen::mparam.uselocalh = aParams.uselocalh;
154 netgen::merge_solids = aParams.merge_solids;
155 netgen::mparam.optsteps2d = aParams.optsteps2d;
156 netgen::mparam.optsteps3d = aParams.optsteps3d;
157 netgen::mparam.elsizeweight = aParams.elsizeweight;
158 netgen::mparam.opterrpow = aParams.opterrpow;
159 netgen::mparam.delaunay = aParams.delaunay;
160 netgen::mparam.checkoverlap = aParams.checkoverlap;
161 netgen::mparam.checkchartboundary = aParams.checkchartboundary;
164 netgen::mparam.meshsizefilename = aParams.meshsizefilename;
165 netgen::mparam.closeedgefac = aParams.closeedgefac;
169 netgen::mparam.meshsizefilename= aParams.meshsizefilename.empty() ? 0 : aParams.meshsizefilename.c_str();
174 * @brief compute mesh with netgen3d
176 * @param input_mesh_file Input Mesh file
177 * @param shape_file Shape file
178 * @param hypo_file Parameter file
179 * @param new_element_file Binary file containing new nodes and new element info
180 * @param output_mesh If true will export mesh into output_mesh_file
181 * @param output_mesh_file Output Mesh file
185 int netgen3d(const std::string input_mesh_file,
186 const std::string shape_file,
187 const std::string hypo_file,
188 const std::string element_orientation_file,
189 const std::string new_element_file,
190 const std::string output_mesh_file,
193 auto time0 = std::chrono::high_resolution_clock::now();
197 std::unique_ptr<SMESH_Mesh> myMesh(gen.CreateMesh(false));
199 std::string mesh_name = "Maillage_1";
201 importMesh(input_mesh_file, *myMesh, mesh_name);
202 auto time1 = std::chrono::high_resolution_clock::now();
203 auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time1-time0);
204 std::cout << "Time for importMesh: " << elapsed.count() * 1e-9 << std::endl;
207 TopoDS_Shape myShape;
208 importShape(shape_file, myShape);
209 auto time2 = std::chrono::high_resolution_clock::now();
210 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time2-time1);
211 std::cout << "Time for importShape: " << elapsed.count() * 1e-9 << std::endl;
213 // Importing hypothesis
214 netgen_params myParams;
216 importNetgenParams(hypo_file, myParams, &gen);
217 auto time3 = std::chrono::high_resolution_clock::now();
218 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time3-time2);
219 std::cout << "Time for import_netgen_param: " << elapsed.count() * 1e-9 << std::endl;
220 // Setting number of threads for netgen
221 myParams.nbThreads = nbThreads;
223 std::cout << "Meshing with netgen3d" << std::endl;
224 int ret = netgen3dInternal(myShape, *myMesh, myParams,
225 new_element_file, element_orientation_file,
226 !output_mesh_file.empty());
230 std::cout << "Meshing failed" << std::endl;
234 if(!output_mesh_file.empty()){
235 auto time4 = std::chrono::high_resolution_clock::now();
236 exportMesh(output_mesh_file, *myMesh, mesh_name);
237 auto time5 = std::chrono::high_resolution_clock::now();
238 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time5-time4);
239 std::cout << "Time for exportMesh: " << elapsed.count() * 1e-9 << std::endl;
246 * @brief Compute aShape within aMesh using netgen3d
248 * @param aShape the shape
249 * @param aMesh the mesh
250 * @param aParams the netgen parameters
251 * @param new_element_file file containing data on the new point/tetra added by netgen
252 * @param element_orientation_file file containing data on the orientation of each element to add to netgen
253 * @param output_mesh if true add element created by netgen into aMesh
257 int netgen3dInternal(TopoDS_Shape &aShape, SMESH_Mesh& aMesh, netgen_params& aParams,
258 std::string new_element_file, std::string element_orientation_file,
262 auto time0 = std::chrono::high_resolution_clock::now();
264 netgen::multithread.terminate = 0;
265 netgen::multithread.task = "Volume meshing";
267 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
269 SMESH_MesherHelper helper(aMesh);
270 aParams._quadraticMesh = helper.IsQuadraticSubMesh(aShape);
271 helper.SetElementsOnShape( true );
273 int Netgen_NbOfNodes = 0;
274 double Netgen_point[3];
275 int Netgen_triangle[3];
277 NETGENPlugin_NetgenLibWrapper ngLib;
278 Ng_Mesh * Netgen_mesh = (Ng_Mesh*)ngLib._ngMesh;
280 // vector of nodes in which node index == netgen ID
281 vector< const SMDS_MeshNode* > nodeVec;
283 const int invalid_ID = -1;
285 SMESH::Controls::Area areaControl;
286 SMESH::Controls::TSequenceOfXYZ nodesCoords;
288 // maps nodes to ng ID
289 typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
290 typedef TNodeToIDMap::value_type TN2ID;
291 TNodeToIDMap nodeToNetgenID;
293 // find internal shapes
294 NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
296 // ---------------------------------
297 // Feed the Netgen with surface mesh
298 // ---------------------------------
300 TopAbs_ShapeEnum mainType = aMesh.GetShapeToMesh().ShapeType();
301 bool checkReverse = ( mainType == TopAbs_COMPOUND || mainType == TopAbs_COMPSOLID );
303 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
304 if ( aParams._viscousLayersHyp )
306 netgen::multithread.percent = 3;
307 proxyMesh = aParams._viscousLayersHyp->Compute( aMesh, aShape );
311 if ( aMesh.NbQuadrangles() > 0 )
313 netgen::multithread.percent = 6;
314 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
315 Adaptor->Compute(aMesh,aShape,proxyMesh.get());
316 proxyMesh.reset( Adaptor );
319 // Get list of elements + their orientation from element_orientation file
320 std::map<vtkIdType, bool> elemOrientation;
322 // Setting all element orientation to false if there no element orientation file
323 if(element_orientation_file.empty()){
324 SMDS_ElemIteratorPtr iteratorElem = meshDS->elementsIterator(SMDSAbs_Face);
325 while ( iteratorElem->more() ) // loop on elements on a geom face
328 const SMDS_MeshElement* elem = iteratorElem->next();
329 elemOrientation[elem->GetID()] = false;
332 std::ifstream df(element_orientation_file, ios::binary|ios::in);
336 // Warning of the use of vtkIdType (I had issue when run_mesher was compiled with internal vtk) and salome not
337 // Sizeof was the same but how he othered the type was different
338 // Maybe using another type (uint64_t) instead would be better
340 df.read((char*)&nbElement, sizeof(int));
342 for(int ielem=0;ielem<nbElement;++ielem){
343 df.read((char*) &id, sizeof(vtkIdType));
344 df.read((char*) &orient, sizeof(bool));
345 elemOrientation[id] = orient;
350 // Adding elements from Mesh
351 SMDS_ElemIteratorPtr iteratorElem = meshDS->elementsIterator(SMDSAbs_Face);
353 bool isInternalFace = false;
357 while ( iteratorElem->more() ) // loop on elements on a geom face
360 const SMDS_MeshElement* elem = iteratorElem->next();
362 return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
363 if ( elem->NbCornerNodes() != 3 )
364 return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
366 // Keeping only element that are in the element orientation file
367 isIn = elemOrientation.count(elem->GetID())==1;
373 // Netgen requires that all the triangle point outside
374 isRev = elemOrientation[elem->GetID()];
376 // Add nodes of triangles and triangles them-selves to netgen mesh
378 // add three nodes of triangle
379 bool hasDegen = false;
380 for ( int iN = 0; iN < 3; ++iN )
382 const SMDS_MeshNode* node = elem->GetNode( iN );
383 const int shapeID = node->getshapeId();
384 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE &&
385 helper.IsDegenShape( shapeID ))
387 // ignore all nodes on degeneraged edge and use node on its vertex instead
388 TopoDS_Shape vertex = TopoDS_Iterator( meshDS->IndexToShape( shapeID )).Value();
389 node = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), meshDS );
392 int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
393 if ( ngID == invalid_ID )
395 ngID = ++Netgen_NbOfNodes;
396 Netgen_point [ 0 ] = node->X();
397 Netgen_point [ 1 ] = node->Y();
398 Netgen_point [ 2 ] = node->Z();
399 Ng_AddPoint(Netgen_mesh, Netgen_point);
402 Netgen_triangle[ isRev ? 2-iN : iN ] = ngID;
405 if ( hasDegen && (Netgen_triangle[0] == Netgen_triangle[1] ||
406 Netgen_triangle[0] == Netgen_triangle[2] ||
407 Netgen_triangle[2] == Netgen_triangle[1] ))
410 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
412 // TODO: Handle that case (quadrangle 2D) (isInternal is set to false)
413 if ( isInternalFace && !proxyMesh->IsTemporary( elem ))
415 swap( Netgen_triangle[1], Netgen_triangle[2] );
416 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
420 // insert old nodes into nodeVec
421 nodeVec.resize( nodeToNetgenID.size() + 1, 0 );
422 TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
423 for ( ; n_id != nodeToNetgenID.end(); ++n_id )
424 nodeVec[ n_id->second ] = n_id->first;
425 nodeToNetgenID.clear();
427 // TODO: Handle internal vertex
428 //if ( internals.hasInternalVertexInSolid() )
430 // netgen::OCCGeometry occgeo;
431 // NETGENPlugin_Mesher::AddIntVerticesInSolids( occgeo,
432 // (netgen::Mesh&) *Netgen_mesh,
437 auto time1 = std::chrono::high_resolution_clock::now();
438 auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time1-time0);
439 std::cout << "Time for fill_in_ngmesh: " << elapsed.count() * 1e-9 << std::endl;
441 // -------------------------
442 // Generate the volume mesh
443 // -------------------------
444 netgen::multithread.terminate = 0;
446 netgen::Mesh* ngMesh = ngLib._ngMesh;
447 Netgen_mesh = ngLib.ngMesh();
448 Netgen_NbOfNodes = Ng_GetNP( Netgen_mesh );
451 int startWith = netgen::MESHCONST_MESHVOLUME;
452 int endWith = netgen::MESHCONST_OPTVOLUME;
455 NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
456 netgen::OCCGeometry occgeo;
457 set_netgen_parameters(aParams);
459 if ( aParams.has_netgen_param )
461 if ( aParams.has_local_size)
463 if ( ! &ngMesh->LocalHFunction() )
465 netgen::Point3d pmin, pmax;
466 ngMesh->GetBox( pmin, pmax, 0 );
467 ngMesh->SetLocalH( pmin, pmax, aParams.grading );
469 aMesher.SetLocalSize( occgeo, *ngMesh );
472 ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
473 } catch (netgen::NgException & ex) {
474 return error( COMPERR_BAD_PARMETERS, ex.What() );
477 if ( !aParams.optimize )
478 endWith = netgen::MESHCONST_MESHVOLUME;
480 else if ( aParams.has_maxelementvolume_hyp )
482 netgen::mparam.maxh = pow( 72, 1/6. ) * pow( aParams.maxElementVolume, 1/3. );
483 // limitVolumeSize( ngMesh, netgen::mparam.maxh ); // result is unpredictable
485 else if ( aMesh.HasShapeToMesh() )
487 aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
488 netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
492 netgen::Point3d pmin, pmax;
493 ngMesh->GetBox (pmin, pmax);
494 netgen::mparam.maxh = Dist(pmin, pmax)/2;
497 if ( !aParams.has_netgen_param && aMesh.HasShapeToMesh() )
499 netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
506 ngLib.CalcLocalH(ngMesh);
507 err = ngLib.GenerateMesh(occgeo, startWith, endWith, ngMesh);
509 if(netgen::multithread.terminate)
512 return error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
514 catch (Standard_Failure& ex)
516 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
517 str << " at " << netgen::multithread.task
518 << ": " << ex.DynamicType()->Name();
519 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
520 str << ": " << ex.GetMessageString();
523 catch (netgen::NgException& exc)
525 SMESH_Comment str("NgException");
526 if ( strlen( netgen::multithread.task ) > 0 )
527 str << " at " << netgen::multithread.task;
528 str << ": " << exc.What();
533 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
534 if ( strlen( netgen::multithread.task ) > 0 )
535 str << " at " << netgen::multithread.task;
539 int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
540 int Netgen_NbOfTetra = Ng_GetNE(Netgen_mesh);
542 // -------------------------------------------------------------------
543 // Feed back the SMESHDS with the generated Nodes and Volume Elements
544 // -------------------------------------------------------------------
548 SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
549 if ( ce && ce->HasBadElems() )
552 auto time2 = std::chrono::high_resolution_clock::now();
553 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time2-time1);
554 std::cout << "Time for netgen_compute: " << elapsed.count() * 1e-9 << std::endl;
556 bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
557 if ( isOK && !new_element_file.empty() )
559 std::ofstream df(new_element_file, ios::out|ios::binary);
561 double Netgen_point[3];
562 int Netgen_tetrahedron[4];
564 // Writing nodevec (correspondence netgen numbering mesh numbering)
566 df.write((char*) &Netgen_NbOfNodes, sizeof(int));
567 df.write((char*) &Netgen_NbOfNodesNew, sizeof(int));
568 for (int nodeIndex = 1 ; nodeIndex <= Netgen_NbOfNodes; ++nodeIndex )
571 int id = nodeVec.at(nodeIndex)->GetID();
572 df.write((char*) &id, sizeof(int));
575 // Writing info on new points
576 for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
578 Ng_GetPoint(Netgen_mesh, nodeIndex, Netgen_point );
579 // Coordinates of the point
580 df.write((char *) &Netgen_point, sizeof(double)*3);
583 // create tetrahedrons
584 df.write((char*) &Netgen_NbOfTetra, sizeof(int));
585 for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
587 Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
588 df.write((char*) &Netgen_tetrahedron, sizeof(int)*4);
591 auto time3 = std::chrono::high_resolution_clock::now();
592 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time3-time2);
593 std::cout << "Time for write_new_elem: " << elapsed.count() * 1e-9 << std::endl;
596 // Adding new elements in aMesh as well
599 double Netgen_point[3];
600 int Netgen_tetrahedron[4];
602 // create and insert new nodes into nodeVec
603 nodeVec.resize( Netgen_NbOfNodesNew + 1, 0 );
604 int nodeIndex = Netgen_NbOfNodes + 1;
605 for ( ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
607 Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
608 nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
613 // create tetrahedrons
614 for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
616 Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
619 helper.AddVolume (nodeVec.at( Netgen_tetrahedron[0] ),
620 nodeVec.at( Netgen_tetrahedron[1] ),
621 nodeVec.at( Netgen_tetrahedron[2] ),
622 nodeVec.at( Netgen_tetrahedron[3] ));
628 auto time4 = std::chrono::high_resolution_clock::now();
629 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time4-time3);
630 std::cout << "Time for add_element_to_smesh: " << elapsed.count() * 1e-9 << std::endl;
638 * @brief compute mesh with netgen2d
640 * @param input_mesh_file Input Mesh file
641 * @param shape_file Shape file
642 * @param hypo_file Parameter file
643 * @param new_element_file Binary file containing new nodes and new element info
644 * @param output_mesh If true will export mesh into output_mesh_file
645 * @param output_mesh_file Output Mesh file
649 int netgen2d(const std::string input_mesh_file,
650 const std::string shape_file,
651 const std::string hypo_file,
652 const std::string element_orientation_file,
653 const std::string new_element_file,
654 const std::string output_mesh_file)
660 std::unique_ptr<SMESH_Mesh> myMesh(gen.CreateMesh(false));
663 std::string mesh_name = "Maillage_1";
665 importMesh(input_mesh_file, *myMesh, mesh_name);
668 TopoDS_Shape myShape;
669 importShape(shape_file, myShape);
671 // Importing hypothesis
672 netgen_params myParams;
674 importNetgenParams(hypo_file, myParams, &gen);
676 std::cout << "Meshing with netgen3d" << std::endl;
677 int ret = netgen2dInternal(myShape, *myMesh, myParams,
678 new_element_file, element_orientation_file,
679 !output_mesh_file.empty());
682 std::cout << "Meshing failed" << std::endl;
686 if(!output_mesh_file.empty())
687 exportMesh(output_mesh_file, *myMesh, mesh_name);
693 // TODO: Not working properly
695 * @brief Compute aShape within aMesh using netgen2d
697 * @param aShape the shape
698 * @param aMesh the mesh
699 * @param aParams the netgen parameters
700 * @param new_element_file file containing data on the new point/tetra added by netgen
704 int netgen2dInternal(TopoDS_Shape &aShape, SMESH_Mesh& aMesh, netgen_params& aParams,
705 std::string new_element_file, std::string element_orientation_file,
708 netgen::multithread.terminate = 0;
709 netgen::multithread.task = "Surface meshing";
711 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
712 SMESH_MesherHelper helper(aMesh);
713 helper.SetElementsOnShape( true );
715 NETGENPlugin_NetgenLibWrapper ngLib;
716 ngLib._isComputeOk = false;
718 netgen::Mesh ngMeshNoLocSize;
719 netgen::Mesh * ngMeshes[2] = { (netgen::Mesh*) ngLib._ngMesh, & ngMeshNoLocSize };
720 netgen::OCCGeometry occgeoComm;
722 std::map<vtkIdType, bool> elemOrientation;
724 typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
725 typedef TNodeToIDMap::value_type TN2ID;
726 const int invalid_ID = -1;
727 int Netgen_NbOfNodes=0;
728 double Netgen_point[3];
729 int Netgen_segment[2];
730 int Netgen_triangle[3];
732 // min / max sizes are set as follows:
733 // if ( _hypParameters )
734 // min and max are defined by the user
735 // else if ( aParams.has_LengthFromEdges_hyp )
736 // min = aMesher.GetDefaultMinSize()
737 // max = average segment len of a FACE
738 // else if ( _hypMaxElementArea )
739 // min = aMesher.GetDefaultMinSize()
740 // max = f( _hypMaxElementArea )
742 // min = aMesher.GetDefaultMinSize()
743 // max = max segment len of a FACE
744 NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
745 set_netgen_parameters( aParams );
746 const bool toOptimize = aParams.optimize;
747 if ( aParams.has_maxelementvolume_hyp )
749 netgen::mparam.maxh = sqrt( 2. * aParams.maxElementVolume / sqrt(3.0) );
751 netgen::mparam.quad = aParams.quad;
753 // local size is common for all FACEs in aShape?
754 const bool isCommonLocalSize = ( !aParams.has_LengthFromEdges_hyp && !aParams.has_maxelementvolume_hyp && netgen::mparam.uselocalh );
755 const bool isDefaultHyp = ( !aParams.has_LengthFromEdges_hyp && !aParams.has_maxelementvolume_hyp && !aParams.has_netgen_param );
758 if ( isCommonLocalSize ) // compute common local size in ngMeshes[0]
760 //list< SMESH_subMesh* > meshedSM[4]; --> all sub-shapes are added to occgeoComm
761 aMesher.PrepareOCCgeometry( occgeoComm, aShape, aMesh );//, meshedSM );
763 // local size set at MESHCONST_ANALYSE step depends on
764 // minh, face_maxh, grading and curvaturesafety; find minh if not set by the user
765 if ( !aParams.has_netgen_param || netgen::mparam.minh < DBL_MIN )
767 if ( !aParams.has_netgen_param )
768 netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam() / 3.;
769 netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
771 // set local size depending on curvature and NOT closeness of EDGEs
773 const double factor = 2; //netgen::occparam.resthcloseedgefac;
775 const double factor = netgen::occparam.resthcloseedgefac;
776 netgen::occparam.resthcloseedgeenable = false;
777 netgen::occparam.resthcloseedgefac = 1.0 + netgen::mparam.grading;
779 occgeoComm.face_maxh = netgen::mparam.maxh;
781 netgen::OCCParameters occparam;
782 netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0], netgen::mparam, occparam );
784 netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0] );
786 occgeoComm.emap.Clear();
787 occgeoComm.vmap.Clear();
789 // Reading list of element to integrate into netgen mesh
791 std::ifstream df(element_orientation_file, ios::in|ios::binary);
795 df.read((char*)&nbElement, sizeof(int));
797 for(int ielem=0;ielem<nbElement;++ielem){
798 df.read((char*) &id, sizeof(vtkIdType));
799 df.read((char*) &orient, sizeof(bool));
800 elemOrientation[id] = orient;
805 // set local size according to size of existing segments
806 SMDS_ElemIteratorPtr iteratorElem = meshDS->elementsIterator(SMDSAbs_Edge);
807 while ( iteratorElem->more() ) // loop on elements on a geom face
809 const SMDS_MeshElement* seg = iteratorElem->next();
810 // Keeping only element that are in the element orientation file
811 isIn = elemOrientation.count(seg->GetID())==1;
816 SMESH_TNodeXYZ n1 = seg->GetNode(0);
817 SMESH_TNodeXYZ n2 = seg->GetNode(1);
818 gp_XYZ p = 0.5 * ( n1 + n2 );
819 netgen::Point3d pi(p.X(), p.Y(), p.Z());
820 ngMeshes[0]->RestrictLocalH( pi, factor * ( n1 - n2 ).Modulus() );
823 // set local size defined on shapes
824 aMesher.SetLocalSize( occgeoComm, *ngMeshes[0] );
825 aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMeshes[0] );
827 ngMeshes[0]->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
828 } catch (netgen::NgException & ex) {
829 return error( COMPERR_BAD_PARMETERS, ex.What() );
832 netgen::mparam.uselocalh = toOptimize; // restore as it is used at surface optimization
833 // ==================
835 // ==================
837 vector< const SMDS_MeshNode* > nodeVec;
840 netgen::OCCGeometry occgeom;
841 occgeom.shape = aShape;
842 occgeom.fmap.Add( aShape );
843 occgeom.CalcBoundingBox();
844 occgeom.facemeshstatus.SetSize(1);
845 occgeom.facemeshstatus = 0;
846 occgeom.face_maxh_modified.SetSize(1);
847 occgeom.face_maxh_modified = 0;
848 occgeom.face_maxh.SetSize(1);
849 occgeom.face_maxh = netgen::mparam.maxh;
851 // -------------------------
853 // -------------------------
854 // maps nodes to ng ID
857 // MESHCONST_ANALYSE step may lead to a failure, so we make an attempt
858 // w/o MESHCONST_ANALYSE at the second loop
860 enum { LOC_SIZE, NO_LOC_SIZE };
861 int iLoop = isCommonLocalSize ? 0 : 1;
862 int faceID = occgeom.fmap.FindIndex(aShape);
864 for ( ; iLoop < 2; iLoop++ )
866 //bool isMESHCONST_ANALYSE = false;
867 //TODO: check how to replace that
868 //InitComputeError();
870 netgen::Mesh * ngMesh = ngMeshes[ iLoop ];
871 ngMesh->DeleteMesh();
873 if ( iLoop == NO_LOC_SIZE )
875 ngMesh->SetGlobalH ( netgen::mparam.maxh );
876 ngMesh->SetMinimalH( netgen::mparam.minh );
877 netgen::Box<3> bb = occgeom.GetBoundingBox();
878 bb.Increase (bb.Diam()/10);
879 ngMesh->SetLocalH (bb.PMin(), bb.PMax(), netgen::mparam.grading);
880 aMesher.SetLocalSize( occgeom, *ngMesh );
881 aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMesh );
883 ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
884 } catch (netgen::NgException & ex) {
885 return error( COMPERR_BAD_PARMETERS, ex.What() );
889 TNodeToIDMap nodeToNetgenID;
892 ngMesh->AddFaceDescriptor( netgen::FaceDescriptor( faceID, solidID, solidID, 0 ));
893 // set local size according to size of existing segments
894 SMDS_ElemIteratorPtr iteratorElem = meshDS->elementsIterator(SMDSAbs_Edge);
895 while ( iteratorElem->more() ) // loop on elements on a geom face
897 const SMDS_MeshElement* elem = iteratorElem->next();
898 // Keeping only element that are in the element orientation file
899 bool isIn = elemOrientation.count(elem->GetID())==1;
904 bool isRev = elemOrientation[elem->GetID()];
909 for ( int iN = 0; iN < 2; ++iN )
911 const SMDS_MeshNode* node = elem->GetNode( iN );
912 const int shapeID = node->getshapeId();
913 int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
914 if ( ngID == invalid_ID )
916 ngID = ++Netgen_NbOfNodes;
917 Netgen_point [ 0 ] = node->X();
918 Netgen_point [ 1 ] = node->Y();
919 Netgen_point [ 2 ] = node->Z();
920 netgen::MeshPoint mp( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
921 ngMesh->AddPoint ( mp, 1, netgen::EDGEPOINT );
923 Netgen_segment[ isRev ? 1-iN : iN ] = ngID;
928 seg[0] = Netgen_segment[0];
929 seg[1] = Netgen_segment[1];
930 seg.edgenr = ngMesh->GetNSeg() +1;
933 ngMesh->AddSegment(seg);
935 int nbNodes2 = ngMesh->GetNP();
936 int nseg = ngMesh->GetNSeg();
938 // insert old nodes into nodeVec
939 nodeVec.resize( nodeToNetgenID.size() + 1, 0 );
940 TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
941 for ( ; n_id != nodeToNetgenID.end(); ++n_id )
942 nodeVec[ n_id->second ] = n_id->first;
943 nodeToNetgenID.clear();
946 //if ( !isCommonLocalSize )
947 //limitSize( ngMesh, mparam.maxh * 0.8);
949 // -------------------------
950 // Generate surface mesh
951 // -------------------------
953 const int startWith = netgen::MESHCONST_MESHSURFACE;
954 const int endWith = toOptimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
959 err = ngLib.GenerateMesh(occgeom, startWith, endWith, ngMesh);
960 if ( netgen::multithread.terminate )
963 str << "Error in netgen::OCCGenerateMesh() at " << netgen::multithread.task;
965 catch (Standard_Failure& ex)
968 str << "Exception in netgen::OCCGenerateMesh()"
969 << " at " << netgen::multithread.task
970 << ": " << ex.DynamicType()->Name();
971 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
972 str << ": " << ex.GetMessageString();
976 str << "Exception in netgen::OCCGenerateMesh()"
977 << " at " << netgen::multithread.task;
981 if ( iLoop == LOC_SIZE )
983 std::cout << "Need second run" << std::endl;
984 /*netgen::mparam.minh = netgen::mparam.maxh;
985 netgen::mparam.maxh = 0;
986 for ( size_t iW = 0; iW < wires.size(); ++iW )
988 StdMeshers_FaceSidePtr wire = wires[ iW ];
989 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
990 for ( size_t iP = 1; iP < uvPtVec.size(); ++iP )
992 SMESH_TNodeXYZ p( uvPtVec[ iP ].node );
993 netgen::Point3d np( p.X(),p.Y(),p.Z());
994 double segLen = p.Distance( uvPtVec[ iP-1 ].node );
995 double size = ngMesh->GetH( np );
996 netgen::mparam.minh = Min( netgen::mparam.minh, size );
997 netgen::mparam.maxh = Max( netgen::mparam.maxh, segLen );
1000 //cerr << "min " << mparam.minh << " max " << mparam.maxh << endl;
1001 netgen::mparam.minh *= 0.9;
1002 netgen::mparam.maxh *= 1.1;
1008 //faceErr.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, str ));
1012 // ----------------------------------------------------
1013 // Fill the SMESHDS with the generated nodes and faces
1014 // ----------------------------------------------------
1018 int nbNodes = ngMesh->GetNP();
1019 int nbFaces = ngMesh->GetNSE();
1020 std::cout << nbFaces << " " << nbNodes << std::endl;
1022 int nbInputNodes = (int) nodeVec.size()-1;
1023 nodeVec.resize( nbNodes+1, 0 );
1026 for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
1028 const netgen::MeshPoint& ngPoint = ngMesh->Point( ngID );
1029 SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
1030 nodeVec[ ngID ] = node;
1035 for ( i = 1; i <= nbFaces ; ++i )
1037 Ng_GetVolumeElement(ngLib.ngMesh(), i, Netgen_triangle);
1039 helper.AddFace (nodeVec.at( Netgen_triangle[0] ),
1040 nodeVec.at( Netgen_triangle[1] ),
1041 nodeVec.at( Netgen_triangle[2] ));
1048 //} // loop on FACEs