Salome HOME
Renaming functions and files + minor corrections in runner_main to detect what to do
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_Runner.cxx
1 // Copyright (C) 2007-2021  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  File   : NETGENPlugin_Runner.cxx
24 //  Author : Yoann AUDOUIN, EDF
25 //  Module : SMESH
26 //
27
28 #include "NETGENPlugin_Runner.hxx"
29
30
31 #include "NETGENPlugin_DriverParam.hxx"
32
33 #include <fstream>
34 #include <vector>
35 #include <boost/filesystem.hpp>
36 namespace fs = boost::filesystem;
37 #include <chrono>
38
39 // SMESH include
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_DriverStep.hxx>
54 #include <SMESH_DriverMesh.hxx>
55
56
57 // NETGENPlugin
58 // #include <NETGENPlugin_Mesher.hxx>
59 // #include <NETGENPlugin_Hypothesis.hxx>
60 #include "NETGENPlugin_Mesher.hxx"
61 #include "NETGENPlugin_Hypothesis.hxx"
62
63
64 // OCC include
65 #include <TopoDS.hxx>
66 #include <BRepClass3d_SolidClassifier.hxx>
67 #include <GProp_GProps.hxx>
68 #include <BRepGProp.hxx>
69
70 #include <Standard_Failure.hxx>
71 #include <Standard_ErrorHandler.hxx>
72 /*
73   Netgen include files
74 */
75
76 #ifndef OCCGEOMETRY
77 #define OCCGEOMETRY
78 #endif
79 #include <occgeom.hpp>
80 #include <meshing.hpp>
81
82 #ifdef NETGEN_V5
83 #include <ngexception.hpp>
84 #endif
85 #ifdef NETGEN_V6
86 #include <core/exception.hpp>
87 #endif
88
89 namespace nglib {
90 #include <nglib.h>
91 }
92 namespace netgen {
93
94   NETGENPLUGIN_DLL_HEADER
95   extern MeshingParameters mparam;
96
97   NETGENPLUGIN_DLL_HEADER
98   extern volatile multithreadt multithread;
99
100   NETGENPLUGIN_DLL_HEADER
101   extern bool merge_solids;
102
103 #ifdef NETGEN_V5
104   extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
105 #endif
106 }
107 using namespace nglib;
108
109 int error(int error_type, std::string msg)
110 {
111  std::cerr << msg << std::endl;
112   return error_type;
113 };
114
115 int error(const SMESH_Comment& comment)
116 {
117   return error(1, "SMESH_Comment error: "+comment);
118 };
119
120 /**
121  * @brief Set the netgen parameters
122  *
123  * @param aParams Internal structure of parameters
124  * @param mparams Netgen strcuture of parameters
125  */
126 void set_netgen_parameters(netgen_params& aParams)
127 {
128
129   // Default parameters
130 #ifdef NETGEN_V6
131
132   //netgen::mparam.nthreads = std::thread::hardware_concurrency();
133   netgen::mparam.nthreads = aParams.nbThreads;
134   netgen::mparam.parallel_meshing = aParams.nbThreads > 1;
135
136
137   if ( getenv( "SALOME_NETGEN_DISABLE_MULTITHREADING" ))
138   {
139     netgen::mparam.nthreads = 1;
140     netgen::mparam.parallel_meshing = false;
141   }
142
143 #endif
144
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;
162 #ifdef NETGEN_V6
163   // std::string
164   netgen::mparam.meshsizefilename = aParams.meshsizefilename;
165   netgen::mparam.closeedgefac = aParams.closeedgefac;
166
167 #else
168   // const char*
169   netgen::mparam.meshsizefilename= aParams.meshsizefilename.empty() ? 0 : aParams.meshsizefilename.c_str();
170 #endif
171 }
172
173 /**
174  * @brief compute mesh with netgen3d
175  *
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
182  *
183  * @return error code
184  */
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,
191              int nbThreads)
192 {
193   auto time0 = std::chrono::high_resolution_clock::now();
194   // Importing mesh
195   SMESH_Gen gen;
196
197   SMESH_Mesh *myMesh = gen.CreateMesh(false);
198   //TODO: To define
199   std::string mesh_name = "Maillage_1";
200
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;
205
206   // Importing shape
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;
212
213   // Importing hypothesis
214   netgen_params myParams;
215
216   importNetgenParams(hypo_file, myParams);
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;
222
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());
227
228
229   if(!ret){
230     std::cout << "Meshing failed" << std::endl;
231     return ret;
232   }
233
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;
240   }
241
242   return ret;
243 }
244
245 /**
246  * @brief Compute aShape within aMesh using netgen3d
247  *
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
254  *
255  * @return error code
256  */
257 int netgen3dInternal(TopoDS_Shape &aShape, SMESH_Mesh& aMesh, netgen_params& aParams,
258                       std::string new_element_file, std::string element_orientation_file,
259                       bool output_mesh)
260 {
261
262   auto time0 = std::chrono::high_resolution_clock::now();
263
264   netgen::multithread.terminate = 0;
265   netgen::multithread.task = "Volume meshing";
266
267   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
268
269   SMESH_MesherHelper helper(aMesh);
270   aParams._quadraticMesh = helper.IsQuadraticSubMesh(aShape);
271   helper.SetElementsOnShape( true );
272
273   int Netgen_NbOfNodes = 0;
274   double Netgen_point[3];
275   int Netgen_triangle[3];
276
277   NETGENPlugin_NetgenLibWrapper ngLib;
278   Ng_Mesh * Netgen_mesh = (Ng_Mesh*)ngLib._ngMesh;
279
280   // vector of nodes in which node index == netgen ID
281   vector< const SMDS_MeshNode* > nodeVec;
282   {
283     const int invalid_ID = -1;
284
285     SMESH::Controls::Area areaControl;
286     SMESH::Controls::TSequenceOfXYZ nodesCoords;
287
288     // maps nodes to ng ID
289     typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
290     typedef TNodeToIDMap::value_type                     TN2ID;
291     TNodeToIDMap nodeToNetgenID;
292
293     // find internal shapes
294     NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
295
296     // ---------------------------------
297     // Feed the Netgen with surface mesh
298     // ---------------------------------
299
300     TopAbs_ShapeEnum mainType = aMesh.GetShapeToMesh().ShapeType();
301     bool checkReverse = ( mainType == TopAbs_COMPOUND || mainType == TopAbs_COMPSOLID );
302
303     SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
304     if ( aParams._viscousLayersHyp )
305     {
306       netgen::multithread.percent = 3;
307       proxyMesh = aParams._viscousLayersHyp->Compute( aMesh, aShape );
308       if ( !proxyMesh )
309         return false;
310     }
311     if ( aMesh.NbQuadrangles() > 0 )
312     {
313       netgen::multithread.percent = 6;
314       StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
315       Adaptor->Compute(aMesh,aShape,proxyMesh.get());
316       proxyMesh.reset( Adaptor );
317     }
318
319     // Get list of elements + their orientation from element_orientation file
320     std::map<vtkIdType, bool> elemOrientation;
321     {
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
326           {
327             // check mesh face
328             const SMDS_MeshElement* elem = iteratorElem->next();
329             elemOrientation[elem->GetID()] = false;
330           }
331       } else {
332         std::ifstream df(element_orientation_file, ios::binary|ios::in);
333         int nbElement;
334         bool orient;
335
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
339         vtkIdType id;
340         df.read((char*)&nbElement, sizeof(int));
341
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;
346         }
347       }
348     }
349
350     // Adding elements from Mesh
351     SMDS_ElemIteratorPtr iteratorElem = meshDS->elementsIterator(SMDSAbs_Face);
352     bool isRev;
353     bool isInternalFace = false;
354
355     bool isIn;
356
357     while ( iteratorElem->more() ) // loop on elements on a geom face
358       {
359         // check mesh face
360         const SMDS_MeshElement* elem = iteratorElem->next();
361         if ( !elem )
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");
365
366         // Keeping only element that are in the element orientation file
367         isIn = elemOrientation.count(elem->GetID())==1;
368
369         if(!isIn)
370           continue;
371
372         // Get orientation
373         // Netgen requires that all the triangle point outside
374         isRev = elemOrientation[elem->GetID()];
375
376         // Add nodes of triangles and triangles them-selves to netgen mesh
377
378         // add three nodes of triangle
379         bool hasDegen = false;
380         for ( int iN = 0; iN < 3; ++iN )
381         {
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 ))
386           {
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 );
390             hasDegen = true;
391           }
392           int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
393           if ( ngID == invalid_ID )
394           {
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);
400           }
401
402           Netgen_triangle[ isRev ? 2-iN : iN ] = ngID;
403         }
404         // add triangle
405         if ( hasDegen && (Netgen_triangle[0] == Netgen_triangle[1] ||
406                           Netgen_triangle[0] == Netgen_triangle[2] ||
407                           Netgen_triangle[2] == Netgen_triangle[1] ))
408           continue;
409
410         Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
411
412         // TODO: Handle that case (quadrangle 2D) (isInternal is set to false)
413         if ( isInternalFace && !proxyMesh->IsTemporary( elem ))
414         {
415           swap( Netgen_triangle[1], Netgen_triangle[2] );
416           Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
417         }
418       }
419
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();
426
427     // TODO: Handle internal vertex
428     //if ( internals.hasInternalVertexInSolid() )
429     //{
430     //  netgen::OCCGeometry occgeo;
431     //  NETGENPlugin_Mesher::AddIntVerticesInSolids( occgeo,
432     //                                               (netgen::Mesh&) *Netgen_mesh,
433     //                                               nodeVec,
434     //                                               internals);
435     //}
436   }
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;
440
441   // -------------------------
442   // Generate the volume mesh
443   // -------------------------
444   netgen::multithread.terminate = 0;
445
446   netgen::Mesh* ngMesh = ngLib._ngMesh;
447   Netgen_mesh = ngLib.ngMesh();
448   Netgen_NbOfNodes = Ng_GetNP( Netgen_mesh );
449
450
451   int startWith = netgen::MESHCONST_MESHVOLUME;
452   int endWith   = netgen::MESHCONST_OPTVOLUME;
453   int err = 1;
454
455   NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
456   netgen::OCCGeometry occgeo;
457   set_netgen_parameters(aParams);
458
459   if ( aParams.has_netgen_param )
460   {
461     if ( aParams.has_local_size)
462     {
463       if ( ! &ngMesh->LocalHFunction() )
464       {
465         netgen::Point3d pmin, pmax;
466         ngMesh->GetBox( pmin, pmax, 0 );
467         ngMesh->SetLocalH( pmin, pmax, aParams.grading );
468       }
469       aMesher.SetLocalSize( occgeo, *ngMesh );
470
471       try {
472         ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
473       } catch (netgen::NgException & ex) {
474         return error( COMPERR_BAD_PARMETERS, ex.What() );
475       }
476     }
477     if ( !aParams.optimize )
478       endWith = netgen::MESHCONST_MESHVOLUME;
479   }
480   else if ( aParams.has_maxelementvolume_hyp )
481   {
482     netgen::mparam.maxh = pow( 72, 1/6. ) * pow( aParams.maxElementVolume, 1/3. );
483     // limitVolumeSize( ngMesh, netgen::mparam.maxh ); // result is unpredictable
484   }
485   else if ( aMesh.HasShapeToMesh() )
486   {
487     aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
488     netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
489   }
490   else
491   {
492     netgen::Point3d pmin, pmax;
493     ngMesh->GetBox (pmin, pmax);
494     netgen::mparam.maxh = Dist(pmin, pmax)/2;
495   }
496
497   if ( !aParams.has_netgen_param && aMesh.HasShapeToMesh() )
498   {
499     netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
500   }
501
502   try
503   {
504     OCC_CATCH_SIGNALS;
505
506     ngLib.CalcLocalH(ngMesh);
507     err = ngLib.GenerateMesh(occgeo, startWith, endWith, ngMesh);
508
509     if(netgen::multithread.terminate)
510       return false;
511     if ( err )
512       return error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
513   }
514   catch (Standard_Failure& ex)
515   {
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();
521     return error(str);
522   }
523   catch (netgen::NgException& exc)
524   {
525     SMESH_Comment str("NgException");
526     if ( strlen( netgen::multithread.task ) > 0 )
527       str << " at " << netgen::multithread.task;
528     str << ": " << exc.What();
529     return error(str);
530   }
531   catch (...)
532   {
533     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
534     if ( strlen( netgen::multithread.task ) > 0 )
535       str << " at " << netgen::multithread.task;
536     return error(str);
537   }
538
539   int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
540   int Netgen_NbOfTetra    = Ng_GetNE(Netgen_mesh);
541
542   // -------------------------------------------------------------------
543   // Feed back the SMESHDS with the generated Nodes and Volume Elements
544   // -------------------------------------------------------------------
545
546   if ( err )
547   {
548     SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
549     if ( ce && ce->HasBadElems() )
550       return error( ce );
551   }
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;
555
556   bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
557   if ( isOK && !new_element_file.empty() )
558   {
559     std::ofstream df(new_element_file, ios::out|ios::binary);
560
561     double Netgen_point[3];
562     int    Netgen_tetrahedron[4];
563
564     // Writing nodevec (correspondence netgen numbering mesh numbering)
565     // Number of nodes
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 )
569     {
570       //Id of the point
571       int id = nodeVec.at(nodeIndex)->GetID();
572       df.write((char*) &id, sizeof(int));
573     }
574
575     // Writing info on new points
576     for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
577     {
578       Ng_GetPoint(Netgen_mesh, nodeIndex, Netgen_point );
579       // Coordinates of the point
580       df.write((char *) &Netgen_point, sizeof(double)*3);
581     }
582
583     // create tetrahedrons
584     df.write((char*) &Netgen_NbOfTetra, sizeof(int));
585     for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
586     {
587       Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
588       df.write((char*) &Netgen_tetrahedron, sizeof(int)*4);
589     }
590   }
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;
594
595
596   // Adding new elements in aMesh as well
597   if ( output_mesh )
598   {
599     double Netgen_point[3];
600     int    Netgen_tetrahedron[4];
601
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 )
606     {
607       Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
608       nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
609                                              Netgen_point[1],
610                                              Netgen_point[2]);
611     }
612
613     // create tetrahedrons
614     for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
615     {
616       Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
617       try
618       {
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] ));
623       }
624       catch (...)
625       {
626       }
627     }
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;
631
632   }
633
634   return !err;
635 }
636
637 /**
638  * @brief compute mesh with netgen2d
639  *
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
646  *
647  * @return error code
648  */
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)
655 {
656
657   // Importing mesh
658   SMESH_Gen gen;
659
660   SMESH_Mesh *myMesh = gen.CreateMesh(false);
661   //TODO: To define
662   std::string mesh_name = "Maillage_1";
663
664   importMesh(input_mesh_file, *myMesh, mesh_name);
665
666   // Importing shape
667   TopoDS_Shape myShape;
668   importShape(shape_file, myShape);
669
670   // Importing hypothesis
671   netgen_params myParams;
672
673   importNetgenParams(hypo_file, myParams);
674
675   std::cout << "Meshing with netgen3d" << std::endl;
676   int ret = netgen2dInternal(myShape, *myMesh, myParams,
677                               new_element_file, element_orientation_file,
678                               !output_mesh_file.empty());
679
680   if(!ret){
681     std::cout << "Meshing failed" << std::endl;
682     return ret;
683   }
684
685   if(!output_mesh_file.empty())
686     exportMesh(output_mesh_file, *myMesh, mesh_name);
687
688   return ret;
689 }
690
691
692 // TODO: Not working properly
693 /**
694  * @brief Compute aShape within aMesh using netgen2d
695  *
696  * @param aShape the shape
697  * @param aMesh the mesh
698  * @param aParams the netgen parameters
699  * @param new_element_file file containing data on the new point/tetra added by netgen
700  *
701  * @return error code
702  */
703 int netgen2dInternal(TopoDS_Shape &aShape, SMESH_Mesh& aMesh, netgen_params& aParams,
704                       std::string new_element_file, std::string element_orientation_file,
705                       bool output_mesh)
706 {
707   netgen::multithread.terminate = 0;
708   netgen::multithread.task = "Surface meshing";
709
710   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
711   SMESH_MesherHelper helper(aMesh);
712   helper.SetElementsOnShape( true );
713
714   NETGENPlugin_NetgenLibWrapper ngLib;
715   ngLib._isComputeOk = false;
716
717   netgen::Mesh   ngMeshNoLocSize;
718   netgen::Mesh * ngMeshes[2] = { (netgen::Mesh*) ngLib._ngMesh,  & ngMeshNoLocSize };
719   netgen::OCCGeometry occgeoComm;
720
721   std::map<vtkIdType, bool> elemOrientation;
722
723   typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
724   typedef TNodeToIDMap::value_type                     TN2ID;
725   const int invalid_ID = -1;
726   int Netgen_NbOfNodes=0;
727   double Netgen_point[3];
728   int Netgen_segment[2];
729   int Netgen_triangle[3];
730
731   // min / max sizes are set as follows:
732   // if ( _hypParameters )
733   //    min and max are defined by the user
734   // else if ( aParams.has_LengthFromEdges_hyp )
735   //    min = aMesher.GetDefaultMinSize()
736   //    max = average segment len of a FACE
737   // else if ( _hypMaxElementArea )
738   //    min = aMesher.GetDefaultMinSize()
739   //    max = f( _hypMaxElementArea )
740   // else
741   //    min = aMesher.GetDefaultMinSize()
742   //    max = max segment len of a FACE
743   NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
744   set_netgen_parameters( aParams );
745   const bool toOptimize = aParams.optimize;
746   if ( aParams.has_maxelementvolume_hyp )
747   {
748     netgen::mparam.maxh = sqrt( 2. * aParams.maxElementVolume / sqrt(3.0) );
749   }
750   netgen::mparam.quad = aParams.quad;
751
752   // local size is common for all FACEs in aShape?
753   const bool isCommonLocalSize = ( !aParams.has_LengthFromEdges_hyp && !aParams.has_maxelementvolume_hyp && netgen::mparam.uselocalh );
754   const bool isDefaultHyp = ( !aParams.has_LengthFromEdges_hyp && !aParams.has_maxelementvolume_hyp && !aParams.has_netgen_param );
755
756
757   if ( isCommonLocalSize ) // compute common local size in ngMeshes[0]
758   {
759     //list< SMESH_subMesh* > meshedSM[4]; --> all sub-shapes are added to occgeoComm
760     aMesher.PrepareOCCgeometry( occgeoComm, aShape, aMesh );//, meshedSM );
761
762     // local size set at MESHCONST_ANALYSE step depends on
763     // minh, face_maxh, grading and curvaturesafety; find minh if not set by the user
764     if ( !aParams.has_netgen_param || netgen::mparam.minh < DBL_MIN )
765     {
766       if ( !aParams.has_netgen_param )
767         netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam() / 3.;
768       netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
769     }
770     // set local size depending on curvature and NOT closeness of EDGEs
771 #ifdef NETGEN_V6
772     const double factor = 2; //netgen::occparam.resthcloseedgefac;
773 #else
774     const double factor = netgen::occparam.resthcloseedgefac;
775     netgen::occparam.resthcloseedgeenable = false;
776     netgen::occparam.resthcloseedgefac = 1.0 + netgen::mparam.grading;
777 #endif
778     occgeoComm.face_maxh = netgen::mparam.maxh;
779 #ifdef NETGEN_V6
780     netgen::OCCParameters occparam;
781     netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0], netgen::mparam, occparam );
782 #else
783     netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0] );
784 #endif
785     occgeoComm.emap.Clear();
786     occgeoComm.vmap.Clear();
787
788     // Reading list of element to integrate into netgen mesh
789     {
790       std::ifstream df(element_orientation_file, ios::in|ios::binary);
791       int nbElement;
792       vtkIdType id;
793       bool orient;
794       df.read((char*)&nbElement, sizeof(int));
795
796       for(int ielem=0;ielem<nbElement;++ielem){
797         df.read((char*) &id, sizeof(vtkIdType));
798         df.read((char*) &orient, sizeof(bool));
799         elemOrientation[id] = orient;
800       }
801     }
802
803     bool isIn;
804     // set local size according to size of existing segments
805     SMDS_ElemIteratorPtr iteratorElem = meshDS->elementsIterator(SMDSAbs_Edge);
806     while ( iteratorElem->more() ) // loop on elements on a geom face
807     {
808       const SMDS_MeshElement* seg = iteratorElem->next();
809       // Keeping only element that are in the element orientation file
810       isIn = elemOrientation.count(seg->GetID())==1;
811
812       if(!isIn)
813         continue;
814
815       SMESH_TNodeXYZ n1 = seg->GetNode(0);
816       SMESH_TNodeXYZ n2 = seg->GetNode(1);
817       gp_XYZ p = 0.5 * ( n1 + n2 );
818       netgen::Point3d pi(p.X(), p.Y(), p.Z());
819       ngMeshes[0]->RestrictLocalH( pi, factor * ( n1 - n2 ).Modulus() );
820     }
821
822     // set local size defined on shapes
823     aMesher.SetLocalSize( occgeoComm, *ngMeshes[0] );
824     aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMeshes[0] );
825     try {
826       ngMeshes[0]->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
827     } catch (netgen::NgException & ex) {
828       return error( COMPERR_BAD_PARMETERS, ex.What() );
829     }
830   }
831   netgen::mparam.uselocalh = toOptimize; // restore as it is used at surface optimization
832   // ==================
833   // Loop on all FACEs
834   // ==================
835
836   vector< const SMDS_MeshNode* > nodeVec;
837
838     // prepare occgeom
839     netgen::OCCGeometry occgeom;
840     occgeom.shape = aShape;
841     occgeom.fmap.Add( aShape );
842     occgeom.CalcBoundingBox();
843     occgeom.facemeshstatus.SetSize(1);
844     occgeom.facemeshstatus = 0;
845     occgeom.face_maxh_modified.SetSize(1);
846     occgeom.face_maxh_modified = 0;
847     occgeom.face_maxh.SetSize(1);
848     occgeom.face_maxh = netgen::mparam.maxh;
849
850     // -------------------------
851     // Fill netgen mesh
852     // -------------------------
853     // maps nodes to ng ID
854
855
856     // MESHCONST_ANALYSE step may lead to a failure, so we make an attempt
857     // w/o MESHCONST_ANALYSE at the second loop
858     int err = 0;
859     enum { LOC_SIZE, NO_LOC_SIZE };
860     int iLoop = isCommonLocalSize ? 0 : 1;
861     int faceID = occgeom.fmap.FindIndex(aShape);
862     int solidID = 0;
863     for ( ; iLoop < 2; iLoop++ )
864     {
865       //bool isMESHCONST_ANALYSE = false;
866       //TODO: check how to replace that
867       //InitComputeError();
868
869       netgen::Mesh * ngMesh = ngMeshes[ iLoop ];
870       ngMesh->DeleteMesh();
871
872       if ( iLoop == NO_LOC_SIZE )
873       {
874         ngMesh->SetGlobalH ( netgen::mparam.maxh );
875         ngMesh->SetMinimalH( netgen::mparam.minh );
876         netgen::Box<3> bb = occgeom.GetBoundingBox();
877         bb.Increase (bb.Diam()/10);
878         ngMesh->SetLocalH (bb.PMin(), bb.PMax(), netgen::mparam.grading);
879         aMesher.SetLocalSize( occgeom, *ngMesh );
880         aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMesh );
881         try {
882           ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
883         } catch (netgen::NgException & ex) {
884           return error( COMPERR_BAD_PARMETERS, ex.What() );
885         }
886       }
887
888       TNodeToIDMap nodeToNetgenID;
889
890       nodeVec.clear();
891       ngMesh->AddFaceDescriptor( netgen::FaceDescriptor( faceID, solidID, solidID, 0 ));
892           // set local size according to size of existing segments
893       SMDS_ElemIteratorPtr iteratorElem = meshDS->elementsIterator(SMDSAbs_Edge);
894       while ( iteratorElem->more() ) // loop on elements on a geom face
895       {
896         const SMDS_MeshElement* elem = iteratorElem->next();
897         // Keeping only element that are in the element orientation file
898         bool isIn = elemOrientation.count(elem->GetID())==1;
899
900         if(!isIn)
901           continue;
902
903         bool isRev = elemOrientation[elem->GetID()];
904         std::cerr << isRev;
905
906
907
908         for ( int iN = 0; iN < 2; ++iN )
909         {
910           const SMDS_MeshNode* node = elem->GetNode( iN );
911           const int shapeID = node->getshapeId();
912           int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
913           if ( ngID == invalid_ID )
914           {
915             ngID = ++Netgen_NbOfNodes;
916             Netgen_point [ 0 ] = node->X();
917             Netgen_point [ 1 ] = node->Y();
918             Netgen_point [ 2 ] = node->Z();
919             netgen::MeshPoint mp( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
920             ngMesh->AddPoint ( mp, 1, netgen::EDGEPOINT );
921           }
922           Netgen_segment[ isRev ? 1-iN : iN ] = ngID;
923         }
924         // add segment
925
926         netgen::Segment seg;
927         seg[0] = Netgen_segment[0];
928         seg[1] = Netgen_segment[1];
929         seg.edgenr = ngMesh->GetNSeg() +1;
930         seg.si = faceID;
931
932         ngMesh->AddSegment(seg);
933       }
934       int nbNodes2 = ngMesh->GetNP();
935       int nseg = ngMesh->GetNSeg();
936
937       // insert old nodes into nodeVec
938       nodeVec.resize( nodeToNetgenID.size() + 1, 0 );
939       TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
940       for ( ; n_id != nodeToNetgenID.end(); ++n_id )
941         nodeVec[ n_id->second ] = n_id->first;
942       nodeToNetgenID.clear();
943
944
945       //if ( !isCommonLocalSize )
946       //limitSize( ngMesh, mparam.maxh * 0.8);
947
948       // -------------------------
949       // Generate surface mesh
950       // -------------------------
951
952       const int startWith = netgen::MESHCONST_MESHSURFACE;
953       const int endWith   = toOptimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
954
955       SMESH_Comment str;
956       try {
957         OCC_CATCH_SIGNALS;
958         err = ngLib.GenerateMesh(occgeom, startWith, endWith, ngMesh);
959         if ( netgen::multithread.terminate )
960           return false;
961         if ( err )
962           str << "Error in netgen::OCCGenerateMesh() at " << netgen::multithread.task;
963       }
964       catch (Standard_Failure& ex)
965       {
966         err = 1;
967         str << "Exception in  netgen::OCCGenerateMesh()"
968             << " at " << netgen::multithread.task
969             << ": " << ex.DynamicType()->Name();
970         if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
971           str << ": " << ex.GetMessageString();
972       }
973       catch (...) {
974         err = 1;
975         str << "Exception in  netgen::OCCGenerateMesh()"
976             << " at " << netgen::multithread.task;
977       }
978       if ( err )
979       {
980         if ( iLoop == LOC_SIZE )
981         {
982           std::cout << "Need second run" << std::endl;
983           /*netgen::mparam.minh = netgen::mparam.maxh;
984           netgen::mparam.maxh = 0;
985           for ( size_t iW = 0; iW < wires.size(); ++iW )
986           {
987             StdMeshers_FaceSidePtr wire = wires[ iW ];
988             const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
989             for ( size_t iP = 1; iP < uvPtVec.size(); ++iP )
990             {
991               SMESH_TNodeXYZ   p( uvPtVec[ iP ].node );
992               netgen::Point3d np( p.X(),p.Y(),p.Z());
993               double segLen = p.Distance( uvPtVec[ iP-1 ].node );
994               double   size = ngMesh->GetH( np );
995               netgen::mparam.minh = Min( netgen::mparam.minh, size );
996               netgen::mparam.maxh = Max( netgen::mparam.maxh, segLen );
997             }
998           }
999           //cerr << "min " << mparam.minh << " max " << mparam.maxh << endl;
1000           netgen::mparam.minh *= 0.9;
1001           netgen::mparam.maxh *= 1.1;
1002           */
1003           continue;
1004         }
1005         else
1006         {
1007           //faceErr.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, str ));
1008         }
1009       }
1010
1011       // ----------------------------------------------------
1012       // Fill the SMESHDS with the generated nodes and faces
1013       // ----------------------------------------------------
1014
1015       if(output_mesh)
1016       {
1017         int nbNodes = ngMesh->GetNP();
1018         int nbFaces = ngMesh->GetNSE();
1019         std::cout << nbFaces << " " << nbNodes << std::endl;
1020
1021         int nbInputNodes = (int) nodeVec.size()-1;
1022         nodeVec.resize( nbNodes+1, 0 );
1023
1024         // add nodes
1025         for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
1026         {
1027           const netgen::MeshPoint& ngPoint = ngMesh->Point( ngID );
1028           SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
1029           nodeVec[ ngID ] = node;
1030         }
1031
1032         // create faces
1033         int i,j;
1034         for ( i = 1; i <= nbFaces ; ++i )
1035         {
1036           Ng_GetVolumeElement(ngLib.ngMesh(), i, Netgen_triangle);
1037
1038           helper.AddFace (nodeVec.at( Netgen_triangle[0] ),
1039                           nodeVec.at( Netgen_triangle[1] ),
1040                           nodeVec.at( Netgen_triangle[2] ));
1041
1042         }
1043       } // output_mesh
1044
1045       break;
1046     } // two attempts
1047   //} // loop on FACEs
1048
1049   return true;
1050
1051 }