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