Salome HOME
bos #24596 [CEA] New MeshGems license:: fix regressions in tests
[plugins/hexoticplugin.git] / src / HexoticPlugin / HexoticPlugin_Hexotic.cxx
1 // Copyright (C) 2007-2021  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // ---
21 // File   : HexoticPlugin_Hexotic.cxx
22 // Author : Lioka RAZAFINDRAZAKA (CEA)
23 // ---
24 //
25 #include "HexoticPlugin_Hexotic.hxx"
26 #include "HexoticPlugin_Hypothesis.hxx"
27 #include "MG_Hexotic_API.hxx"
28
29 #include "utilities.h"
30
31 #ifdef WIN32
32 #include <process.h>
33 #endif
34
35 #ifdef _DEBUG_
36 #define DUMP(txt) \
37 //  std::cout << txt
38 #else
39 #define DUMP(txt)
40 #endif
41
42 #include <SMESHDS_GroupBase.hxx>
43 #include <SMESHDS_Mesh.hxx>
44 #include <SMESH_ComputeError.hxx>
45 #include <SMESH_File.hxx>
46 #include <SMESH_Gen.hxx>
47 #include <SMESH_HypoFilter.hxx>
48 #include <SMESH_MesherHelper.hxx>
49 #include <SMESH_subMesh.hxx>
50 #include <SMESH_MeshEditor.hxx>
51 #include <SMESH_ControlPnt.hxx>
52
53 #include <list>
54 #include <cstdlib>
55
56 #include <Standard_ProgramError.hxx>
57
58 #include <BRepBndLib.hxx>
59 #include <BRepClass3d_SolidClassifier.hxx>
60 #include <BRep_Tool.hxx>
61 #include <Bnd_Box.hxx>
62 #include <OSD_File.hxx>
63 #include <Precision.hxx>
64 #include <TopExp_Explorer.hxx>
65 #include <TopTools_MapOfShape.hxx>
66 #include <TopoDS.hxx>
67 #include <TopoDS_Vertex.hxx>
68 #include <gp_Pnt.hxx>
69
70 #include <Basics_DirUtils.hxx>
71 #include <Basics_Utils.hxx>
72 #include <GEOMImpl_Types.hxx>
73 #include <GEOM_wrap.hxx>
74
75 #define GMFVERSION GmfDouble
76 #define GMFDIMENSION 3
77
78 using SMESHUtils::ControlPnt;
79
80 static void removeFile( const TCollection_AsciiString& fileName )
81 {
82   try {
83     OSD_File( fileName ).Remove();
84   }
85   catch ( Standard_ProgramError& ) {
86     MESSAGE("Can't remove file: " << fileName.ToCString() << " ; file does not exist or permission denied");
87   }
88 }
89
90 //=============================================================================
91 /*!
92  *  
93  */
94 //=============================================================================
95
96 HexoticPlugin_Hexotic::HexoticPlugin_Hexotic(int hypId, SMESH_Gen* gen)
97   : SMESH_3D_Algo(hypId, gen)
98 {
99   _name = "MG-Hexa";
100   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
101   _onlyUnaryInput = false;
102   _requireShape = false;
103   _iShape=0;
104   _nbShape=0;
105   _hexoticFilesKept=false;
106   _compatibleHypothesis.push_back( HexoticPlugin_Hypothesis::GetHypType() );
107 #ifdef WITH_BLSURFPLUGIN
108   _blsurfHypo = NULL;
109 #endif
110   _computeCanceled = false;
111   
112 }
113
114 //=============================================================================
115 /*!
116  *  
117  */
118 //=============================================================================
119
120 HexoticPlugin_Hexotic::~HexoticPlugin_Hexotic()
121 {
122 }
123
124
125 #ifdef WITH_BLSURFPLUGIN
126 bool HexoticPlugin_Hexotic::CheckBLSURFHypothesis( SMESH_Mesh&         aMesh,
127                                                    const TopoDS_Shape& aShape )
128 {
129   _blsurfHypo = NULL;
130
131   std::list<const SMESHDS_Hypothesis*>::const_iterator itl;
132   const SMESHDS_Hypothesis* theHyp;
133
134   // If a BLSURF hypothesis is applied, get it
135   SMESH_HypoFilter blsurfFilter;
136   blsurfFilter.Init( blsurfFilter.HasName( BLSURFPlugin_Hypothesis::GetHypType(true) ));
137   blsurfFilter.Or  ( blsurfFilter.HasName( BLSURFPlugin_Hypothesis::GetHypType(false)));
138   std::list<const SMESHDS_Hypothesis *> appliedHyps;
139   aMesh.GetHypotheses( aShape, blsurfFilter, appliedHyps, false );
140
141   if ( appliedHyps.size() > 0 ) {
142     itl = appliedHyps.begin();
143     theHyp = (*itl); // use only the first hypothesis
144     std::string hypName = theHyp->GetName();
145     if (hypName == BLSURFPlugin_Hypothesis::GetHypType(true) ||
146         hypName == BLSURFPlugin_Hypothesis::GetHypType(false) )
147     {
148       _blsurfHypo = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
149       ASSERT(_blsurfHypo);
150       return true;
151     }
152   }
153   return false;
154 }
155 #endif
156
157 //=============================================================================
158 /*!
159  *  
160  */
161 //=============================================================================
162
163 bool HexoticPlugin_Hexotic::CheckHypothesis( SMESH_Mesh&                          aMesh,
164                                              const TopoDS_Shape&                  aShape,
165                                              SMESH_Hypothesis::Hypothesis_Status& aStatus )
166 {
167   _hypothesis = NULL;
168
169   std::list<const SMESHDS_Hypothesis*>::const_iterator itl;
170   const SMESHDS_Hypothesis* theHyp;
171
172   const std::list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
173   int nbHyp = hyps.size();
174   if (!nbHyp) {
175     // retrieve BLSURF hypothesis if no hexotic hypothesis has been set
176 #ifdef WITH_BLSURFPLUGIN
177     CheckBLSURFHypothesis(aMesh, aShape);
178 #endif
179     aStatus = SMESH_Hypothesis::HYP_OK;
180     return true;  // can work with no hypothesis
181   }
182
183   itl = hyps.begin();
184   theHyp = (*itl); // use only the first hypothesis
185
186   std::string hypName = theHyp->GetName();
187   if (hypName == HexoticPlugin_Hypothesis::GetHypType() ) {
188     _hypothesis = static_cast<const HexoticPlugin_Hypothesis*> (theHyp);
189     ASSERT(_hypothesis);
190     aStatus = SMESH_Hypothesis::HYP_OK;
191   }
192   else
193     aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
194   
195 #ifdef WITH_BLSURFPLUGIN
196   CheckBLSURFHypothesis(aMesh, aShape);
197 #endif
198   
199   return aStatus == SMESH_Hypothesis::HYP_OK;
200 }
201
202 //=======================================================================
203 //function : findShape
204 //purpose  :
205 //=======================================================================
206
207 static TopoDS_Shape findShape(SMDS_MeshNode**     t_Node,
208                               TopoDS_Shape        aShape,
209                               const TopoDS_Shape* t_Shape,
210                               double**            t_Box,
211                               const int           nShape)
212 {
213   double pntCoor[3];
214   int iShape, nbNode = 8;
215
216   for ( int i=0; i<3; i++ ) {
217     pntCoor[i] = 0;
218     for ( int j=0; j<nbNode; j++ ) {
219       if ( i == 0) pntCoor[i] += t_Node[j]->X();
220       if ( i == 1) pntCoor[i] += t_Node[j]->Y();
221       if ( i == 2) pntCoor[i] += t_Node[j]->Z();
222     }
223     pntCoor[i] /= nbNode;
224   }
225   gp_Pnt aPnt(pntCoor[0], pntCoor[1], pntCoor[2]);
226
227   if ( aShape.IsNull() ) aShape = t_Shape[0];
228   BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
229   if ( !(SC.State() == TopAbs_IN) ) {
230     aShape.Nullify();
231     for (iShape = 0; iShape < nShape && aShape.IsNull(); iShape++) {
232       if ( !( pntCoor[0] < t_Box[iShape][0] || t_Box[iShape][1] < pntCoor[0] ||
233               pntCoor[1] < t_Box[iShape][2] || t_Box[iShape][3] < pntCoor[1] ||
234               pntCoor[2] < t_Box[iShape][4] || t_Box[iShape][5] < pntCoor[2]) ) {
235         BRepClass3d_SolidClassifier SC (t_Shape[iShape], aPnt, Precision::Confusion());
236         if (SC.State() == TopAbs_IN)
237           aShape = t_Shape[iShape];
238       }
239     }
240   }
241   return aShape;
242 }
243
244 //=======================================================================
245 //function : getNbShape
246 //purpose  :
247 //=======================================================================
248
249 static int getNbShape(MG_Hexotic_API* hexaOutput, int iMesh, GmfKwdCod what, int defaultValue=0)
250 {
251   int number = hexaOutput->GmfStatKwd( iMesh, what );
252   if ( number > 0 )
253   {
254     number = ( number + defaultValue + std::abs(number - defaultValue) ) / 2;
255   }
256   else
257   {
258     number = defaultValue;
259   }
260   return number;
261 }
262
263 //=======================================================================
264 //function : countShape
265 //purpose  :
266 //=======================================================================
267
268 static int countShape( SMESH_Mesh* mesh, TopAbs_ShapeEnum shape )
269 {
270   if ( !mesh->HasShapeToMesh() )
271     return 0;
272   TopExp_Explorer expShape ( mesh->GetShapeToMesh(), shape );
273   TopTools_MapOfShape mapShape;
274   int nbShape = 0;
275   for ( ; expShape.More(); expShape.Next() ) {
276     if (mapShape.Add(expShape.Current())) {
277       nbShape++;
278     }
279   }
280   return nbShape;
281 }
282
283 //=======================================================================
284 //function : getShape
285 //purpose  :
286 //=======================================================================
287
288 template < class Mesh, class Shape, class Tab >
289 void getShape(Mesh* mesh, Shape shape, Tab *t_Shape)
290 {
291   TopExp_Explorer expShape ( mesh->ShapeToMesh(), shape );
292   TopTools_MapOfShape mapShape;
293   for ( int i=0; expShape.More(); expShape.Next() ) {
294     if (mapShape.Add(expShape.Current())) {
295       t_Shape[i] = expShape.Current();
296       i++;
297     }
298   }
299   return;
300 }
301
302 //=======================================================================
303 //function : printWarning
304 //purpose  :
305 //=======================================================================
306
307 static void printWarning(const int nbExpected, std::string aString, const int nbFound) {
308   std::cout << std::endl;
309   std::cout << "WARNING : " << nbExpected << " " << aString << " expected, MG-Hexa has found " << nbFound << std::endl;
310   std::cout << "=======" << std::endl;
311   std::cout << std::endl;
312   return;
313 }
314
315 //=======================================================================
316 //function : removeHexoticFiles
317 //purpose  :
318 //=======================================================================
319
320 static void removeHexoticFiles(TCollection_AsciiString file_In, TCollection_AsciiString file_Out)
321 {
322   removeFile( file_In );
323   removeFile( file_Out );
324 }
325
326 //=======================================================================
327 //function : splitQuads
328 //purpose  : splits all quadrangles into triangles
329 //=======================================================================
330
331 static void splitQuads(SMESH_Mesh& aMesh)
332 {
333   SMESH_MeshEditor spliter( &aMesh );
334
335   TIDSortedElemSet elems;
336   SMDS_ElemIteratorPtr eIt = aMesh.GetMeshDS()->elementsIterator();
337   while( eIt->more() )
338     elems.insert( elems.end(), eIt->next() );
339   
340   spliter.QuadToTri ( elems, /*the13Diag=*/true);
341 }
342
343 //=======================================================================
344 //function : writeInput
345 //purpose  : pass a mesh to input of MG-Hexa
346 //=======================================================================
347
348 static void writeInput(MG_Hexotic_API*     theHexaInput,
349                        const char*         theFile,
350                        const SMESHDS_Mesh* theMeshDS)
351 {
352   int meshID = theHexaInput->GmfOpenMesh( theFile, GmfWrite, GMFVERSION, GMFDIMENSION);
353   
354   // nodes
355   int iN = 0;
356   smIdType nbNodes = theMeshDS->NbNodes();
357   theHexaInput->GmfSetKwd( meshID, GmfVertices, nbNodes );
358   std::map< const SMDS_MeshNode*, int, TIDCompare > node2IdMap;
359   SMDS_NodeIteratorPtr nodeIt = theMeshDS->nodesIterator();
360   SMESH_TNodeXYZ n;
361   while ( nodeIt->more() )
362   {
363     n.Set( nodeIt->next() );
364     theHexaInput->GmfSetLin( meshID, GmfVertices, n.X(), n.Y(), n.Z(), n._node->getshapeId() );
365     node2IdMap.insert( node2IdMap.end(), std::make_pair( n._node, ++iN ));
366   }
367
368   // edges
369   SMDS_ElemIteratorPtr elemIt = theMeshDS->elementsIterator( SMDSAbs_Edge );
370   if ( elemIt->more() )
371   {
372     smIdType nbEdges = theMeshDS->GetMeshInfo().NbElements( SMDSAbs_Edge );
373     theHexaInput->GmfSetKwd(meshID, GmfEdges, nbEdges );
374     for ( int gmfID = 1; elemIt->more(); ++gmfID )
375     {
376       const SMDS_MeshElement* edge = elemIt->next();
377       theHexaInput->GmfSetLin(meshID, GmfEdges, 
378                               node2IdMap[ edge->GetNode( 0 )],
379                               node2IdMap[ edge->GetNode( 1 )],
380                               edge->getshapeId() );
381     }
382   }
383
384   // triangles
385   elemIt = theMeshDS->elementGeomIterator( SMDSGeom_TRIANGLE );
386   if ( elemIt->more() )
387   {
388     smIdType nbTria = theMeshDS->GetMeshInfo().NbElements( SMDSGeom_TRIANGLE );
389     theHexaInput->GmfSetKwd(meshID, GmfTriangles, nbTria );
390     for ( int gmfID = 1; elemIt->more(); ++gmfID )
391     {
392       const SMDS_MeshElement* tria = elemIt->next();
393       theHexaInput->GmfSetLin(meshID, GmfTriangles, 
394                               node2IdMap[ tria->GetNode( 0 )],
395                               node2IdMap[ tria->GetNode( 1 )],
396                               node2IdMap[ tria->GetNode( 2 )],
397                               tria->getshapeId() );
398     }
399   }
400   theHexaInput->GmfCloseMesh( meshID );
401 }
402
403 //=======================================================================
404 //function : readResult
405 //purpose  : Read GMF file in case of a mesh with geometry
406 //=======================================================================
407
408 static bool readResult(MG_Hexotic_API*       theHexaOutput,
409                        const char*           theFile,
410                        HexoticPlugin_Hexotic*theAlgo,
411                        SMESH_MesherHelper*   theHelper,
412                        const int             nbShape = 0,
413                        const TopoDS_Shape*   tabShape = 0,
414                        double**              tabBox = 0)
415 {
416   SMESH_Mesh*     theMesh = theHelper->GetMesh();
417   SMESHDS_Mesh* theMeshDS = theHelper->GetMeshDS();
418
419   // ---------------------------------
420   // Read generated elements and nodes
421   // ---------------------------------
422
423   TopoDS_Shape aShape;
424   TopoDS_Vertex aVertex;
425   std::string token;
426   int shapeID, hexoticShapeID;
427   const int IdShapeRef = 2;
428   std::vector< int > tabID;
429   double epsilon = Precision::Confusion();
430   std::map <std::string,int> mapField;
431   std::vector< SMDS_MeshNode*> HexoticNode;
432   std::vector< TopoDS_Shape > tabCorner;
433
434   const int nbDomains = countShape( theMesh, TopAbs_SHELL );
435   const int holeID = -1;
436
437   if ( nbDomains > 0 )
438   {
439     tabID.resize( nbDomains, 0 );
440     if ( nbDomains == 1 )
441       tabID[0] = theMeshDS->ShapeToIndex( tabShape[0] );
442   }
443   else
444   {
445     tabID.resize( 1, 1 );
446   }
447
448   SMDS_ElemIteratorPtr eIt = theMeshDS->elementsIterator();
449   while( eIt->more() )
450     theMeshDS->RemoveFreeElement( eIt->next(), /*sm=*/0 );
451   SMDS_NodeIteratorPtr nIt = theMeshDS->nodesIterator();
452   while ( nIt->more() )
453     theMeshDS->RemoveFreeNode( nIt->next(), /*sm=*/0 );
454
455   theHelper->SetElementsOnShape( false );
456
457   int ver, dim;
458   int meshID = theHexaOutput->GmfOpenMesh( theFile, GmfRead, &ver, &dim );
459
460   int nbVerticesInShape = countShape( theMesh, TopAbs_VERTEX );
461   int nbVertices  = getNbShape(theHexaOutput, meshID, GmfVertices );
462   int nbCorners   = getNbShape(theHexaOutput, meshID, GmfCorners, nbVerticesInShape);
463   if ( nbVertices == 0 )
464     return false;
465
466   tabCorner.resize( nbCorners );
467   HexoticNode.resize( nbVertices + 1 );
468
469   // get the shape vertices if the mesh lies on a shape (and this shape has corners)
470   if ( nbCorners > 0 && nbVerticesInShape > 0 )
471     getShape( theMeshDS, TopAbs_VERTEX, tabCorner.data() );
472
473   int nbNodes = theHexaOutput->GmfStatKwd( meshID, GmfVertices );
474   if ( nbNodes > 0 )
475   {
476     theHexaOutput->GmfGotoKwd( meshID, GmfVertices );
477     double x,y,z;
478     for ( int aHexoticID = 1; aHexoticID <= nbNodes; ++aHexoticID )
479     {
480       if ( theAlgo->computeCanceled() )
481         return false;
482       theHexaOutput->GmfGetLin( meshID, GmfVertices, &x, &y, &z, &shapeID );
483       HexoticNode[ aHexoticID ] = theHelper->AddNode( x,y,z );
484     }
485   }
486
487   int nodeID[8];
488   SMDS_MeshNode* node[8];
489   SMDS_MeshElement * aHexoticElement;
490
491   nbCorners = theHexaOutput->GmfStatKwd( meshID, GmfCorners );
492   if ( nbCorners > 0 && nbDomains > 0 )
493   {
494     theHexaOutput->GmfGotoKwd( meshID, GmfCorners );
495     for ( int iElem = 0; iElem < nbCorners; iElem++ )
496     {
497       if ( theAlgo->computeCanceled() )
498         return false;
499       theHexaOutput->GmfGetLin( meshID, GmfCorners, &nodeID[0] );
500       node[0] = HexoticNode[ nodeID[0] ];
501       gp_Pnt HexoticPnt ( node[0]->X(), node[0]->Y(), node[0]->Z() );
502       for ( int i = 0; i < nbCorners; i++ )
503       {
504         aVertex = TopoDS::Vertex( tabCorner[i] );
505         gp_Pnt aPnt = BRep_Tool::Pnt( aVertex );
506         if ( aPnt.Distance( HexoticPnt ) < epsilon )
507         {
508           theMeshDS->SetNodeOnVertex( node[0], aVertex );
509           break;
510         }
511       }
512     }
513   }
514
515   int nbEdges = theHexaOutput->GmfStatKwd( meshID, GmfEdges );
516   if ( nbEdges > 0 )
517   {
518     theHexaOutput->GmfGotoKwd( meshID, GmfEdges );
519     for ( int iElem = 0; iElem < nbEdges; iElem++ )
520     {
521       if ( theAlgo->computeCanceled() )
522         return false;
523       theHexaOutput->GmfGetLin( meshID, GmfEdges, &nodeID[0], &nodeID[1], &shapeID );
524       for ( int i = 0; i < 2; ++i )
525       {
526         node[i] = HexoticNode[ nodeID[i]];
527         if ( shapeID > 0 && node[i]->getshapeId() < 1 )
528           theMeshDS->SetNodeOnEdge( node[i], shapeID );
529       }
530       aHexoticElement = theHelper->AddEdge( node[0], node[1] );
531       if ( shapeID > 0 && aHexoticElement->getshapeId() < 1 )
532         theMeshDS->SetMeshElementOnShape( aHexoticElement, shapeID );
533     }
534   }
535
536   int nbQuad = theHexaOutput->GmfStatKwd( meshID, GmfQuadrilaterals );
537   if ( nbQuad > 0 )
538   {
539     theHexaOutput->GmfGotoKwd( meshID, GmfQuadrilaterals );
540     for ( int iElem = 0; iElem < nbQuad; iElem++ )
541     {
542       if ( theAlgo->computeCanceled() )
543         return false;
544       theHexaOutput->GmfGetLin( meshID, GmfQuadrilaterals,
545                                 &nodeID[0], &nodeID[1], &nodeID[2], &nodeID[3], &shapeID );
546       for ( int i = 0; i < 4; ++i )
547       {
548         node[i] = HexoticNode[ nodeID[i]];
549         if ( shapeID > 0 && node[i]->getshapeId() < 1 )
550           theMeshDS->SetNodeOnFace( node[i], shapeID );
551       }
552       aHexoticElement = theHelper->AddFace( node[0], node[1], node[2], node[3] );
553       if ( shapeID > 0 && aHexoticElement->getshapeId() < 1 )
554         theMeshDS->SetMeshElementOnShape( aHexoticElement, shapeID );
555     }
556   }
557
558   int nbHexa = theHexaOutput->GmfStatKwd( meshID, GmfHexahedra );
559   if ( nbHexa > 0 )
560   {
561     theHexaOutput->GmfGotoKwd( meshID, GmfHexahedra );
562     for ( int iElem = 0; iElem < nbHexa; iElem++ )
563     {
564       if ( theAlgo->computeCanceled() )
565         return false;
566       theHexaOutput->GmfGetLin( meshID, GmfHexahedra,
567                                 &nodeID[0], &nodeID[1], &nodeID[2], &nodeID[3],
568                                 &nodeID[4], &nodeID[5], &nodeID[6], &nodeID[7],
569                                 &shapeID );
570       for ( int i = 0; i < 8; ++i )
571       {
572         node[i] = HexoticNode[ nodeID[i]];
573       }
574       if ( nbDomains > 1 ) {
575         hexoticShapeID = shapeID - IdShapeRef;
576         if ( tabID[ hexoticShapeID ] == 0 ) {
577           aShape = findShape(node, aShape, tabShape, tabBox, nbShape);
578           shapeID = aShape.IsNull() ? holeID : theMeshDS->ShapeToIndex( aShape );
579           tabID[ hexoticShapeID ] = shapeID;
580         }
581         else {
582           shapeID = tabID[ hexoticShapeID ];
583         }
584         if ( iElem == ( nbHexa - 1) ) {
585           int shapeAssociated = 0;
586           for ( int i=0; i<nbDomains; i++ ) {
587             if (tabID[i] > 0 )
588               shapeAssociated += 1;
589           }
590           if ( shapeAssociated != nbShape )
591             printWarning(nbShape, "domains", shapeAssociated);
592         }
593       }
594       else {
595         shapeID = tabID[0];
596       }
597
598       if ( shapeID != holeID )
599       {
600         for ( int i = 0; i < 8; ++i )
601         {
602           if ( node[i]->NbInverseElements( SMDSAbs_Face ) == 0 )
603             theMeshDS->SetNodeInVolume( node[i], shapeID );
604         }
605         aHexoticElement = theHelper->AddVolume( node[0], node[3], node[2], node[1],
606                                                 node[4], node[7], node[6], node[5]);
607         if ( aHexoticElement->getshapeId() < 1 )
608           theMeshDS->SetMeshElementOnShape( aHexoticElement, shapeID );
609       }
610     }
611   }
612   std::cout << std::endl;
613
614   // remove nodes in holes
615   if ( nbDomains > 1 )
616   {
617     SMESHDS_SubMesh* subMesh = 0;
618     for ( int i = 1; i <= nbNodes; ++i )
619       if ( HexoticNode[i]->NbInverseElements() == 0 )
620       {
621         theMeshDS->RemoveFreeNode( HexoticNode[i], subMesh, /*fromGroups=*/false );
622       }
623   }
624
625   // avoid "Error: No mesh on sub-shape"
626   if ( theMesh->NbVolumes() > 0 )
627   {
628     SMESH_subMesh*         smMain = theMesh->GetSubMesh( theMesh->GetShapeToMesh() );
629     SMESH_subMeshIteratorPtr smIt = smMain->getDependsOnIterator( /*includeSelf=*/true );
630     while ( smIt->more() )
631     {
632       SMESH_subMesh* sm = smIt->next();
633       if ( !sm->IsMeshComputed() )
634         sm->SetIsAlwaysComputed( true );
635     }
636   }
637
638   return true;
639 }
640
641 //=============================================================================
642 /*!
643  * Pass parameters to MG-Hexa
644  */
645 //=============================================================================
646
647 void HexoticPlugin_Hexotic::SetParameters(const HexoticPlugin_Hypothesis* hyp)
648 {
649   if (hyp) {
650     _hexesMinLevel = hyp->GetHexesMinLevel();
651     _hexesMaxLevel = hyp->GetHexesMaxLevel();
652     _hexesMinSize = hyp->GetMinSize();
653     _hexesMaxSize = hyp->GetMaxSize();
654     _approxAngle = hyp->GetGeomApproxAngle();
655     _hexoticIgnoreRidges = hyp->GetHexoticIgnoreRidges();
656     _hexoticInvalidElements = hyp->GetHexoticInvalidElements();
657     _hexoticSharpAngleThreshold = hyp->GetHexoticSharpAngleThreshold();
658     _hexoticNbProc = hyp->GetHexoticNbProc();
659     _hexoticWorkingDirectory = hyp->GetHexoticWorkingDirectory();
660     _hexoticVerbosity = hyp->GetHexoticVerbosity();
661     _hexoticMaxMemory = hyp->GetHexoticMaxMemory();
662     _hexoticSdMode = hyp->GetHexoticSdMode();
663     _textOptions = hyp->GetAdvancedOption();
664     _sizeMaps = hyp->GetSizeMaps();
665     _nbLayers = hyp->GetNbLayers();
666     _firstLayerSize = hyp->GetFirstLayerSize();
667     _direction = hyp->GetDirection();
668     _growth = hyp->GetGrowth();
669     _facesWithLayers = hyp->GetFacesWithLayers();
670     _imprintedFaces = hyp->GetImprintedFaces();
671     _keepFiles = hyp->GetKeepFiles();
672     _removeLogOnSuccess = hyp->GetRemoveLogOnSuccess();
673     _logInStandardOutput = hyp->GetStandardOutputLog();
674   }
675   else {
676     std::cout << std::endl;
677     std::cout << "WARNING : The MG-Hexa default parameters are taken into account" << std::endl;
678     std::cout << "=======" << std::endl;
679     _hexesMinLevel = hyp->GetDefaultHexesMinLevel();
680     _hexesMaxLevel = hyp->GetDefaultHexesMaxLevel();
681     _hexesMinSize = hyp->GetDefaultMinSize();
682     _hexesMaxSize = hyp->GetDefaultMaxSize();
683     _approxAngle = hyp->GetDefaultGeomApproxAngle();
684     _hexoticIgnoreRidges = hyp->GetDefaultHexoticIgnoreRidges();
685     _hexoticInvalidElements = hyp->GetDefaultHexoticInvalidElements();
686     _hexoticSharpAngleThreshold = hyp->GetDefaultHexoticSharpAngleThreshold();
687     _hexoticNbProc = hyp->GetDefaultHexoticNbProc();
688     _hexoticWorkingDirectory = hyp->GetDefaultHexoticWorkingDirectory();
689     _hexoticVerbosity = hyp->GetDefaultHexoticVerbosity();
690     _hexoticMaxMemory = hyp->GetDefaultHexoticMaxMemory();
691     _hexoticSdMode = hyp->GetDefaultHexoticSdMode();
692     _textOptions = hyp->GetDefaultTextOptions();
693     _sizeMaps = hyp->GetDefaultHexoticSizeMaps();
694     _nbLayers = hyp->GetDefaultNbLayers();
695     _firstLayerSize = hyp->GetDefaultFirstLayerSize();
696     _direction = hyp->GetDefaultDirection();
697     _growth = hyp->GetDefaultGrowth();
698     _facesWithLayers = hyp->GetDefaultFacesWithLayers();
699     _imprintedFaces = hyp->GetDefaultImprintedFaces();
700     _keepFiles = hyp->GetDefaultKeepFiles();
701     _removeLogOnSuccess = hyp->GetDefaultRemoveLogOnSuccess();
702     _logInStandardOutput = hyp->GetDefaultStandardOutputLog();
703   }
704 }
705
706 //=======================================================================
707 //function : getSuffix
708 //purpose  : Returns a suffix that will be unique for the current process
709 //=======================================================================
710
711 static TCollection_AsciiString getSuffix()
712 {
713   TCollection_AsciiString aSuffix = "";
714   aSuffix += "_";
715 #ifndef WIN32
716   aSuffix += getenv("USER");
717 #else
718   std::string uname = std::string(getenv("USERNAME"));
719   replace(uname.begin(), uname.end(), ' ', '_');
720   aSuffix += uname.c_str();
721 #endif
722   aSuffix += "_";
723   aSuffix += Kernel_Utils::GetHostname().c_str();
724   aSuffix += "_";
725 #ifndef WIN32
726   aSuffix += getpid();
727 #else
728   aSuffix += _getpid();
729 #endif
730
731   return aSuffix;
732 }
733
734 //================================================================================
735 /*!
736  * \brief Returns a command to run MG-Hexa mesher
737  */
738 //================================================================================
739
740 std::string
741 HexoticPlugin_Hexotic::getHexoticCommand(const TCollection_AsciiString& Hexotic_In,
742                                          const TCollection_AsciiString& Hexotic_Out,
743                                          const TCollection_AsciiString& Hexotic_SizeMap_Prefix,
744                                          const bool                     forExecutable) const
745 {
746   std::cout << std::endl;
747   std::cout << "MG-Hexa execution..." << std::endl;
748   std::cout << _name << " parameters :" << std::endl;
749   std::cout << "    " << _name << " Verbosity = " << _hexoticVerbosity << std::endl;
750   std::cout << "    " << _name << " Max Memory = " << _hexoticMaxMemory << std::endl;
751   std::cout << "    " << _name << " Segments Min Level = " << _hexesMinLevel << std::endl;
752   std::cout << "    " << _name << " Segments Max Level = " << _hexesMaxLevel << std::endl;
753   std::cout << "    " << _name << " Segments Min Size = " << _hexesMinSize << std::endl;
754   std::cout << "    " << _name << " Segments Max Size = " << _hexesMaxSize << std::endl;
755   std::cout << "    " << "MG-Hexa can ignore ridges : " << (_hexoticIgnoreRidges ? "yes":"no") << std::endl;
756   std::cout << "    " << "MG-Hexa authorize invalide elements : " << ( _hexoticInvalidElements ? "yes":"no") << std::endl;
757   std::cout << "    " << _name << " Sharp angle threshold = " << _hexoticSharpAngleThreshold << " degrees" << std::endl;
758   std::cout << "    " << _name << " Number of threads = " << _hexoticNbProc << std::endl;
759   std::cout << "    " << _name << " Working directory = \"" << _hexoticWorkingDirectory << "\"" << std::endl;
760   std::cout << "    " << _name << " Sub. Dom mode = " << _hexoticSdMode << std::endl;
761   std::cout << "    " << _name << " Text options = \"" << _textOptions << "\"" << std::endl;
762   std::cout << "    " << _name << " Number of layers = " << _nbLayers << std::endl;
763   std::cout << "    " << _name << " Size of the first layer  = " << _firstLayerSize << std::endl;
764   std::cout << "    " << _name << " Direction of the layers = " << ( _direction ? "Inward" : "Outward" ) << std::endl;
765   std::cout << "    " << _name << " Growth = " << _growth << std::endl;
766   if (!_facesWithLayers.empty()) {
767     std::cout << "    " << _name << " Faces with layers = ";
768     for (size_t i = 0; i < _facesWithLayers.size(); i++)
769     {
770       std::cout << _facesWithLayers.at(i);
771       if ((i + 1) != _facesWithLayers.size())
772         std::cout << ", ";
773     }
774     std::cout << std::endl;
775   }
776   if (!_imprintedFaces.empty()) {
777     std::cout << "    " << _name << " Imprinted faces = ";
778     for (size_t i = 0; i < _imprintedFaces.size(); i++)
779     {
780       std::cout << _imprintedFaces.at(i);
781       if ((i + 1) != _imprintedFaces.size())
782         std::cout << ", ";
783     }
784     std::cout << std::endl;
785   }
786
787   TCollection_AsciiString run_Hexotic("mg-hexa.exe");
788
789   TCollection_AsciiString minl         = " --min_level ", maxl = " --max_level ", angle = " --ridge_angle ";
790   TCollection_AsciiString mins         = " --min_size ", maxs = " --max_size ";
791   TCollection_AsciiString in           = " --in ",   out  = " --out ";
792   TCollection_AsciiString sizeMap      = " --sizemap ";
793   TCollection_AsciiString ignoreRidges = " --compute_ridges no ", invalideElements = " --allow_invalid_elements yes ";
794   TCollection_AsciiString subdom       = " --components ";
795 #ifndef WIN32
796   TCollection_AsciiString proc         = " --max_number_of_threads ";
797 #endif
798   TCollection_AsciiString verb         = " --verbose ";
799   TCollection_AsciiString maxmem       = " --max_memory ";
800
801   TCollection_AsciiString comNbLayers        = " --number_of_boundary_layers ";
802   TCollection_AsciiString comFirstLayerSize  = " --height_of_the_first_layer ";
803   TCollection_AsciiString comDirection       = " --boundary_layers_subdomain_direction ";
804   TCollection_AsciiString comGrowth          = " --boundary_layers_geometric_progression ";
805   TCollection_AsciiString comFacesWithLayers = " --boundary_layers_surface_ids ";
806   TCollection_AsciiString comImptintedFaces  = " --imprinted_surface_ids ";
807
808   TCollection_AsciiString minLevel, maxLevel, minSize, maxSize, sharpAngle, mode, nbproc, verbosity, maxMemory,
809                           textOptions, nbLayers, firstLayerSize, direction, growth, facesWithLayers, imprintedFaces;
810   minLevel   = _hexesMinLevel;
811   maxLevel   = _hexesMaxLevel;
812   minSize    = _hexesMinSize;
813   maxSize    = _hexesMaxSize;
814   sharpAngle = _hexoticSharpAngleThreshold;
815   // Mode translation for mg-tetra 1.1
816   switch ( _hexoticSdMode )
817   {
818     case 1:
819       mode = "outside_skin_only";
820       break;
821     case 2:
822       mode = "outside_components";
823       break;
824     case 3:
825       mode = "all";
826       break;
827     case 4:
828       mode = "all --manifold_geometry no";
829       break;
830   }
831   nbproc         = _hexoticNbProc;
832   verbosity      = _hexoticVerbosity;
833   maxMemory      = _hexoticMaxMemory;
834   textOptions    = (" " + _textOptions + " ").c_str();
835   nbLayers       = _nbLayers;
836   firstLayerSize = _firstLayerSize;
837   direction      = _direction ? "1" : "-1";
838   growth         = _growth;
839   for (size_t i = 0; i < _facesWithLayers.size(); i++)
840   {
841     facesWithLayers += _facesWithLayers[i];
842     if ((i + 1) != _facesWithLayers.size())
843       facesWithLayers += ",";
844   }
845   for (size_t i = 0; i < _imprintedFaces.size(); i++)
846   {
847     imprintedFaces += _imprintedFaces[i];
848     if ((i + 1) != _imprintedFaces.size())
849       imprintedFaces += ",";
850   }
851
852   if (_hexoticIgnoreRidges)
853     run_Hexotic +=  ignoreRidges;
854
855   if (_hexoticInvalidElements)
856     run_Hexotic +=  invalideElements;
857
858   if (_hexesMinSize > 0)
859     run_Hexotic +=  mins + minSize;
860
861   if (_hexesMaxSize > 0)
862     run_Hexotic +=  maxs + maxSize;
863
864   if (_hexesMinLevel > 0)
865     run_Hexotic +=  minl + minLevel;
866
867   if (_hexesMaxLevel > 0)
868     run_Hexotic +=  maxl + maxLevel;
869
870   if (_hexoticSharpAngleThreshold > 0)
871     run_Hexotic +=  angle + sharpAngle;
872   
873   if (_sizeMaps.begin() != _sizeMaps.end() && forExecutable )
874     run_Hexotic += sizeMap + Hexotic_SizeMap_Prefix + ".sol";
875
876   if (_nbLayers       > 0 &&
877       _firstLayerSize > 0 &&
878       _growth         > 0 &&
879       !_facesWithLayers.empty())
880   {
881     run_Hexotic += comNbLayers + nbLayers;
882     run_Hexotic += comFirstLayerSize + firstLayerSize;
883     run_Hexotic += comDirection + direction;
884     run_Hexotic += comGrowth + growth;
885     run_Hexotic += comFacesWithLayers + facesWithLayers;
886     if (!_imprintedFaces.empty())
887       run_Hexotic += comImptintedFaces + imprintedFaces;
888   }
889   if ( forExecutable )
890     run_Hexotic += in + Hexotic_In + out + Hexotic_Out;
891   run_Hexotic += subdom + mode;
892 #ifndef WIN32
893   run_Hexotic += proc + nbproc;
894 #endif
895   run_Hexotic += verb + verbosity;
896   run_Hexotic += maxmem + maxMemory;
897
898   if (!_textOptions.empty())
899     run_Hexotic += textOptions;
900
901   return run_Hexotic.ToCString();
902 }
903
904 // TODO : this is a duplication of some code found in BLSURFPlugin_BLSURF find a proper
905 // way to share it
906 TopoDS_Shape HexoticPlugin_Hexotic::entryToShape(std::string entry)
907 {
908   GEOM::GEOM_Object_var aGeomObj;
909   TopoDS_Shape S = TopoDS_Shape();
910   SALOMEDS::SObject_var aSObj = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( entry.c_str() );
911   if (!aSObj->_is_nil()) {
912     CORBA::Object_var obj = aSObj->GetObject();
913     aGeomObj = GEOM::GEOM_Object::_narrow(obj);
914     aSObj->UnRegister();
915   }
916   if ( !aGeomObj->_is_nil() )
917     S = SMESH_Gen_i::GetSMESHGen()->GeomObjectToShape( aGeomObj.in() );
918   return S;
919 }
920
921 //================================================================================
922 /*!
923  * \brief Produces a .mesh file with the size maps informations to give to Hexotic
924  */
925 //================================================================================
926
927 std::vector<std::string> HexoticPlugin_Hexotic::writeSizeMapFile( MG_Hexotic_API* mgInput,
928                                                                   std::string     sizeMapPrefix )
929 {
930   HexoticPlugin_Hypothesis::THexoticSizeMaps::iterator it;
931
932   std::vector<ControlPnt> points;
933   // Iterate on the size maps
934   for (it=_sizeMaps.begin(); it!=_sizeMaps.end(); it++)
935   {
936     // Step 1 : Get the GEOM object entry and the size 
937     // from the _sizeMaps infos
938     std::string anEntry = it->first;
939     double aLocalSize = it->second;
940     TopoDS_Shape aShape = entryToShape( anEntry );
941     
942     // Step 2 : Create the points
943     createControlPoints( aShape, aLocalSize, points );
944   }
945
946   // Write the .mesh size map file
947
948   std::string myVerticesFile = sizeMapPrefix + ".mesh";
949   std::string      mySolFile = sizeMapPrefix + ".sol";
950   
951   // Open files
952   int verticesFileID =
953     mgInput->GmfOpenMesh( myVerticesFile.c_str(), GmfWrite, GMFVERSION, GMFDIMENSION );  
954   int solFileID =
955     mgInput->GmfOpenMesh( mySolFile.c_str(), GmfWrite, GMFVERSION, GMFDIMENSION );
956   
957   int pointsNumber = points.size();
958   
959   // Vertices Keyword
960   mgInput->GmfSetKwd( verticesFileID, GmfVertices, pointsNumber );
961   // SolAtVertices Keyword
962   int TypTab[] = {GmfSca};
963   mgInput->GmfSetKwd(solFileID, GmfSolAtVertices, pointsNumber, 1, TypTab);
964   
965   // Read the control points information from the vector and write it into the files
966   double ValTab[1];
967   std::vector<ControlPnt>::const_iterator points_it;
968   for (points_it = points.begin(); points_it != points.end(); points_it++ )
969   {
970     mgInput->GmfSetLin( verticesFileID, GmfVertices, points_it->X(), points_it->Y(), points_it->Z(), 0 );
971     ValTab[0] = points_it->Size();
972     mgInput->GmfSetLin( solFileID, GmfSolAtVertices, ValTab);
973   }
974
975   // Close Files
976   mgInput->GmfCloseMesh( verticesFileID );
977   mgInput->GmfCloseMesh( solFileID );
978
979   std::vector<std::string> fileNames(2);
980   fileNames[0] = myVerticesFile;
981   fileNames[1] = mySolFile;
982
983   return fileNames;
984 }
985
986 //=============================================================================
987 /*!
988  * Here we are going to use the MG-Hexa mesher
989  */
990 //=============================================================================
991
992 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh&          aMesh,
993                                     const TopoDS_Shape& /*aShape*/)
994 {
995   _computeCanceled = false;
996   bool Ok = true;
997   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
998   TCollection_AsciiString hexahedraMessage;
999
1000   _nbShape = countShape( &aMesh, TopAbs_SOLID );  // we count the number of shapes
1001
1002   {
1003     // create bounding box for each shape of the compound
1004
1005     int iShape = 0;
1006     TopoDS_Shape *tabShape;
1007     double **tabBox;
1008
1009     tabShape = new TopoDS_Shape[_nbShape];
1010     tabBox   = new double*[_nbShape];
1011     for (int i=0; i<_nbShape; i++)
1012       tabBox[i] = new double[6];
1013     double Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
1014
1015     TopExp_Explorer expBox (meshDS->ShapeToMesh(), TopAbs_SOLID);
1016     for (; expBox.More(); expBox.Next()) {
1017       tabShape[iShape] = expBox.Current();
1018       Bnd_Box BoundingBox;
1019       BRepBndLib::Add(expBox.Current(), BoundingBox);
1020       BoundingBox.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
1021       tabBox[iShape][0] = Xmin; tabBox[iShape][1] = Xmax;
1022       tabBox[iShape][2] = Ymin; tabBox[iShape][3] = Ymax;
1023       tabBox[iShape][4] = Zmin; tabBox[iShape][5] = Zmax;
1024       iShape++;
1025     }
1026
1027     SetParameters(_hypothesis);
1028
1029     TCollection_AsciiString aTmpDir = Kernel_Utils::GetTmpDirByPath(_hexoticWorkingDirectory).c_str();
1030     TCollection_AsciiString aQuote("");
1031 #ifdef WIN32
1032     aQuote = "\"";
1033     if ( aTmpDir.Value(aTmpDir.Length()) != '\\' ) aTmpDir += '\\';
1034 #else
1035     if ( aTmpDir.Value(aTmpDir.Length()) != '/' ) aTmpDir += '/';
1036 #endif
1037     TCollection_AsciiString Hexotic_In(""), Hexotic_Out, Hexotic_SizeMap_Prefix;
1038     TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );
1039     TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log";    // log
1040
1041     std::map <int,int> aSmdsToHexoticIdMap;
1042     std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
1043
1044     MG_Hexotic_API mgHexa( _computeCanceled, _progress );
1045
1046     Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
1047 #ifdef WITH_BLSURFPLUGIN
1048     bool defaultInputFile = true;
1049     if (_blsurfHypo && _blsurfHypo->GetElementType() == BLSURFPlugin_Hypothesis::Triangles ) {
1050       Hexotic_In = _blsurfHypo->GetGMFFile().c_str();
1051       if ( !Hexotic_In.IsEmpty() &&
1052            SMESH_File( _blsurfHypo->GetGMFFile() ).exists() )
1053       {
1054         MESSAGE("Use output file from blsurf as input file from hexotic: " << Hexotic_In);
1055         mgHexa.SetUseExecutable();
1056         mgHexa.SetInputFile( _blsurfHypo->GetGMFFile() );
1057         defaultInputFile = false;
1058       }
1059     }
1060     if (defaultInputFile) {
1061 #endif
1062       Hexotic_In  = aTmpDir + "Hexotic"+getSuffix()+"_In.mesh";
1063       removeHexoticFiles(Hexotic_In, Hexotic_Out);
1064       splitQuads(aMesh); // quadrangles are no longer acceptable as input
1065       if ( mgHexa.IsExecutable() )
1066       {
1067         std::cout << std::endl;
1068         std::cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
1069       }
1070       writeInput( &mgHexa, Hexotic_In.ToCString(), meshDS );
1071 #ifdef WITH_BLSURFPLUGIN
1072     }
1073     else {
1074       removeFile( Hexotic_Out );
1075     }
1076 #endif
1077     
1078     Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap" + getSuffix();
1079     std::vector<std::string> sizeMapFiles = writeSizeMapFile( &mgHexa, Hexotic_SizeMap_Prefix.ToCString() );
1080     
1081     std::string run_Hexotic = getHexoticCommand(aQuote + Hexotic_In + aQuote, aQuote + Hexotic_Out + aQuote, Hexotic_SizeMap_Prefix, mgHexa.IsExecutable() );
1082     run_Hexotic += std::string(" 1> ") + aQuote.ToCString() + aLogFileName.ToCString() + aQuote.ToCString();  // dump into file
1083     mgHexa.SetLogFile( aLogFileName.ToCString() );
1084     std::cout << "Creating MG-Hexa log file : " << aLogFileName << std::endl;
1085
1086     std::cout << std::endl;
1087     std::cout << "MG-Hexa command : " << run_Hexotic << std::endl;
1088
1089     if ( mgHexa.IsExecutable() )
1090     {
1091 #ifndef WIN32    
1092       modeFile_In += Hexotic_In;
1093       system( modeFile_In.ToCString() );
1094 #endif
1095     }
1096     aSmdsToHexoticIdMap.clear();
1097     aHexoticIdToNodeMap.clear();
1098
1099     MESSAGE("HexoticPlugin_Hexotic::Compute");
1100
1101     
1102     std::string errStr;
1103     Ok = mgHexa.Compute( run_Hexotic, errStr ); // run
1104
1105
1106     // --------------
1107     // read a result
1108     // --------------
1109
1110     if ( mgHexa.IsExecutable() && SMESH_File( Hexotic_Out.ToCString() ).exists() )
1111     {
1112 #ifndef WIN32
1113       modeFile_Out += Hexotic_Out;
1114       system( modeFile_Out.ToCString() );
1115 #endif
1116     }
1117     SMESH_MesherHelper aHelper( aMesh );
1118
1119     Ok = readResult( &mgHexa, Hexotic_Out.ToCString(),
1120                      this,
1121                      &aHelper, _nbShape, tabShape, tabBox );
1122
1123     std::string log = mgHexa.GetLog();
1124     hexahedraMessage = "failed";
1125     if ( Ok )
1126     {
1127       hexahedraMessage = "success";
1128       if ( _removeLogOnSuccess )
1129         removeFile( aLogFileName );
1130     }
1131     else if ( !log.empty() )
1132     {
1133       if( _computeCanceled )
1134         error( "interruption initiated by user" );
1135       else
1136       {
1137         // get problem description from the log file
1138         char msgLic[] = " Dlim ";
1139         const char* fileBeg = &log[0], *fileEnd = fileBeg + log.size();
1140         if ( std::search( fileBeg, fileEnd, msgLic, msgLic+strlen(msgLic)) != fileEnd )
1141           error("Licence problems.");
1142       }
1143     }
1144     else if ( !errStr.empty() )
1145     {
1146       // the log file is empty
1147       removeFile( aLogFileName );
1148       INFOS( "MG-Hexa Error, " << errStr);
1149       error(COMPERR_ALGO_FAILED, errStr);
1150     }
1151
1152     if ( !Ok && mgHexa.IsExecutable() )
1153       std::cout << "Problem with MG-Hexa output file " << Hexotic_Out.ToCString() << std::endl;
1154
1155     if ( !_keepFiles )
1156     {
1157       if (! Ok && _computeCanceled )
1158         removeFile( aLogFileName );
1159       removeFile(Hexotic_Out);
1160       removeFile(Hexotic_In);
1161       for ( size_t i = 0; i < sizeMapFiles.size(); i++ )
1162         removeFile( sizeMapFiles[i].c_str() );
1163     }
1164     std::cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
1165     std::cout << std::endl;
1166
1167     delete [] tabShape;
1168     for (int i=0; i<_nbShape; i++)
1169       delete [] tabBox[i];
1170     delete [] tabBox;
1171     _nbShape = 0;
1172     _iShape  = 0;
1173   }
1174
1175   return Ok;
1176 }
1177
1178 //=============================================================================
1179 /*!
1180  * \brief Computes mesh without geometry
1181  *  \param aMesh - the mesh
1182  *  \param aHelper - helper that must be used for adding elements to \aaMesh
1183  *  \retval bool - is a success
1184  *
1185  * The method is called if ( !aMesh->HasShapeToMesh() )
1186  */
1187 //=============================================================================
1188
1189 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh & aMesh, SMESH_MesherHelper* aHelper)
1190 {
1191   _computeCanceled = false;
1192
1193   bool Ok = true;
1194   TCollection_AsciiString hexahedraMessage;
1195   TCollection_AsciiString aQuote("");
1196 #ifdef WIN32
1197   aQuote = "\"";
1198 #endif
1199   SetParameters(_hypothesis);
1200
1201   TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str();//getTmpDir();
1202   TCollection_AsciiString Hexotic_In, Hexotic_Out, Hexotic_SizeMap_Prefix;
1203   TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );
1204   TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log";    // log
1205
1206   std::map <int,int> aSmdsToHexoticIdMap;
1207   std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
1208
1209   Hexotic_In  = aTmpDir + "Hexotic"+getSuffix()+"_In.mesh";
1210   Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
1211   Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap";
1212
1213   MG_Hexotic_API mgHexa( _computeCanceled, _progress );
1214
1215   std::vector<std::string> sizeMapFiles = writeSizeMapFile( &mgHexa, Hexotic_SizeMap_Prefix.ToCString() );
1216
1217   std::string run_Hexotic = getHexoticCommand(aQuote + Hexotic_In + aQuote, aQuote + Hexotic_Out + aQuote, Hexotic_SizeMap_Prefix, mgHexa.IsExecutable());
1218   run_Hexotic += std::string(" 1> ") + aQuote.ToCString() + aLogFileName.ToCString() + aQuote.ToCString();  // dump into file
1219   mgHexa.SetLogFile( aLogFileName.ToCString() );
1220   std::cout << "Creating MG-Hexa log file : " << aLogFileName << std::endl;
1221
1222   removeHexoticFiles(Hexotic_In, Hexotic_Out);
1223
1224   splitQuads(aMesh); // quadrangles are no longer acceptable as input
1225
1226   std::cout << std::endl;
1227   std::cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
1228   writeInput( &mgHexa, Hexotic_In.ToCString(), aHelper->GetMeshDS() );
1229   if ( mgHexa.IsExecutable() )
1230   {
1231 #ifndef WIN32    
1232     modeFile_In += Hexotic_In;
1233     system( modeFile_In.ToCString() );
1234 #endif
1235   }
1236   aSmdsToHexoticIdMap.clear();
1237   aHexoticIdToNodeMap.clear();
1238
1239   MESSAGE("HexoticPlugin_Hexotic::Compute");
1240
1241   std::cout << std::endl;
1242   std::cout << "MG-Hexa command : " << run_Hexotic << std::endl;
1243
1244   std::string errStr;
1245   Ok = mgHexa.Compute( run_Hexotic, errStr ); // run
1246
1247   // --------------
1248   // read a result
1249   // --------------
1250
1251   if ( mgHexa.IsExecutable() && SMESH_File( Hexotic_Out.ToCString() ).exists() )
1252   {
1253     modeFile_Out += Hexotic_Out;
1254     system( modeFile_Out.ToCString() );
1255   }
1256
1257   Ok = Ok && readResult( &mgHexa, Hexotic_Out.ToCString(), this, aHelper );
1258
1259   std::string log = mgHexa.GetLog();
1260   if ( Ok )
1261   {
1262     hexahedraMessage = "success";
1263   }
1264   else
1265   {
1266     hexahedraMessage = "failed";
1267     if ( mgHexa.IsExecutable() )
1268       std::cout << "Problem with MG-Hexa output file " << Hexotic_Out << std::endl;
1269
1270     if ( log.find( " license " ) != std::string::npos ||
1271          log.find( " Dlim "    ) != std::string::npos )
1272       error("License problems.");
1273
1274     if ( !errStr.empty() )
1275       error(errStr);
1276   }
1277   std::cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
1278   std::cout << std::endl;
1279
1280   if(_computeCanceled)
1281     return error(SMESH_Comment("interruption initiated by user"));
1282   removeFile(Hexotic_Out);
1283   removeFile(Hexotic_In);
1284   if ( Ok )
1285     removeFile(aLogFileName);
1286   for( size_t i=0; i<sizeMapFiles.size(); i++)
1287   {
1288     removeFile( TCollection_AsciiString(sizeMapFiles[i].c_str()) );
1289   }
1290   return Ok;
1291 }
1292
1293 //=============================================================================
1294 /*!
1295  *
1296  */
1297 //=============================================================================
1298
1299 bool HexoticPlugin_Hexotic::Evaluate(SMESH_Mesh&         aMesh,
1300                                      const TopoDS_Shape& aShape,
1301                                      MapShapeNbElems&    aResMap)
1302 {
1303   std::vector<smIdType> aResVec(SMDSEntity_Last);
1304   for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1305   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
1306   aResMap.insert(std::make_pair(sm,aResVec));
1307
1308   SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1309   smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Evaluation is not implemented",this));
1310
1311   return true;
1312 }
1313
1314 void HexoticPlugin_Hexotic::CancelCompute()
1315 {
1316   _computeCanceled = true;
1317 #ifdef WIN32
1318 #else
1319   TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str(); //getTmpDir();
1320   TCollection_AsciiString Hexotic_In = aTmpDir + "Hexotic_In.mesh";
1321   TCollection_AsciiString cmd = TCollection_AsciiString("ps ux | grep ") + Hexotic_In;
1322   cmd += TCollection_AsciiString(" | grep -v grep | awk '{print $2}' | xargs kill -9 > /dev/null 2>&1");
1323   system( cmd.ToCString() );
1324 #endif
1325 }