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