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