Salome HOME
4c6ec601551f1b1eb749cba2a959241172d07a52
[plugins/hexoticplugin.git] / src / HexoticPlugin / HexoticPlugin_Hexotic.cxx
1 // Copyright (C) 2007-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 // ---
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   theHexaInput->SetIsInputMesh( true ); // it's a mesh file
354
355   // nodes
356   int iN = 0;
357   smIdType nbNodes = theMeshDS->NbNodes();
358   theHexaInput->GmfSetKwd( meshID, GmfVertices, nbNodes );
359   std::map< const SMDS_MeshNode*, int, TIDCompare > node2IdMap;
360   SMDS_NodeIteratorPtr nodeIt = theMeshDS->nodesIterator();
361   SMESH_TNodeXYZ n;
362   while ( nodeIt->more() )
363   {
364     n.Set( nodeIt->next() );
365     theHexaInput->GmfSetLin( meshID, GmfVertices, n.X(), n.Y(), n.Z(), n._node->getshapeId() );
366     node2IdMap.insert( node2IdMap.end(), std::make_pair( n._node, ++iN ));
367   }
368
369   // edges
370   SMDS_ElemIteratorPtr elemIt = theMeshDS->elementsIterator( SMDSAbs_Edge );
371   if ( elemIt->more() )
372   {
373     smIdType nbEdges = theMeshDS->GetMeshInfo().NbElements( SMDSAbs_Edge );
374     theHexaInput->GmfSetKwd(meshID, GmfEdges, nbEdges );
375     for ( int gmfID = 1; elemIt->more(); ++gmfID )
376     {
377       const SMDS_MeshElement* edge = elemIt->next();
378       theHexaInput->GmfSetLin(meshID, GmfEdges, 
379                               node2IdMap[ edge->GetNode( 0 )],
380                               node2IdMap[ edge->GetNode( 1 )],
381                               edge->getshapeId() );
382     }
383   }
384
385   // triangles
386   elemIt = theMeshDS->elementGeomIterator( SMDSGeom_TRIANGLE );
387   if ( elemIt->more() )
388   {
389     smIdType nbTria = theMeshDS->GetMeshInfo().NbElements( SMDSGeom_TRIANGLE );
390     theHexaInput->GmfSetKwd(meshID, GmfTriangles, nbTria );
391     for ( int gmfID = 1; elemIt->more(); ++gmfID )
392     {
393       const SMDS_MeshElement* tria = elemIt->next();
394       theHexaInput->GmfSetLin(meshID, GmfTriangles, 
395                               node2IdMap[ tria->GetNode( 0 )],
396                               node2IdMap[ tria->GetNode( 1 )],
397                               node2IdMap[ tria->GetNode( 2 )],
398                               tria->getshapeId() );
399     }
400   }
401   theHexaInput->GmfCloseMesh( meshID );
402 }
403
404 //=======================================================================
405 //function : readResult
406 //purpose  : Read GMF file in case of a mesh with geometry
407 //=======================================================================
408
409 static bool readResult(MG_Hexotic_API*       theHexaOutput,
410                        const char*           theFile,
411                        HexoticPlugin_Hexotic*theAlgo,
412                        SMESH_MesherHelper*   theHelper,
413                        const int             nbShape = 0,
414                        const TopoDS_Shape*   tabShape = 0,
415                        double**              tabBox = 0)
416 {
417   SMESH_Mesh*     theMesh = theHelper->GetMesh();
418   SMESHDS_Mesh* theMeshDS = theHelper->GetMeshDS();
419
420   // ---------------------------------
421   // Read generated elements and nodes
422   // ---------------------------------
423
424   TopoDS_Shape aShape;
425   TopoDS_Vertex aVertex;
426   std::string token;
427   int shapeID, hexoticShapeID;
428   const int IdShapeRef = 2;
429   std::vector< int > tabID;
430   double epsilon = Precision::Confusion();
431   std::map <std::string,int> mapField;
432   std::vector< SMDS_MeshNode*> HexoticNode;
433   std::vector< TopoDS_Shape > tabCorner;
434
435   const int nbDomains = countShape( theMesh, TopAbs_SHELL );
436   const int holeID = -1;
437
438   if ( nbDomains > 0 )
439   {
440     tabID.resize( nbDomains, 0 );
441     if ( nbDomains == 1 )
442       tabID[0] = theMeshDS->ShapeToIndex( tabShape[0] );
443   }
444   else
445   {
446     tabID.resize( 1, 1 );
447   }
448
449   SMDS_ElemIteratorPtr eIt = theMeshDS->elementsIterator();
450   while( eIt->more() )
451     theMeshDS->RemoveFreeElement( eIt->next(), /*sm=*/0 );
452   SMDS_NodeIteratorPtr nIt = theMeshDS->nodesIterator();
453   while ( nIt->more() )
454     theMeshDS->RemoveFreeNode( nIt->next(), /*sm=*/0 );
455
456   theHelper->SetElementsOnShape( false );
457
458   int ver, dim;
459   int meshID = theHexaOutput->GmfOpenMesh( theFile, GmfRead, &ver, &dim );
460
461   int nbVerticesInShape = countShape( theMesh, TopAbs_VERTEX );
462   int nbVertices  = getNbShape(theHexaOutput, meshID, GmfVertices );
463   int nbCorners   = getNbShape(theHexaOutput, meshID, GmfCorners, nbVerticesInShape);
464   if ( nbVertices == 0 )
465     return false;
466
467   tabCorner.resize( nbCorners );
468   HexoticNode.resize( nbVertices + 1 );
469
470   // get the shape vertices if the mesh lies on a shape (and this shape has corners)
471   if ( nbCorners > 0 && nbVerticesInShape > 0 )
472     getShape( theMeshDS, TopAbs_VERTEX, tabCorner.data() );
473
474   int nbNodes = theHexaOutput->GmfStatKwd( meshID, GmfVertices );
475   if ( nbNodes > 0 )
476   {
477     theHexaOutput->GmfGotoKwd( meshID, GmfVertices );
478     double x,y,z;
479     for ( int aHexoticID = 1; aHexoticID <= nbNodes; ++aHexoticID )
480     {
481       if ( theAlgo->computeCanceled() )
482         return false;
483       theHexaOutput->GmfGetLin( meshID, GmfVertices, &x, &y, &z, &shapeID );
484       HexoticNode[ aHexoticID ] = theHelper->AddNode( x,y,z );
485     }
486   }
487
488   int nodeID[8];
489   SMDS_MeshNode* node[8];
490   SMDS_MeshElement * aHexoticElement;
491
492   nbCorners = theHexaOutput->GmfStatKwd( meshID, GmfCorners );
493   if ( nbCorners > 0 && nbDomains > 0 )
494   {
495     theHexaOutput->GmfGotoKwd( meshID, GmfCorners );
496     for ( int iElem = 0; iElem < nbCorners; iElem++ )
497     {
498       if ( theAlgo->computeCanceled() )
499         return false;
500       theHexaOutput->GmfGetLin( meshID, GmfCorners, &nodeID[0] );
501       node[0] = HexoticNode[ nodeID[0] ];
502       gp_Pnt HexoticPnt ( node[0]->X(), node[0]->Y(), node[0]->Z() );
503       for ( int i = 0; i < nbCorners; i++ )
504       {
505         aVertex = TopoDS::Vertex( tabCorner[i] );
506         gp_Pnt aPnt = BRep_Tool::Pnt( aVertex );
507         if ( aPnt.Distance( HexoticPnt ) < epsilon )
508         {
509           theMeshDS->SetNodeOnVertex( node[0], aVertex );
510           break;
511         }
512       }
513     }
514   }
515
516   int nbEdges = theHexaOutput->GmfStatKwd( meshID, GmfEdges );
517   if ( nbEdges > 0 )
518   {
519     theHexaOutput->GmfGotoKwd( meshID, GmfEdges );
520     for ( int iElem = 0; iElem < nbEdges; iElem++ )
521     {
522       if ( theAlgo->computeCanceled() )
523         return false;
524       theHexaOutput->GmfGetLin( meshID, GmfEdges, &nodeID[0], &nodeID[1], &shapeID );
525       for ( int i = 0; i < 2; ++i )
526       {
527         node[i] = HexoticNode[ nodeID[i]];
528         if ( shapeID > 0 && node[i]->getshapeId() < 1 )
529           theMeshDS->SetNodeOnEdge( node[i], shapeID );
530       }
531       aHexoticElement = theHelper->AddEdge( node[0], node[1] );
532       if ( shapeID > 0 && aHexoticElement->getshapeId() < 1 )
533         theMeshDS->SetMeshElementOnShape( aHexoticElement, shapeID );
534     }
535   }
536
537   int nbQuad = theHexaOutput->GmfStatKwd( meshID, GmfQuadrilaterals );
538   if ( nbQuad > 0 )
539   {
540     theHexaOutput->GmfGotoKwd( meshID, GmfQuadrilaterals );
541     for ( int iElem = 0; iElem < nbQuad; iElem++ )
542     {
543       if ( theAlgo->computeCanceled() )
544         return false;
545       theHexaOutput->GmfGetLin( meshID, GmfQuadrilaterals,
546                                 &nodeID[0], &nodeID[1], &nodeID[2], &nodeID[3], &shapeID );
547       for ( int i = 0; i < 4; ++i )
548       {
549         node[i] = HexoticNode[ nodeID[i]];
550         if ( shapeID > 0 && node[i]->getshapeId() < 1 )
551           theMeshDS->SetNodeOnFace( node[i], shapeID );
552       }
553       aHexoticElement = theHelper->AddFace( node[0], node[1], node[2], node[3] );
554       if ( shapeID > 0 && aHexoticElement->getshapeId() < 1 )
555         theMeshDS->SetMeshElementOnShape( aHexoticElement, shapeID );
556     }
557   }
558
559   int nbHexa = theHexaOutput->GmfStatKwd( meshID, GmfHexahedra );
560   if ( nbHexa > 0 )
561   {
562     theHexaOutput->GmfGotoKwd( meshID, GmfHexahedra );
563     for ( int iElem = 0; iElem < nbHexa; iElem++ )
564     {
565       if ( theAlgo->computeCanceled() )
566         return false;
567       theHexaOutput->GmfGetLin( meshID, GmfHexahedra,
568                                 &nodeID[0], &nodeID[1], &nodeID[2], &nodeID[3],
569                                 &nodeID[4], &nodeID[5], &nodeID[6], &nodeID[7],
570                                 &shapeID );
571       for ( int i = 0; i < 8; ++i )
572       {
573         node[i] = HexoticNode[ nodeID[i]];
574       }
575       if ( nbDomains > 1 ) {
576         hexoticShapeID = shapeID - IdShapeRef;
577         if ( tabID[ hexoticShapeID ] == 0 ) {
578           aShape = findShape(node, aShape, tabShape, tabBox, nbShape);
579           shapeID = aShape.IsNull() ? holeID : theMeshDS->ShapeToIndex( aShape );
580           tabID[ hexoticShapeID ] = shapeID;
581         }
582         else {
583           shapeID = tabID[ hexoticShapeID ];
584         }
585         if ( iElem == ( nbHexa - 1) ) {
586           int shapeAssociated = 0;
587           for ( int i=0; i<nbDomains; i++ ) {
588             if (tabID[i] > 0 )
589               shapeAssociated += 1;
590           }
591           if ( shapeAssociated != nbShape )
592             printWarning(nbShape, "domains", shapeAssociated);
593         }
594       }
595       else {
596         shapeID = tabID[0];
597       }
598
599       if ( shapeID != holeID )
600       {
601         for ( int i = 0; i < 8; ++i )
602         {
603           if ( node[i]->NbInverseElements( SMDSAbs_Face ) == 0 )
604             theMeshDS->SetNodeInVolume( node[i], shapeID );
605         }
606         aHexoticElement = theHelper->AddVolume( node[0], node[3], node[2], node[1],
607                                                 node[4], node[7], node[6], node[5]);
608         if ( aHexoticElement->getshapeId() < 1 )
609           theMeshDS->SetMeshElementOnShape( aHexoticElement, shapeID );
610       }
611     }
612   }
613   std::cout << std::endl;
614
615   // remove nodes in holes
616   if ( nbDomains > 1 )
617   {
618     SMESHDS_SubMesh* subMesh = 0;
619     for ( int i = 1; i <= nbNodes; ++i )
620       if ( HexoticNode[i]->NbInverseElements() == 0 )
621       {
622         theMeshDS->RemoveFreeNode( HexoticNode[i], subMesh, /*fromGroups=*/false );
623       }
624   }
625
626   // avoid "Error: No mesh on sub-shape"
627   if ( theMesh->NbVolumes() > 0 )
628   {
629     SMESH_subMesh*         smMain = theMesh->GetSubMesh( theMesh->GetShapeToMesh() );
630     SMESH_subMeshIteratorPtr smIt = smMain->getDependsOnIterator( /*includeSelf=*/true );
631     while ( smIt->more() )
632     {
633       SMESH_subMesh* sm = smIt->next();
634       if ( !sm->IsMeshComputed() )
635         sm->SetIsAlwaysComputed( true );
636     }
637   }
638
639   return true;
640 }
641
642 //=============================================================================
643 /*!
644  * Pass parameters to MG-Hexa
645  */
646 //=============================================================================
647
648 void HexoticPlugin_Hexotic::SetParameters(const HexoticPlugin_Hypothesis* hyp)
649 {
650   if (hyp) {
651     _hexesMinLevel = hyp->GetHexesMinLevel();
652     _hexesMaxLevel = hyp->GetHexesMaxLevel();
653     _hexesMinSize = hyp->GetMinSize();
654     _hexesMaxSize = hyp->GetMaxSize();
655     _approxAngle = hyp->GetGeomApproxAngle();
656     _hexoticIgnoreRidges = hyp->GetHexoticIgnoreRidges();
657     _hexoticInvalidElements = hyp->GetHexoticInvalidElements();
658     _hexoticSharpAngleThreshold = hyp->GetHexoticSharpAngleThreshold();
659     _hexoticNbProc = hyp->GetHexoticNbProc();
660     _hexoticWorkingDirectory = hyp->GetHexoticWorkingDirectory();
661     _hexoticVerbosity = hyp->GetHexoticVerbosity();
662     _hexoticMaxMemory = hyp->GetHexoticMaxMemory();
663     _hexoticSdMode = hyp->GetHexoticSdMode();
664     _textOptions = hyp->GetAdvancedOption();
665     _sizeMaps = hyp->GetSizeMaps();
666     _nbLayers = hyp->GetNbLayers();
667     _firstLayerSize = hyp->GetFirstLayerSize();
668     _direction = hyp->GetDirection();
669     _growth = hyp->GetGrowth();
670     _facesWithLayers = hyp->GetFacesWithLayers();
671     _imprintedFaces = hyp->GetImprintedFaces();
672     _keepFiles = hyp->GetKeepFiles();
673     _removeLogOnSuccess = hyp->GetRemoveLogOnSuccess();
674     _logInStandardOutput = hyp->GetStandardOutputLog();
675   }
676   else {
677     std::cout << std::endl;
678     std::cout << "WARNING : The MG-Hexa default parameters are taken into account" << std::endl;
679     std::cout << "=======" << std::endl;
680     _hexesMinLevel = hyp->GetDefaultHexesMinLevel();
681     _hexesMaxLevel = hyp->GetDefaultHexesMaxLevel();
682     _hexesMinSize = hyp->GetDefaultMinSize();
683     _hexesMaxSize = hyp->GetDefaultMaxSize();
684     _approxAngle = hyp->GetDefaultGeomApproxAngle();
685     _hexoticIgnoreRidges = hyp->GetDefaultHexoticIgnoreRidges();
686     _hexoticInvalidElements = hyp->GetDefaultHexoticInvalidElements();
687     _hexoticSharpAngleThreshold = hyp->GetDefaultHexoticSharpAngleThreshold();
688     _hexoticNbProc = hyp->GetDefaultHexoticNbProc();
689     _hexoticWorkingDirectory = hyp->GetDefaultHexoticWorkingDirectory();
690     _hexoticVerbosity = hyp->GetDefaultHexoticVerbosity();
691     _hexoticMaxMemory = hyp->GetDefaultHexoticMaxMemory();
692     _hexoticSdMode = hyp->GetDefaultHexoticSdMode();
693     _textOptions = hyp->GetDefaultTextOptions();
694     _sizeMaps = hyp->GetDefaultHexoticSizeMaps();
695     _nbLayers = hyp->GetDefaultNbLayers();
696     _firstLayerSize = hyp->GetDefaultFirstLayerSize();
697     _direction = hyp->GetDefaultDirection();
698     _growth = hyp->GetDefaultGrowth();
699     _facesWithLayers = hyp->GetDefaultFacesWithLayers();
700     _imprintedFaces = hyp->GetDefaultImprintedFaces();
701     _keepFiles = hyp->GetDefaultKeepFiles();
702     _removeLogOnSuccess = hyp->GetDefaultRemoveLogOnSuccess();
703     _logInStandardOutput = hyp->GetDefaultStandardOutputLog();
704   }
705 }
706
707 //=======================================================================
708 //function : getSuffix
709 //purpose  : Returns a suffix that will be unique for the current process
710 //=======================================================================
711
712 static TCollection_AsciiString getSuffix()
713 {
714   TCollection_AsciiString aSuffix = "";
715   aSuffix += "_";
716 #ifndef WIN32
717   aSuffix += getenv("USER");
718 #else
719   std::string uname = std::string(getenv("USERNAME"));
720   replace(uname.begin(), uname.end(), ' ', '_');
721   aSuffix += uname.c_str();
722 #endif
723   aSuffix += "_";
724   aSuffix += Kernel_Utils::GetHostname().c_str();
725   aSuffix += "_";
726 #ifndef WIN32
727   aSuffix += getpid();
728 #else
729   aSuffix += _getpid();
730 #endif
731
732   return aSuffix;
733 }
734
735 //================================================================================
736 /*!
737  * \brief Returns a command to run MG-Hexa mesher
738  */
739 //================================================================================
740
741 std::string
742 HexoticPlugin_Hexotic::getHexoticCommand(const TCollection_AsciiString& Hexotic_In,
743                                          const TCollection_AsciiString& Hexotic_Out,
744                                          const TCollection_AsciiString& Hexotic_SizeMap_Prefix,
745                                          const bool                     forExecutable) const
746 {
747   std::cout << std::endl;
748   std::cout << "MG-Hexa execution..." << std::endl;
749   std::cout << _name << " parameters :" << std::endl;
750   std::cout << "    " << _name << " Verbosity = " << _hexoticVerbosity << std::endl;
751   std::cout << "    " << _name << " Max Memory = " << _hexoticMaxMemory << std::endl;
752   std::cout << "    " << _name << " Segments Min Level = " << _hexesMinLevel << std::endl;
753   std::cout << "    " << _name << " Segments Max Level = " << _hexesMaxLevel << std::endl;
754   std::cout << "    " << _name << " Segments Min Size = " << _hexesMinSize << std::endl;
755   std::cout << "    " << _name << " Segments Max Size = " << _hexesMaxSize << std::endl;
756   std::cout << "    " << "MG-Hexa can ignore ridges : " << (_hexoticIgnoreRidges ? "yes":"no") << std::endl;
757   std::cout << "    " << "MG-Hexa authorize invalide elements : " << ( _hexoticInvalidElements ? "yes":"no") << std::endl;
758   std::cout << "    " << _name << " Sharp angle threshold = " << _hexoticSharpAngleThreshold << " degrees" << std::endl;
759   std::cout << "    " << _name << " Number of threads = " << _hexoticNbProc << std::endl;
760   std::cout << "    " << _name << " Working directory = \"" << _hexoticWorkingDirectory << "\"" << std::endl;
761   std::cout << "    " << _name << " Sub. Dom mode = " << _hexoticSdMode << std::endl;
762   std::cout << "    " << _name << " Text options = \"" << _textOptions << "\"" << std::endl;
763   std::cout << "    " << _name << " Number of layers = " << _nbLayers << std::endl;
764   std::cout << "    " << _name << " Size of the first layer  = " << _firstLayerSize << std::endl;
765   std::cout << "    " << _name << " Direction of the layers = " << ( _direction ? "Inward" : "Outward" ) << std::endl;
766   std::cout << "    " << _name << " Growth = " << _growth << std::endl;
767   if (!_facesWithLayers.empty()) {
768     std::cout << "    " << _name << " Faces with layers = ";
769     for (size_t i = 0; i < _facesWithLayers.size(); i++)
770     {
771       std::cout << _facesWithLayers.at(i);
772       if ((i + 1) != _facesWithLayers.size())
773         std::cout << ", ";
774     }
775     std::cout << std::endl;
776   }
777   if (!_imprintedFaces.empty()) {
778     std::cout << "    " << _name << " Imprinted faces = ";
779     for (size_t i = 0; i < _imprintedFaces.size(); i++)
780     {
781       std::cout << _imprintedFaces.at(i);
782       if ((i + 1) != _imprintedFaces.size())
783         std::cout << ", ";
784     }
785     std::cout << std::endl;
786   }
787
788   TCollection_AsciiString run_Hexotic("mg-hexa.exe");
789
790   TCollection_AsciiString minl         = " --min_level ", maxl = " --max_level ", angle = " --ridge_angle ";
791   TCollection_AsciiString mins         = " --min_size ", maxs = " --max_size ";
792   TCollection_AsciiString in           = " --in ",   out  = " --out ";
793   TCollection_AsciiString sizeMap      = " --background_sizemap ";
794   TCollection_AsciiString sizeMapMesh  = " --background_mesh ";
795   TCollection_AsciiString ignoreRidges = " --compute_ridges no ", invalideElements = " --allow_invalid_elements yes ";
796   TCollection_AsciiString subdom       = " --components ";
797 #ifndef WIN32
798   TCollection_AsciiString proc         = " --max_number_of_threads ";
799 #endif
800   TCollection_AsciiString verb         = " --verbose ";
801   TCollection_AsciiString maxmem       = " --max_memory ";
802
803   TCollection_AsciiString comNbLayers        = " --number_of_boundary_layers ";
804   TCollection_AsciiString comFirstLayerSize  = " --height_of_the_first_layer ";
805   TCollection_AsciiString comDirection       = " --boundary_layers_subdomain_direction ";
806   TCollection_AsciiString comGrowth          = " --boundary_layers_geometric_progression ";
807   TCollection_AsciiString comFacesWithLayers = " --boundary_layers_surface_ids ";
808   TCollection_AsciiString comImptintedFaces  = " --imprinted_surface_ids ";
809
810   TCollection_AsciiString minLevel, maxLevel, minSize, maxSize, sharpAngle, mode, nbproc, verbosity, maxMemory,
811                           textOptions, nbLayers, firstLayerSize, direction, growth, facesWithLayers, imprintedFaces;
812   minLevel   = _hexesMinLevel;
813   maxLevel   = _hexesMaxLevel;
814   minSize    = _hexesMinSize;
815   maxSize    = _hexesMaxSize;
816   sharpAngle = _hexoticSharpAngleThreshold;
817   // Mode translation for mg-tetra 1.1
818   switch ( _hexoticSdMode )
819   {
820     case 1:
821       mode = "outside_skin_only";
822       break;
823     case 2:
824       mode = "outside_components";
825       break;
826     case 3:
827       mode = "all";
828       break;
829     case 4:
830       mode = "all --manifold_geometry no";
831       break;
832   }
833   nbproc         = _hexoticNbProc;
834   verbosity      = _hexoticVerbosity;
835   maxMemory      = _hexoticMaxMemory;
836   textOptions    = (" " + _textOptions + " ").c_str();
837   nbLayers       = _nbLayers;
838   firstLayerSize = _firstLayerSize;
839   direction      = _direction ? "1" : "-1";
840   growth         = _growth;
841   for (size_t i = 0; i < _facesWithLayers.size(); i++)
842   {
843     facesWithLayers += _facesWithLayers[i];
844     if ((i + 1) != _facesWithLayers.size())
845       facesWithLayers += ",";
846   }
847   for (size_t i = 0; i < _imprintedFaces.size(); i++)
848   {
849     imprintedFaces += _imprintedFaces[i];
850     if ((i + 1) != _imprintedFaces.size())
851       imprintedFaces += ",";
852   }
853
854   if (_hexoticIgnoreRidges)
855     run_Hexotic +=  ignoreRidges;
856
857   if (_hexoticInvalidElements)
858     run_Hexotic +=  invalideElements;
859
860   if (_hexesMinSize > 0)
861     run_Hexotic +=  mins + minSize;
862
863   if (_hexesMaxSize > 0)
864     run_Hexotic +=  maxs + maxSize;
865
866   if (_hexesMinLevel > 0)
867     run_Hexotic +=  minl + minLevel;
868
869   if (_hexesMaxLevel > 0)
870     run_Hexotic +=  maxl + maxLevel;
871
872   if (_hexoticSharpAngleThreshold > 0)
873     run_Hexotic +=  angle + sharpAngle;
874
875   if ( !_sizeMaps.empty() && forExecutable )
876     run_Hexotic += ( sizeMap     + Hexotic_SizeMap_Prefix + ".sol " +
877                      sizeMapMesh + Hexotic_SizeMap_Prefix + ".mesh " );
878
879   if (_nbLayers       > 0 &&
880       _firstLayerSize > 0 &&
881       _growth         > 0 &&
882       !_facesWithLayers.empty())
883   {
884     run_Hexotic += comNbLayers + nbLayers;
885     run_Hexotic += comFirstLayerSize + firstLayerSize;
886     run_Hexotic += comDirection + direction;
887     run_Hexotic += comGrowth + growth;
888     run_Hexotic += comFacesWithLayers + facesWithLayers;
889     if (!_imprintedFaces.empty())
890       run_Hexotic += comImptintedFaces + imprintedFaces;
891   }
892   if ( forExecutable )
893     run_Hexotic += in + Hexotic_In + out + Hexotic_Out;
894   run_Hexotic += subdom + mode;
895 #ifndef WIN32
896   run_Hexotic += proc + nbproc;
897 #endif
898   run_Hexotic += verb + verbosity;
899   run_Hexotic += maxmem + maxMemory;
900
901   if (!_textOptions.empty())
902     run_Hexotic += textOptions;
903
904   return run_Hexotic.ToCString();
905 }
906
907 // TODO : this is a duplication of some code found in BLSURFPlugin_BLSURF find a proper
908 // way to share it
909 TopoDS_Shape HexoticPlugin_Hexotic::entryToShape(std::string entry)
910 {
911   GEOM::GEOM_Object_var aGeomObj;
912   TopoDS_Shape S = TopoDS_Shape();
913   SALOMEDS::SObject_var aSObj = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( entry.c_str() );
914   if (!aSObj->_is_nil()) {
915     CORBA::Object_var obj = aSObj->GetObject();
916     aGeomObj = GEOM::GEOM_Object::_narrow(obj);
917     aSObj->UnRegister();
918   }
919   if ( !aGeomObj->_is_nil() )
920     S = SMESH_Gen_i::GetSMESHGen()->GeomObjectToShape( aGeomObj.in() );
921   return S;
922 }
923
924 //================================================================================
925 /*!
926  * \brief Produces a .mesh file with the size maps informations to give to Hexotic
927  */
928 //================================================================================
929
930 std::vector<std::string> HexoticPlugin_Hexotic::writeSizeMapFile( MG_Hexotic_API* mgInput,
931                                                                   std::string     sizeMapPrefix )
932 {
933   HexoticPlugin_Hypothesis::THexoticSizeMaps::iterator it;
934
935   std::vector<ControlPnt> points;
936   // Iterate on the size maps
937   for (it=_sizeMaps.begin(); it!=_sizeMaps.end(); it++)
938   {
939     // Step 1 : Get the GEOM object entry and the size 
940     // from the _sizeMaps infos
941     std::string anEntry = it->first;
942     double aLocalSize = it->second;
943     TopoDS_Shape aShape = entryToShape( anEntry );
944     
945     // Step 2 : Create the points
946     createControlPoints( aShape, aLocalSize, points );
947   }
948
949   // Write the .mesh size map file
950
951   std::string myVerticesFile = sizeMapPrefix + ".mesh";
952   std::string      mySolFile = sizeMapPrefix + ".sol";
953   
954   // Open files
955   int verticesFileID =
956     mgInput->GmfOpenMesh( myVerticesFile.c_str(), GmfWrite, GMFVERSION, GMFDIMENSION );  
957   int solFileID =
958     mgInput->GmfOpenMesh( mySolFile.c_str(), GmfWrite, GMFVERSION, GMFDIMENSION );
959
960   mgInput->SetIsInputMesh( false ); // they are not mesh files
961   
962   int pointsNumber = points.size();
963   
964   // Vertices Keyword
965   mgInput->GmfSetKwd( verticesFileID, GmfVertices, pointsNumber );
966   // SolAtVertices Keyword
967   int TypTab[] = {GmfSca};
968   mgInput->GmfSetKwd(solFileID, GmfSolAtVertices, pointsNumber, 1, TypTab);
969   
970   // Read the control points information from the vector and write it into the files
971   double ValTab[1];
972   std::vector<ControlPnt>::const_iterator points_it;
973   for (points_it = points.begin(); points_it != points.end(); points_it++ )
974   {
975     mgInput->GmfSetLin( verticesFileID, GmfVertices, points_it->X(), points_it->Y(), points_it->Z(), 0 );
976     ValTab[0] = points_it->Size();
977     mgInput->GmfSetLin( solFileID, GmfSolAtVertices, ValTab);
978   }
979
980   // Close Files
981   mgInput->GmfCloseMesh( verticesFileID );
982   mgInput->GmfCloseMesh( solFileID );
983
984   std::vector<std::string> fileNames(2);
985   fileNames[0] = myVerticesFile;
986   fileNames[1] = mySolFile;
987
988   return fileNames;
989 }
990
991 //=============================================================================
992 /*!
993  * Here we are going to use the MG-Hexa mesher
994  */
995 //=============================================================================
996
997 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh&          aMesh,
998                                     const TopoDS_Shape& /*aShape*/)
999 {
1000   _computeCanceled = false;
1001   bool Ok = true;
1002   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1003   TCollection_AsciiString hexahedraMessage;
1004
1005   _nbShape = countShape( &aMesh, TopAbs_SOLID );  // we count the number of shapes
1006
1007   {
1008     // create bounding box for each shape of the compound
1009
1010     int iShape = 0;
1011     TopoDS_Shape *tabShape;
1012     double **tabBox;
1013
1014     tabShape = new TopoDS_Shape[_nbShape];
1015     tabBox   = new double*[_nbShape];
1016     for (int i=0; i<_nbShape; i++)
1017       tabBox[i] = new double[6];
1018     double Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
1019
1020     TopExp_Explorer expBox (meshDS->ShapeToMesh(), TopAbs_SOLID);
1021     for (; expBox.More(); expBox.Next()) {
1022       tabShape[iShape] = expBox.Current();
1023       Bnd_Box BoundingBox;
1024       BRepBndLib::Add(expBox.Current(), BoundingBox);
1025       BoundingBox.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
1026       tabBox[iShape][0] = Xmin; tabBox[iShape][1] = Xmax;
1027       tabBox[iShape][2] = Ymin; tabBox[iShape][3] = Ymax;
1028       tabBox[iShape][4] = Zmin; tabBox[iShape][5] = Zmax;
1029       iShape++;
1030     }
1031
1032     SetParameters(_hypothesis);
1033
1034     TCollection_AsciiString aTmpDir = Kernel_Utils::GetTmpDirByPath(_hexoticWorkingDirectory).c_str();
1035     TCollection_AsciiString aQuote("");
1036 #ifdef WIN32
1037     aQuote = "\"";
1038     if ( aTmpDir.Value(aTmpDir.Length()) != '\\' ) aTmpDir += '\\';
1039 #else
1040     if ( aTmpDir.Value(aTmpDir.Length()) != '/' ) aTmpDir += '/';
1041 #endif
1042     TCollection_AsciiString Hexotic_In(""), Hexotic_Out, Hexotic_SizeMap_Prefix;
1043     TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );
1044     TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log";    // log
1045
1046     std::map <int,int> aSmdsToHexoticIdMap;
1047     std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
1048
1049     MG_Hexotic_API mgHexa( _computeCanceled, _progress );
1050
1051     Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
1052 #ifdef WITH_BLSURFPLUGIN
1053     bool defaultInputFile = true;
1054     if (_blsurfHypo && _blsurfHypo->GetElementType() == BLSURFPlugin_Hypothesis::Triangles ) {
1055       Hexotic_In = _blsurfHypo->GetGMFFile().c_str();
1056       if ( !Hexotic_In.IsEmpty() &&
1057            SMESH_File( _blsurfHypo->GetGMFFile() ).exists() )
1058       {
1059         MESSAGE("Use output file from blsurf as input file from hexotic: " << Hexotic_In);
1060         mgHexa.SetUseExecutable();
1061         mgHexa.SetInputFile( _blsurfHypo->GetGMFFile() );
1062         defaultInputFile = false;
1063       }
1064     }
1065     if (defaultInputFile) {
1066 #endif
1067       Hexotic_In  = aTmpDir + "Hexotic"+getSuffix()+"_In.mesh";
1068       removeHexoticFiles(Hexotic_In, Hexotic_Out);
1069       splitQuads(aMesh); // quadrangles are no longer acceptable as input
1070       if ( mgHexa.IsExecutable() )
1071       {
1072         std::cout << std::endl;
1073         std::cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
1074       }
1075       writeInput( &mgHexa, Hexotic_In.ToCString(), meshDS );
1076 #ifdef WITH_BLSURFPLUGIN
1077     }
1078     else {
1079       removeFile( Hexotic_Out );
1080     }
1081 #endif
1082     
1083     Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap" + getSuffix();
1084     std::vector<std::string> sizeMapFiles = writeSizeMapFile( &mgHexa, Hexotic_SizeMap_Prefix.ToCString() );
1085     
1086     std::string run_Hexotic = getHexoticCommand(aQuote + Hexotic_In + aQuote, aQuote + Hexotic_Out + aQuote, Hexotic_SizeMap_Prefix, mgHexa.IsExecutable() );
1087     run_Hexotic += std::string(" 1> ") + aQuote.ToCString() + aLogFileName.ToCString() + aQuote.ToCString();  // dump into file
1088     mgHexa.SetLogFile( aLogFileName.ToCString() );
1089     std::cout << "Creating MG-Hexa log file : " << aLogFileName << std::endl;
1090
1091     std::cout << std::endl;
1092     std::cout << "MG-Hexa command : " << run_Hexotic << std::endl;
1093
1094     if ( mgHexa.IsExecutable() )
1095     {
1096 #ifndef WIN32    
1097       modeFile_In += Hexotic_In;
1098       system( modeFile_In.ToCString() );
1099 #endif
1100     }
1101     aSmdsToHexoticIdMap.clear();
1102     aHexoticIdToNodeMap.clear();
1103
1104     MESSAGE("HexoticPlugin_Hexotic::Compute");
1105
1106     
1107     std::string errStr;
1108     Ok = mgHexa.Compute( run_Hexotic, errStr ); // run
1109
1110
1111     // --------------
1112     // read a result
1113     // --------------
1114
1115     if ( mgHexa.IsExecutable() && SMESH_File( Hexotic_Out.ToCString() ).exists() )
1116     {
1117 #ifndef WIN32
1118       modeFile_Out += Hexotic_Out;
1119       system( modeFile_Out.ToCString() );
1120 #endif
1121     }
1122     SMESH_MesherHelper aHelper( aMesh );
1123
1124     Ok = readResult( &mgHexa, Hexotic_Out.ToCString(),
1125                      this,
1126                      &aHelper, _nbShape, tabShape, tabBox );
1127
1128     std::string log = mgHexa.GetLog();
1129     hexahedraMessage = "failed";
1130     if ( Ok )
1131     {
1132       hexahedraMessage = "success";
1133       if ( _removeLogOnSuccess )
1134         removeFile( aLogFileName );
1135     }
1136     else if ( !log.empty() )
1137     {
1138       if( _computeCanceled )
1139         error( "interruption initiated by user" );
1140       else
1141       {
1142         // get problem description from the log file
1143         char msgLic[] = " Dlim ";
1144         const char* fileBeg = &log[0], *fileEnd = fileBeg + log.size();
1145         if ( std::search( fileBeg, fileEnd, msgLic, msgLic+strlen(msgLic)) != fileEnd )
1146           error("Licence problems.");
1147       }
1148     }
1149     else if ( !errStr.empty() )
1150     {
1151       // the log file is empty
1152       removeFile( aLogFileName );
1153       INFOS( "MG-Hexa Error, " << errStr);
1154       error(COMPERR_ALGO_FAILED, errStr);
1155     }
1156
1157     if ( !Ok && mgHexa.IsExecutable() )
1158       std::cout << "Problem with MG-Hexa output file " << Hexotic_Out.ToCString() << std::endl;
1159
1160     if ( !_keepFiles )
1161     {
1162       if (! Ok && _computeCanceled )
1163         removeFile( aLogFileName );
1164       removeFile(Hexotic_Out);
1165       removeFile(Hexotic_In);
1166       for ( size_t i = 0; i < sizeMapFiles.size(); i++ )
1167         removeFile( sizeMapFiles[i].c_str() );
1168     }
1169     std::cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
1170     std::cout << std::endl;
1171
1172     delete [] tabShape;
1173     for (int i=0; i<_nbShape; i++)
1174       delete [] tabBox[i];
1175     delete [] tabBox;
1176     _nbShape = 0;
1177     _iShape  = 0;
1178   }
1179
1180   return Ok;
1181 }
1182
1183 //=============================================================================
1184 /*!
1185  * \brief Computes mesh without geometry
1186  *  \param aMesh - the mesh
1187  *  \param aHelper - helper that must be used for adding elements to \aaMesh
1188  *  \retval bool - is a success
1189  *
1190  * The method is called if ( !aMesh->HasShapeToMesh() )
1191  */
1192 //=============================================================================
1193
1194 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh & aMesh, SMESH_MesherHelper* aHelper)
1195 {
1196   _computeCanceled = false;
1197
1198   bool Ok = true;
1199   TCollection_AsciiString hexahedraMessage;
1200   TCollection_AsciiString aQuote("");
1201 #ifdef WIN32
1202   aQuote = "\"";
1203 #endif
1204   SetParameters(_hypothesis);
1205
1206   TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str();//getTmpDir();
1207   TCollection_AsciiString Hexotic_In, Hexotic_Out, Hexotic_SizeMap_Prefix;
1208   TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );
1209   TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log";    // log
1210
1211   std::map <int,int> aSmdsToHexoticIdMap;
1212   std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
1213
1214   Hexotic_In  = aTmpDir + "Hexotic"+getSuffix()+"_In.mesh";
1215   Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
1216   Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap";
1217
1218   MG_Hexotic_API mgHexa( _computeCanceled, _progress );
1219
1220   std::vector<std::string> sizeMapFiles = writeSizeMapFile( &mgHexa, Hexotic_SizeMap_Prefix.ToCString() );
1221
1222   std::string run_Hexotic = getHexoticCommand(aQuote + Hexotic_In + aQuote, aQuote + Hexotic_Out + aQuote, Hexotic_SizeMap_Prefix, mgHexa.IsExecutable());
1223   run_Hexotic += std::string(" 1> ") + aQuote.ToCString() + aLogFileName.ToCString() + aQuote.ToCString();  // dump into file
1224   mgHexa.SetLogFile( aLogFileName.ToCString() );
1225   std::cout << "Creating MG-Hexa log file : " << aLogFileName << std::endl;
1226
1227   removeHexoticFiles(Hexotic_In, Hexotic_Out);
1228
1229   splitQuads(aMesh); // quadrangles are no longer acceptable as input
1230
1231   std::cout << std::endl;
1232   std::cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
1233   writeInput( &mgHexa, Hexotic_In.ToCString(), aHelper->GetMeshDS() );
1234   if ( mgHexa.IsExecutable() )
1235   {
1236 #ifndef WIN32    
1237     modeFile_In += Hexotic_In;
1238     system( modeFile_In.ToCString() );
1239 #endif
1240   }
1241   aSmdsToHexoticIdMap.clear();
1242   aHexoticIdToNodeMap.clear();
1243
1244   MESSAGE("HexoticPlugin_Hexotic::Compute");
1245
1246   std::cout << std::endl;
1247   std::cout << "MG-Hexa command : " << run_Hexotic << std::endl;
1248
1249   std::string errStr;
1250   Ok = mgHexa.Compute( run_Hexotic, errStr ); // run
1251
1252   // --------------
1253   // read a result
1254   // --------------
1255
1256   if ( mgHexa.IsExecutable() && SMESH_File( Hexotic_Out.ToCString() ).exists() )
1257   {
1258     modeFile_Out += Hexotic_Out;
1259     system( modeFile_Out.ToCString() );
1260   }
1261
1262   Ok = Ok && readResult( &mgHexa, Hexotic_Out.ToCString(), this, aHelper );
1263
1264   std::string log = mgHexa.GetLog();
1265   if ( Ok )
1266   {
1267     hexahedraMessage = "success";
1268   }
1269   else
1270   {
1271     hexahedraMessage = "failed";
1272     if ( mgHexa.IsExecutable() )
1273       std::cout << "Problem with MG-Hexa output file " << Hexotic_Out << std::endl;
1274
1275     if ( log.find( " license " ) != std::string::npos ||
1276          log.find( " Dlim "    ) != std::string::npos )
1277       error("License problems.");
1278
1279     if ( !errStr.empty() )
1280       error(errStr);
1281   }
1282   std::cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
1283   std::cout << std::endl;
1284
1285   if(_computeCanceled)
1286     return error(SMESH_Comment("interruption initiated by user"));
1287   removeFile(Hexotic_Out);
1288   removeFile(Hexotic_In);
1289   if ( Ok )
1290     removeFile(aLogFileName);
1291   for( size_t i=0; i<sizeMapFiles.size(); i++)
1292   {
1293     removeFile( TCollection_AsciiString(sizeMapFiles[i].c_str()) );
1294   }
1295   return Ok;
1296 }
1297
1298 //=============================================================================
1299 /*!
1300  *
1301  */
1302 //=============================================================================
1303
1304 bool HexoticPlugin_Hexotic::Evaluate(SMESH_Mesh&         aMesh,
1305                                      const TopoDS_Shape& aShape,
1306                                      MapShapeNbElems&    aResMap)
1307 {
1308   std::vector<smIdType> aResVec(SMDSEntity_Last);
1309   for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1310   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
1311   aResMap.insert(std::make_pair(sm,aResVec));
1312
1313   SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1314   smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Evaluation is not implemented",this));
1315
1316   return true;
1317 }
1318
1319 void HexoticPlugin_Hexotic::CancelCompute()
1320 {
1321   _computeCanceled = true;
1322 #ifdef WIN32
1323 #else
1324   TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str(); //getTmpDir();
1325   TCollection_AsciiString Hexotic_In = aTmpDir + "Hexotic_In.mesh";
1326   TCollection_AsciiString cmd = TCollection_AsciiString("ps ux | grep ") + Hexotic_In;
1327   cmd += TCollection_AsciiString(" | grep -v grep | awk '{print $2}' | xargs kill -9 > /dev/null 2>&1");
1328   system( cmd.ToCString() );
1329 #endif
1330 }