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