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