Salome HOME
Merge branch 'V9_7_BR'
[plugins/ghs3dplugin.git] / src / GHS3DPlugin / MG_Tetra_API.cxx
1 // Copyright (C) 2004-2021  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "MG_Tetra_API.hxx"
21
22 #ifdef WIN32
23 #define NOMINMAX
24 #endif
25 #include <SMESH_Comment.hxx>
26 #include <SMESH_File.hxx>
27 #include <Utils_SALOME_Exception.hxx>
28
29 #include <vector>
30 #include <iterator>
31 #include <cstring>
32
33 #ifdef USE_MG_LIBS
34
35 extern "C"{
36 #include <meshgems/meshgems.h>
37 #include <meshgems/tetra.h>
38 }
39
40 struct MG_Tetra_API::LibData
41 {
42   // MG objects
43   context_t *       _context;
44   tetra_session_t * _session;
45   mesh_t *          _tria_mesh;
46   sizemap_t *       _sizemap;
47   mesh_t *          _tetra_mesh;
48
49   // data to pass to MG
50   std::vector<double> _xyz;
51   std::vector<double> _nodeSize; // required nodes
52   std::vector<int>    _edgeNodes;
53   int                 _nbRequiredEdges;
54   std::vector<int>    _triaNodes;
55   int                 _nbRequiredTria;
56   std::vector<int>    _tetraNodes;
57
58   int                 _count;
59   volatile bool&      _cancelled_flag;
60   std::string         _errorStr;
61   double&             _progress;
62   bool                _progressInCallBack;
63
64   LibData( volatile bool & cancelled_flag, double& progress )
65     : _context(0), _session(0), _tria_mesh(0), _sizemap(0), _tetra_mesh(0),
66       _nbRequiredEdges(0), _nbRequiredTria(0),
67       _cancelled_flag( cancelled_flag ), _progress( progress ), _progressInCallBack( false )
68   {
69   }
70   // methods setting callbacks implemented after callback definitions
71   void Init();
72   bool Compute();
73
74   ~LibData()
75   {
76     if ( _tetra_mesh )
77       tetra_regain_mesh( _session, _tetra_mesh );
78     if ( _session )
79       tetra_session_delete( _session );
80     if ( _tria_mesh )
81       mesh_delete( _tria_mesh );
82     if ( _sizemap )
83       sizemap_delete( _sizemap );
84     if ( _context )
85       context_delete( _context );
86
87     _tetra_mesh = 0;
88     _session = 0;
89     _tria_mesh = 0;
90     _sizemap = 0;
91     _context = 0;
92   }
93
94   void AddError( const char *txt )
95   {
96     if ( txt )
97       _errorStr += txt;
98   }
99
100   const std::string& GetErrors()
101   {
102     return _errorStr;
103   }
104
105   void MG_Error(const char* txt="")
106   {
107     SMESH_Comment msg("\nMeshGems error. ");
108     msg << txt << "\n";
109     AddError( msg.c_str() );
110   }
111
112   bool SetParam( const std::string& param, const std::string& value )
113   {
114     status_t ret = tetra_set_param( _session, param.c_str(), value.c_str() );
115 #ifdef _DEBUG_
116     //std::cout << param << " = " << value << std::endl;
117 #endif
118     return ( ret == STATUS_OK );
119   }
120
121   bool Cancelled()
122   {
123     return _cancelled_flag;
124   }
125
126   int ReadNbSubDomains()
127   {
128     integer nb = 0;
129     status_t ret = mesh_get_subdomain_count( _tetra_mesh, & nb );
130
131     if ( ret != STATUS_OK ) MG_Error("mesh_get_subdomain_count problem");
132     return nb;
133   }
134
135   int ReadNbNodes()
136   {
137     integer nb = 0;
138     status_t ret = mesh_get_vertex_count( _tetra_mesh, & nb );
139
140     if ( ret != STATUS_OK ) MG_Error("mesh_get_vertex_count problem");
141     return nb;
142   }
143
144   int ReadNbEdges()
145   {
146     integer nb = 0;
147     status_t ret = mesh_get_edge_count( _tetra_mesh, & nb );
148
149     if ( ret != STATUS_OK ) MG_Error("mesh_get_edge_count problem");
150     return nb;
151   }
152
153   int ReadNbTria()
154   {
155     integer nb = 0;
156     status_t ret = mesh_get_triangle_count( _tetra_mesh, & nb );
157
158     if ( ret != STATUS_OK ) MG_Error("mesh_get_triangle_count problem");
159     return nb;
160   }
161
162   int ReadNbQuads()
163   {
164     integer nb = 0;
165     status_t ret = mesh_get_quadrangle_count( _tetra_mesh, & nb );
166
167     if ( ret != STATUS_OK ) MG_Error("mesh_get_quadrangle_count problem");
168     return nb;
169   }
170
171   int ReadNbTetra()
172   {
173     integer nb = 0;
174     status_t ret = mesh_get_tetrahedron_count( _tetra_mesh, & nb );
175
176     if ( ret != STATUS_OK ) MG_Error("mesh_get_tetrahedron_count problem");
177     return nb;
178   }
179
180   int ReadNbHexa()
181   {
182     integer nb = 0;
183     status_t ret = mesh_get_hexahedron_count( _tetra_mesh, & nb );
184
185     if ( ret != STATUS_OK ) MG_Error("mesh_get_hexahedron_count problem");
186     return nb;
187   }
188
189   void ResetCounter()
190   {
191     _count = 1;
192   }
193
194   void ReadSubDomain( int* nbNodes, int* faceInd, int* ori, int* domain )
195   {
196     integer tag, seed_type, seed_idx, seed_orientation;
197     status_t ret = mesh_get_subdomain_description( _tetra_mesh, _count,
198                                                    &tag, &seed_type, &seed_idx, &seed_orientation);
199
200     if ( ret != STATUS_OK ) MG_Error( "unable to get a sub-domain description");
201
202     *nbNodes = 3;
203     *faceInd = seed_idx;
204     *domain  = tag;
205     *ori     = seed_orientation;
206
207     ++_count;
208   }
209   void ReadNodeXYZ( double* x, double* y, double *z, int* /*domain*/  )
210   {
211     real coo[3];
212     status_t ret = mesh_get_vertex_coordinates( _tetra_mesh, _count, coo );
213     if ( ret != STATUS_OK ) MG_Error( "unable to get resulting vertices" );
214
215     *x = coo[0];
216     *y = coo[1];
217     *z = coo[2];
218
219     ++_count;
220   }
221
222   void ReadEdgeNodes( int* node1, int* node2, int* domain )
223   {
224     integer vtx[2], tag;
225     status_t ret = mesh_get_edge_vertices( _tetra_mesh, _count, vtx);
226     if (ret != STATUS_OK) MG_Error( "unable to get resulting edge" );
227
228     *node1 = vtx[0];
229     *node2 = vtx[1];
230
231     ret = mesh_get_edge_tag( _tetra_mesh, _count, &tag );
232     if (ret != STATUS_OK) MG_Error( "unable to get resulting edge tag" );
233
234     *domain = tag;
235
236     ++_count;
237   }
238
239   void ReadTriaNodes( int* node1, int* node2, int* node3, int* domain )
240   {
241     integer vtx[3], tag;
242     status_t ret = mesh_get_triangle_vertices( _tetra_mesh, _count, vtx);
243     if (ret != STATUS_OK) MG_Error( "unable to get resulting triangle" );
244
245     *node1 = vtx[0];
246     *node2 = vtx[1];
247     *node3 = vtx[2];
248
249     ret = mesh_get_triangle_tag( _tetra_mesh, _count, &tag );
250     if (ret != STATUS_OK) MG_Error( "unable to get resulting triangle tag" );
251
252     *domain = tag;
253
254     ++_count;
255   }
256
257   void ReadQuadNodes( int* node1, int* node2, int* node3, int* node4, int* domain )
258   {
259     integer vtx[4], tag;
260     status_t ret = mesh_get_quadrangle_vertices( _tetra_mesh, _count, vtx);
261     if (ret != STATUS_OK) MG_Error( "unable to get resulting quadrangle" );
262
263     *node1 = vtx[0];
264     *node2 = vtx[1];
265     *node3 = vtx[2];
266     *node4 = vtx[3];
267
268     ret = mesh_get_quadrangle_tag( _tetra_mesh, _count, &tag );
269     if (ret != STATUS_OK) MG_Error( "unable to get resulting quadrangle tag" );
270
271     *domain = tag;
272
273     ++_count;
274   }
275
276   void ReadTetraNodes( int* node1, int* node2, int* node3, int* node4, int* domain )
277   {
278     integer vtx[4], tag;
279     status_t ret = mesh_get_tetrahedron_vertices( _tetra_mesh, _count, vtx);
280     if (ret != STATUS_OK) MG_Error( "unable to get resulting tetrahedron" );
281
282     *node1 = vtx[0];
283     *node2 = vtx[1];
284     *node3 = vtx[2];
285     *node4 = vtx[3];
286
287     ret = mesh_get_tetrahedron_tag( _tetra_mesh, _count, &tag );
288     if (ret != STATUS_OK) MG_Error( "unable to get resulting tetrahedron tag" );
289
290     *domain = tag;
291
292     ++_count;
293   }
294
295   void ReadHexaNodes( int* node1, int* node2, int* node3, int* node4,
296                      int* node5, int* node6, int* node7, int* node8, int* domain )
297   {
298     integer vtx[8], tag;
299     status_t ret = mesh_get_hexahedron_vertices( _tetra_mesh, _count, vtx);
300     if (ret != STATUS_OK) MG_Error( "unable to get resulting hexahedron" );
301
302     *node1 = vtx[0];
303     *node2 = vtx[1];
304     *node3 = vtx[2];
305     *node4 = vtx[3];
306     *node5 = vtx[4];
307     *node6 = vtx[5];
308     *node7 = vtx[6];
309     *node8 = vtx[7];
310
311     ret = mesh_get_hexahedron_tag( _tetra_mesh, _count, &tag );
312     if (ret != STATUS_OK) MG_Error( "unable to get resulting hexahedron tag" );
313
314     *domain = tag;
315
316     ++_count;
317   }
318
319   void SetNbVertices( int nb )
320   {
321     _xyz.reserve( _xyz.capacity() + nb );
322   }
323
324   void SetNbEdges( int nb )
325   {
326     _edgeNodes.reserve( nb * 2 );
327   }
328
329   void SetNbTria( int nb )
330   {
331     _triaNodes.reserve( nb * 3 );
332   }
333
334   void SetNbTetra( int nb )
335   {
336     _tetraNodes.reserve( nb * 4 );
337   }
338
339   void SetNbReqVertices( int nb )
340   {
341     _nodeSize.reserve( nb );
342   }
343
344   void SetNbReqEdges( int nb )
345   {
346     _nbRequiredEdges = nb;
347   }
348
349   void SetNbReqTria( int nb )
350   {
351     _nbRequiredTria = nb;
352   }
353
354   void AddNode( double x, double y, double z, int /*domain*/ )
355   {
356     _xyz.push_back( x );
357     _xyz.push_back( y );
358     _xyz.push_back( z );
359   }
360
361   void AddSizeAtNode( double size )
362   {
363     _nodeSize.push_back( size );
364   }
365   
366   void AddEdgeNodes( int node1, int node2, int /*domain*/ )
367   {
368     _edgeNodes.push_back( node1 );
369     _edgeNodes.push_back( node2 );
370   }
371   
372   void AddTriaNodes( int node1, int node2, int node3, int /*domain*/ )
373   {
374     _triaNodes.push_back( node1 );
375     _triaNodes.push_back( node2 );
376     _triaNodes.push_back( node3 );
377   }
378
379   void AddTetraNodes( int node1, int node2, int node3, int node4, int /*domain*/ )
380   {
381     _tetraNodes.push_back( node1 );
382     _tetraNodes.push_back( node2 );
383     _tetraNodes.push_back( node3 );
384     _tetraNodes.push_back( node4 );
385   }
386
387   int NbNodes()
388   {
389     return _xyz.size() / 3;
390   }
391
392   double* NodeCoord( int iNode )
393   {
394     return & _xyz[ iNode * 3 ];
395   }
396
397   int NbEdges()
398   {
399     return _edgeNodes.size() / 2;
400   }
401
402   int* GetEdgeNodes( int iEdge )
403   {
404     return & _edgeNodes[ iEdge * 2 ];
405   }
406
407   int NbTriangles()
408   {
409     return _triaNodes.size() / 3;
410   }
411
412   int NbTetra()
413   {
414     return _tetraNodes.size() / 4;
415   }
416
417   int * GetTriaNodes( int iTria )
418   {
419     return & _triaNodes[ iTria * 3 ];
420   }
421
422   int * GetTetraNodes( int iTet )
423   {
424     return & _tetraNodes[ iTet * 4 ];
425   }
426
427   int IsVertexRequired( int iNode )
428   {
429     return ! ( iNode < int( NbNodes() - _nodeSize.size() ));
430   }
431
432   double GetSizeAtVertex( int iNode )
433   {
434     return IsVertexRequired( iNode ) ? _nodeSize[ iNode - NbNodes() + _nodeSize.size() ] : 0.;
435   }
436 };
437
438 namespace // functions called by MG library to exchange with the application
439 {
440   status_t get_vertex_count(integer * nbvtx, void *user_data)
441   {
442     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
443     *nbvtx = data->NbNodes();
444
445     return STATUS_OK;
446   }
447
448   status_t get_vertex_coordinates(integer ivtx, real * xyz, void *user_data)
449   {
450     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
451     double* coord = data->NodeCoord( ivtx-1 );
452     for (int j = 0; j < 3; j++)
453       xyz[j] = coord[j];
454
455     return STATUS_OK;
456   }
457   status_t get_edge_count(integer * nbedge, void *user_data)
458   {
459     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
460     *nbedge = data->NbEdges();
461
462     return STATUS_OK;
463   }
464
465   status_t get_edge_vertices(integer iedge, integer * vedge, void *user_data)
466   {
467     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
468     int* nodes = data->GetEdgeNodes( iedge-1 );
469     vedge[0] = nodes[0];
470     vedge[1] = nodes[1];
471
472     return STATUS_OK;
473   }
474
475   status_t get_triangle_count(integer * nbtri, void *user_data)
476   {
477     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
478     *nbtri = data->NbTriangles();
479
480     return STATUS_OK;
481   }
482
483   status_t get_triangle_vertices(integer itri, integer * vtri, void *user_data)
484   {
485     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
486     int* nodes = data->GetTriaNodes( itri-1 );
487     vtri[0] = nodes[0];
488     vtri[1] = nodes[1];
489     vtri[2] = nodes[2];
490
491     return STATUS_OK;
492   }
493
494   // status_t get_triangle_extra_vertices(integer itri, integer * typetri,
495   //                                      integer * evtri, void *user_data)
496   // {
497   //   int j;
498   //   MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
499
500   //   if (1) {
501   //     /* We want to describe a linear "3 nodes" triangle */
502   //     *typetri = MESHGEMS_MESH_ELEMENT_TYPE_TRIA3;
503   //   } else {
504   //     /* We want to describe a quadratic "6 nodes" triangle */
505   //     *typetri = MESHGEMS_MESH_ELEMENT_TYPE_TRIA6;
506   //     for (j = 0; j < 3; j++)
507   //       evtri[j] = 0;             /* the j'th quadratic vertex index of the itri'th triangle */
508   //   }
509
510   //   return STATUS_OK;
511   // }
512
513   status_t get_tetrahedron_count(integer * nbtetra, void *user_data)
514   {
515     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
516     *nbtetra = data->NbTetra();
517
518     return STATUS_OK;
519   }
520
521   status_t get_tetrahedron_vertices(integer itetra, integer * vtetra,
522                                     void *user_data)
523   {
524     int j;
525     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
526     int* nodes = data->GetTetraNodes( itetra-1 );
527     for (j = 0; j < 4; j++)
528       vtetra[j] = nodes[j];
529
530     return STATUS_OK;
531   }
532
533   status_t get_vertex_required_property(integer ivtx, integer * rvtx, void *user_data)
534   {
535     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
536     *rvtx = data->IsVertexRequired( ivtx - 1 );
537
538     return STATUS_OK;
539   }
540
541   status_t get_vertex_weight(integer ivtx, real * wvtx, void *user_data)
542   {
543     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
544     *wvtx = data->GetSizeAtVertex( ivtx - 1 );
545
546     return STATUS_OK;
547   }
548
549   status_t my_message_cb(message_t * msg, void *user_data)
550   {
551     char *desc;
552     message_get_description(msg, &desc);
553
554     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
555     data->AddError( desc );
556
557 #ifdef _DEBUG_
558     //std::cout << desc << std::endl;
559 #endif
560
561     if ( strncmp( "MGMESSAGE  1009001 ", desc, 19 ) == 0 )
562     {
563       // progress message (10%): "MGMESSAGE  1009001  0 1 1.000000e+01"
564       data->_progress = atof( desc + 24 );
565
566       data->_progressInCallBack = true;
567     }
568
569     if ( !data->_progressInCallBack )
570     {
571       // Compute progress
572       // corresponding messages are:
573       // "  -- PHASE 1 COMPLETED"               => 10 %
574       // "  -- PHASE 2 COMPLETED"               => 25 %
575       // "     ** ITERATION   1"                => 25.* %
576       // "     ** ITERATION   2"                => 25.* %
577       // "  -- PHASE 3 COMPLETED"               => 70 %
578       // "  -- PHASE 4 COMPLETED"               => 98 %
579
580       if ( strncmp( "-- PHASE ", desc + 2, 9 ) == 0 && desc[ 13 ] == 'C' )
581       {
582         const double progress[] = { 10., 25., 70., 98., 100., 100., 100. };
583         int       phase = atoi( desc + 11 );
584         data->_progress = std::max( data->_progress, progress[ phase - 1 ] / 100. );
585       }
586       else if ( strncmp( "** ITERATION ", desc + 5, 13 ) == 0 )
587       {
588         int         iter = atoi( desc + 20 );
589         double   percent = 25. + iter * ( 70 - 25 ) / 20.;
590         data->_progress = std::max( data->_progress, ( percent / 100. ));
591       }
592     }
593
594     return STATUS_OK;
595   }
596
597   status_t my_interrupt_callback(integer *interrupt_status, void *user_data)
598   {
599     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
600     *interrupt_status = ( data->Cancelled() ? INTERRUPT_STOP : INTERRUPT_CONTINUE );
601
602
603     return STATUS_OK;
604   }
605
606 } // end namespace
607
608
609 void MG_Tetra_API::LibData::Init()
610 {
611   status_t ret;
612
613   // Create the meshgems working context
614   _context = context_new();
615   if ( !_context ) MG_Error( "unable to create a new context" );
616
617   // Set the message callback for the _context.
618   ret = context_set_message_callback( _context, my_message_cb, this );
619   if ( ret != STATUS_OK ) MG_Error("in context_set_message_callback");
620
621   // Create the structure holding the callbacks giving access to triangle mesh
622   _tria_mesh = mesh_new( _context );
623   if ( !_tria_mesh ) MG_Error("unable to create a new mesh");
624
625   // Set callbacks to provide triangle mesh data
626   mesh_set_get_vertex_count( _tria_mesh, get_vertex_count, this );
627   mesh_set_get_vertex_coordinates( _tria_mesh, get_vertex_coordinates, this );
628   mesh_set_get_vertex_required_property( _tria_mesh, get_vertex_required_property, this );
629   mesh_set_get_edge_count( _tria_mesh, get_edge_count, this);
630   mesh_set_get_edge_vertices( _tria_mesh, get_edge_vertices, this );
631   mesh_set_get_triangle_count( _tria_mesh, get_triangle_count, this );
632   mesh_set_get_triangle_vertices( _tria_mesh, get_triangle_vertices, this );
633   mesh_set_get_tetrahedron_count( _tria_mesh, get_tetrahedron_count, this );
634   mesh_set_get_tetrahedron_vertices( _tria_mesh, get_tetrahedron_vertices, this );
635
636   // Create a tetra session
637   _session = tetra_session_new( _context );
638   if ( !_session ) MG_Error( "unable to create a new tetra session");
639
640   ret = tetra_set_interrupt_callback( _session, my_interrupt_callback, this );
641   if ( ret != STATUS_OK ) MG_Error("in tetra_set_interrupt_callback");
642
643 }
644
645 bool MG_Tetra_API::LibData::Compute()
646 {
647   status_t ret;
648
649   if ( _tetraNodes.empty() )
650   {
651     // Set surface mesh
652     ret = tetra_set_surface_mesh( _session, _tria_mesh );
653     if ( ret != STATUS_OK ) MG_Error( "unable to set surface mesh");
654   }
655   else
656   {
657     ret = tetra_set_volume_mesh( _session, _tria_mesh );
658     if ( ret != STATUS_OK ) MG_Error( "unable to set volume mesh");
659   }
660
661   // Set a sizemap
662   if ( !_nodeSize.empty() )
663   {
664     _sizemap = meshgems_sizemap_new( _tria_mesh, meshgems_sizemap_type_iso_mesh_vertex,
665                                      (void*) &get_vertex_weight, this );
666     if ( !_sizemap ) MG_Error("unable to create a new sizemap");
667
668     ret = tetra_set_sizemap( _session, _sizemap );
669     if ( ret != STATUS_OK ) MG_Error( "unable to set sizemap");
670   }
671
672   //////////////////////////////////////////////////////////////////////////////////////////
673   // const char* file  =  "/tmp/ghs3d_IN.mesh";
674   // mesh_write_mesh( _tria_mesh,file);
675   // std::cout << std::endl << std::endl << "Write " << file << std::endl << std::endl << std::endl;
676
677   ret = tetra_compute_mesh( _session );
678   if ( ret != STATUS_OK ) return false;
679
680   ret = tetra_get_mesh( _session, &_tetra_mesh);
681   if (ret != STATUS_OK) MG_Error( "unable to get resulting mesh");
682
683   //////////////////////////////////////////////////////////////////////////////////////////
684   // {
685   //   const char* file  =  "/tmp/ghs3d_OUT.mesh";
686   //   mesh_write_mesh( _tetra_mesh,file);
687   //   std::cout << std::endl << std::endl << "Write " << file << std::endl << std::endl << std::endl;
688   // }
689   return true;
690 }
691
692 #else // ifdef USE_MG_LIBS
693
694 struct MG_Tetra_API::LibData // to avoid compiler warnings
695 {
696   volatile bool& _cancelled_flag;
697   double& _progress;
698   LibData(volatile bool& cancelled_flag, double& progress):
699     _cancelled_flag{cancelled_flag}, _progress{progress}
700   {}
701 };
702
703 #endif // ifdef USE_MG_LIBS
704
705
706 //================================================================================
707 /*!
708  * \brief Constructor
709  */
710 //================================================================================
711
712 MG_Tetra_API::MG_Tetra_API(volatile bool& cancelled_flag, double& progress)
713 {
714   _useLib = false;
715   _libData = new LibData( cancelled_flag, progress );
716 #ifdef USE_MG_LIBS
717   _useLib = true;
718   _libData->Init();
719   if ( getenv("MG_TETRA_USE_EXE"))
720     _useLib = false;
721 #endif
722 }
723
724 //================================================================================
725 /*!
726  * \brief Destructor
727  */
728 //================================================================================
729
730 MG_Tetra_API::~MG_Tetra_API()
731 {
732 #ifdef USE_MG_LIBS
733   delete _libData;
734   _libData = 0;
735 #endif
736   std::set<int>::iterator id = _openFiles.begin();
737   for ( ; id != _openFiles.end(); ++id )
738     ::GmfCloseMesh( *id );
739   _openFiles.clear();
740 }
741
742 //================================================================================
743 /*!
744  * \brief Return the way of MG usage
745  */
746 //================================================================================
747
748 bool MG_Tetra_API::IsLibrary()
749 {
750   return _useLib;
751 }
752
753 //================================================================================
754 /*!
755  * \brief Switch to usage of MG-Tetra executable
756  */
757 //================================================================================
758
759 void MG_Tetra_API::SetUseExecutable()
760 {
761   _useLib = false;
762 }
763
764 //================================================================================
765 /*!
766  * \brief Compute the tetra mesh
767  *  \param [in] cmdLine - a command to run mg_tetra.exe
768  *  \return bool - Ok or not
769  */
770 //================================================================================
771
772 bool MG_Tetra_API::Compute( const std::string& cmdLine, std::string& errStr )
773 {
774   if ( _useLib ) {
775 #ifdef USE_MG_LIBS
776
777     // split cmdLine
778     std::istringstream strm( cmdLine );
779     std::istream_iterator<std::string> sIt( strm ), sEnd;
780     std::vector< std::string > args( sIt, sEnd );
781
782     // set parameters
783     std::string param, value;
784     for ( size_t i = 1; i < args.size(); ++i )
785     {
786       // look for a param name; it starts from "-"
787       param = args[i];
788       if ( param.size() < 2 || param[0] != '-')
789         continue;
790       while ( param[0] == '-')
791         param = param.substr( 1 );
792
793       value = "";
794       while ( i+1 < args.size() && args[i+1][0] != '-' )
795       {
796         if ( strncmp( "1>", args[i+1].c_str(), 2 ) == 0 )
797           break;
798         if ( !value.empty() ) value += " ";
799         value += args[++i];
800       }
801       if ( !_libData->SetParam( param, value ))
802         std::cout << "Warning: wrong param: '" << param <<"' = '" << value << "'" << std::endl;
803     }
804
805     // compute
806     bool ok =  _libData->Compute();
807
808     GetLog(); // write a log file
809     _logFile = ""; // not to write it again
810
811     return ok;
812 #endif
813   }
814
815   int err = system( cmdLine.c_str() ); // run
816
817   if ( err )
818     errStr = SMESH_Comment("system(mg-tetra.exe ...) command failed with error: ")
819       << strerror( errno );
820
821   return !err;
822
823 }
824
825 //================================================================================
826 /*!
827  * \brief Prepare for reading a mesh data
828  */
829 //================================================================================
830
831 int  MG_Tetra_API::GmfOpenMesh(const char* theFile, int rdOrWr, int * ver, int * dim)
832 {
833   if ( _useLib ) {
834 #ifdef USE_MG_LIBS
835     return 1;
836 #endif
837   }
838   int id = ::GmfOpenMesh(theFile, rdOrWr, ver, dim );
839   _openFiles.insert( id );
840   return id;
841 }
842
843 //================================================================================
844 /*!
845  * \brief Return nb of entities
846  */
847 //================================================================================
848
849 int MG_Tetra_API::GmfStatKwd( int iMesh, GmfKwdCod what )
850 {
851   if ( _useLib ) {
852 #ifdef USE_MG_LIBS
853     switch ( what )
854     {
855     case GmfSubDomainFromGeom: return _libData->ReadNbSubDomains();
856     case GmfVertices:          return _libData->ReadNbNodes();
857     case GmfEdges:             return _libData->ReadNbEdges();
858     case GmfTriangles:         return _libData->ReadNbTria();
859     case GmfQuadrilaterals:    return _libData->ReadNbQuads();
860     case GmfTetrahedra:        return _libData->ReadNbTetra();
861     case GmfHexahedra:         return _libData->ReadNbHexa();
862     default:                   return 0;
863     }
864     return 0;
865 #endif
866   }
867   return ::GmfStatKwd( iMesh, what );
868 }
869
870 //================================================================================
871 /*!
872  * \brief Prepare for reading some data
873  */
874 //================================================================================
875
876 void MG_Tetra_API::GmfGotoKwd( int iMesh, GmfKwdCod what )
877 {
878   if ( _useLib ) {
879 #ifdef USE_MG_LIBS
880     _libData->ResetCounter();
881     return;
882 #endif
883   }
884   ::GmfGotoKwd( iMesh, what );
885 }
886
887 //================================================================================
888 /*!
889  * \brief Return index of a domain identified by a triangle normal
890  *  \param [in] iMesh - mesh file index
891  *  \param [in] what - must be GmfSubDomainFromGeom
892  *  \param [out] nbNodes - nb nodes in a face
893  *  \param [out] faceInd - face index
894  *  \param [out] ori - face orientation
895  *  \param [out] domain - domain index
896  *  \param [in] dummy - an artificial param used to discriminate from GmfGetLin() reading
897  *              a triangle
898  */
899 //================================================================================
900
901 void MG_Tetra_API::GmfGetLin( int iMesh, GmfKwdCod what, int* nbNodes, int* faceInd, int* ori, int* domain, int /*dummy*/ )
902 {
903   if ( _useLib ) {
904 #ifdef USE_MG_LIBS
905     _libData->ReadSubDomain( nbNodes, faceInd, ori, domain );
906     return;
907 #endif
908   }
909   ::GmfGetLin( iMesh, what, nbNodes, faceInd, ori, domain );
910 }
911
912 //================================================================================
913 /*!
914  * \brief Return coordinates of a next node
915  */
916 //================================================================================
917
918 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
919                              double* x, double* y, double *z, int* domain )
920 {
921   if ( _useLib ) {
922 #ifdef USE_MG_LIBS
923     _libData->ReadNodeXYZ( x, y, z, domain );
924     return;
925 #endif
926   }
927   ::GmfGetLin(iMesh, what, x, y, z, domain );
928 }
929
930 //================================================================================
931 /*!
932  * \brief Return coordinates of a next node
933  */
934 //================================================================================
935
936 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
937                              float* x, float* y, float *z, int* domain )
938 {
939   if ( _useLib ) {
940 #ifdef USE_MG_LIBS
941     double X,Y,Z;
942     _libData->ReadNodeXYZ( &X, &Y, &Z, domain );
943     *x = X;
944     *y = Y;
945     *z = Z;
946     return;
947 #endif
948   }
949   ::GmfGetLin(iMesh, what, x, y, z, domain );
950 }
951
952 //================================================================================
953 /*!
954  * \brief Return node index of a next corner
955  */
956 //================================================================================
957
958 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what, int* node )
959 {
960   if ( _useLib ) {
961 #ifdef USE_MG_LIBS
962     node = 0;
963     return;
964 #endif
965   }
966   ::GmfGetLin(iMesh, what, node );
967 }
968
969 //================================================================================
970 /*!
971  * \brief Return node indices of a next edge
972  */
973 //================================================================================
974
975 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what, int* node1, int* node2, int* domain )
976 {
977   if ( _useLib ) {
978 #ifdef USE_MG_LIBS
979     _libData->ReadEdgeNodes( node1, node2, domain );
980     return;
981 #endif
982   }
983   ::GmfGetLin( iMesh, what, node1, node2, domain );
984 }
985
986 //================================================================================
987 /*!
988  * \brief Return node indices of a next triangle
989  */
990 //================================================================================
991
992 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
993                              int* node1, int* node2, int* node3, int* domain )
994 {
995   if ( _useLib ) {
996 #ifdef USE_MG_LIBS
997     _libData->ReadTriaNodes( node1, node2, node3, domain );
998     return;
999 #endif
1000   }
1001   ::GmfGetLin(iMesh, what, node1, node2, node3, domain );
1002 }
1003
1004 //================================================================================
1005 /*!
1006  * \brief Return node indices of a next tetrahedron or quadrangle
1007  */
1008 //================================================================================
1009
1010 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
1011                              int* node1, int* node2, int* node3, int* node4, int* domain )
1012 {
1013   if ( _useLib ) {
1014 #ifdef USE_MG_LIBS
1015     if ( what == GmfQuadrilaterals )
1016       _libData->ReadQuadNodes( node1, node2, node3, node4, domain );
1017     else
1018       _libData->ReadTetraNodes( node1, node2, node3, node4, domain );
1019     return;
1020 #endif
1021   }
1022   ::GmfGetLin(iMesh, what, node1, node2, node3, node4, domain );
1023 }
1024
1025 //================================================================================
1026 /*!
1027  * \brief Return node indices of a next hexahedron
1028  */
1029 //================================================================================
1030
1031 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
1032                              int* node1, int* node2, int* node3, int* node4,
1033                              int* node5, int* node6, int* node7, int* node8,
1034                              int* domain )
1035 {
1036   if ( _useLib ) {
1037 #ifdef USE_MG_LIBS
1038     _libData->ReadHexaNodes( node1, node2, node3, node4,
1039                              node5, node6, node7, node8, domain );
1040     return;
1041 #endif
1042   }
1043   ::GmfGetLin(iMesh, what, node1, node2, node3, node4, node5, node6, node7, node8, domain );
1044 }
1045
1046 //================================================================================
1047 /*!
1048  * \brief Prepare for passing data to MeshGems
1049  */
1050 //================================================================================
1051
1052 int  MG_Tetra_API::GmfOpenMesh(const char* theFile, int rdOrWr, int ver, int dim)
1053 {
1054   if ( _useLib ) {
1055 #ifdef USE_MG_LIBS
1056     return 1;
1057 #endif
1058   }
1059   int id = ::GmfOpenMesh(theFile, rdOrWr, ver, dim);
1060   _openFiles.insert( id );
1061   return id;
1062 }
1063
1064 //================================================================================
1065 /*!
1066  * \brief Set number of entities
1067  */
1068 //================================================================================
1069
1070 void MG_Tetra_API::GmfSetKwd(int iMesh, GmfKwdCod what, int nb )
1071 {
1072   if ( _useLib ) {
1073 #ifdef USE_MG_LIBS
1074     switch ( what ) {
1075     case GmfVertices:          _libData->SetNbVertices( nb ); break;
1076     case GmfEdges:             _libData->SetNbEdges   ( nb ); break;
1077     case GmfRequiredEdges:     _libData->SetNbReqEdges( nb ); break;
1078     case GmfTriangles:         _libData->SetNbTria    ( nb ); break;
1079     case GmfRequiredTriangles: _libData->SetNbReqTria ( nb ); break;
1080     default:;
1081     }
1082     return;
1083 #endif
1084   }
1085   ::GmfSetKwd(iMesh, what, nb );
1086 }
1087
1088 //================================================================================
1089 /*!
1090  * \brief Add coordinates of a node
1091  */
1092 //================================================================================
1093
1094 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, double x, double y, double z, int domain)
1095 {
1096   if ( _useLib ) {
1097 #ifdef USE_MG_LIBS
1098     _libData->AddNode( x, y, z, domain );
1099     return;
1100 #endif
1101   }
1102   ::GmfSetLin(iMesh, what, x, y, z, domain);
1103 }
1104
1105 //================================================================================
1106 /*!
1107  * \brief Set number of field entities
1108  *  \param [in] iMesh - solution file index
1109  *  \param [in] what - solution type
1110  *  \param [in] nbNodes - nb of entities
1111  *  \param [in] nbTypes - nb of data entries in each entity
1112  *  \param [in] type - types of the data entries
1113  *
1114  * Used to prepare to storing size at nodes
1115  */
1116 //================================================================================
1117
1118 void MG_Tetra_API::GmfSetKwd(int iMesh, GmfKwdCod what, int nbNodes, int dummy, int type[] )
1119 {
1120   if ( _useLib ) {
1121 #ifdef USE_MG_LIBS
1122     if ( what == GmfSolAtVertices ) _libData->SetNbReqVertices( nbNodes );
1123     return;
1124 #endif
1125   }
1126   ::GmfSetKwd(iMesh, what, nbNodes, dummy, type );
1127 }
1128
1129 //================================================================================
1130 /*!
1131  * \brief Add solution data
1132  */
1133 //================================================================================
1134
1135 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, double vals[])
1136 {
1137   if ( _useLib ) {
1138 #ifdef USE_MG_LIBS
1139     _libData->AddSizeAtNode( vals[0] );
1140     return;
1141 #endif
1142   }
1143   ::GmfSetLin(iMesh, what, vals);
1144 }
1145
1146 //================================================================================
1147 /*!
1148  * \brief Add edge nodes
1149  */
1150 //================================================================================
1151
1152 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, int node1, int node2, int domain )
1153 {
1154   if ( _useLib ) {
1155 #ifdef USE_MG_LIBS
1156     _libData->AddEdgeNodes( node1, node2, domain );
1157     return;
1158 #endif
1159   }
1160   ::GmfSetLin(iMesh, what, node1, node2, domain );
1161 }
1162
1163 //================================================================================
1164 /*!
1165  * \brief Add a 'required' flag
1166  */
1167 //================================================================================
1168
1169 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, int id )
1170 {
1171   if ( _useLib ) {
1172 #ifdef USE_MG_LIBS
1173     return;
1174 #endif
1175   }
1176   ::GmfSetLin(iMesh, what, id );
1177 }
1178
1179 //================================================================================
1180 /*!
1181  * \brief Add triangle nodes
1182  */
1183 //================================================================================
1184
1185 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, int node1, int node2, int node3, int domain )
1186 {
1187   if ( _useLib ) {
1188 #ifdef USE_MG_LIBS
1189     _libData->AddTriaNodes( node1, node2, node3, domain );
1190     return;
1191 #endif
1192   }
1193   ::GmfSetLin(iMesh, what, node1, node2, node3, domain );
1194 }
1195
1196 //================================================================================
1197 /*!
1198  * \brief Add tetra nodes
1199  */
1200 //================================================================================
1201
1202 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what,
1203                              int node1, int node2, int node3, int node4, int domain )
1204 {
1205   if ( _useLib ) {
1206 #ifdef USE_MG_LIBS
1207     _libData->AddTetraNodes( node1, node2, node3, node4, domain );
1208     return;
1209 #endif
1210   }
1211   ::GmfSetLin(iMesh, what, node1, node2, node3, node4, domain );
1212 }
1213
1214 //================================================================================
1215 /*!
1216  * \brief Close a file
1217  */
1218 //================================================================================
1219
1220 void MG_Tetra_API::GmfCloseMesh( int iMesh )
1221 {
1222   if ( _useLib ) {
1223 #ifdef USE_MG_LIBS
1224     return;
1225 #endif
1226   }
1227   ::GmfCloseMesh( iMesh );
1228   _openFiles.erase( iMesh );
1229 }
1230
1231 //================================================================================
1232 /*!
1233  * \brief Return true if the log is not empty
1234  */
1235 //================================================================================
1236
1237 bool MG_Tetra_API::HasLog()
1238 {
1239   if ( _useLib ) {
1240 #ifdef USE_MG_LIBS
1241     return !_libData->GetErrors().empty();
1242 #endif
1243   }
1244   SMESH_File file( _logFile );
1245   return file.size() > 0;
1246 }
1247
1248 //================================================================================
1249 /*!
1250  * \brief Return log contents
1251  */
1252 //================================================================================
1253
1254 std::string MG_Tetra_API::GetLog()
1255 {
1256   if ( _useLib ) {
1257 #ifdef USE_MG_LIBS
1258     const std::string& err = _libData->GetErrors();
1259     if ( !_logFile.empty() && !err.empty() )
1260     {
1261       SMESH_File file( _logFile, /*openForReading=*/false );
1262       file.openForWriting();
1263       file.write( err.c_str(), err.size() );
1264     }
1265     return err;
1266 #endif
1267   }
1268   SMESH_File file( _logFile );
1269   return file.getPos();
1270 }