]> SALOME platform Git repositories - plugins/ghs3dplugin.git/blob - src/GHS3DPlugin_GHS3D.cxx
Salome HOME
PAL19680 Meshers: BLSURF, GHS3D and holed shapes
[plugins/ghs3dplugin.git] / src / GHS3DPlugin_GHS3D.cxx
1 // Copyright (C) 2005  CEA/DEN, EDF R&D, OPEN CASCADE, PRINCIPIA 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.
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 // File      : GHS3DPlugin_GHS3D.cxx
21 // Created   : 
22 // Author    : Edward AGAPOV, modified by Lioka RAZAFINDRAZAKA (CEA) 09/02/2007
23 // Project   : SALOME
24 // Copyright : CEA 2003
25 // $Header$
26 //=============================================================================
27 using namespace std;
28
29 #include "GHS3DPlugin_GHS3D.hxx"
30 #include "GHS3DPlugin_Hypothesis.hxx"
31
32 #include "SMESH_Gen.hxx"
33 #include "SMESH_Mesh.hxx"
34 #include "SMESH_Comment.hxx"
35 #include "SMESH_MesherHelper.hxx"
36 #include "SMESH_MeshEditor.hxx"
37
38 #include "SMDS_MeshElement.hxx"
39 #include "SMDS_MeshNode.hxx"
40
41 #include <BRepAdaptor_Surface.hxx>
42 #include <BRepBndLib.hxx>
43 #include <BRepClass3d_SolidClassifier.hxx>
44 #include <BRep_Tool.hxx>
45 #include <Bnd_Box.hxx>
46 #include <GeomAPI_ProjectPointOnSurf.hxx>
47 #include <OSD_File.hxx>
48 #include <Precision.hxx>
49 #include <Quantity_Parameter.hxx>
50 #include <Standard_ErrorHandler.hxx>
51 #include <Standard_Failure.hxx>
52 #include <TopExp.hxx>
53 #include <TopExp_Explorer.hxx>
54 #include <TopTools_IndexedMapOfShape.hxx>
55 #include <TopTools_ListIteratorOfListOfShape.hxx>
56 #include <TopoDS.hxx>
57 //#include <BRepClass_FaceClassifier.hxx>
58 //#include <BRepGProp.hxx>
59 //#include <GProp_GProps.hxx>
60
61 #include "utilities.h"
62
63 #ifndef WIN32
64 #include <sys/sysinfo.h>
65 #endif
66
67 //#include <Standard_Stream.hxx>
68
69
70 #define castToNode(n) static_cast<const SMDS_MeshNode *>( n );
71
72 #ifdef _DEBUG_
73 #define DUMP(txt) \
74 //  cout << txt
75 #else
76 #define DUMP(txt)
77 #endif
78
79 extern "C"
80 {
81 #ifndef WNT
82 #include <unistd.h>
83 #include <sys/mman.h>
84 #endif
85 #include <sys/stat.h>
86 #include <fcntl.h>
87 }
88
89 //=============================================================================
90 /*!
91  *  
92  */
93 //=============================================================================
94
95 GHS3DPlugin_GHS3D::GHS3DPlugin_GHS3D(int hypId, int studyId, SMESH_Gen* gen)
96   : SMESH_3D_Algo(hypId, studyId, gen)
97 {
98   MESSAGE("GHS3DPlugin_GHS3D::GHS3DPlugin_GHS3D");
99   _name = "GHS3D_3D";
100   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
101   _onlyUnaryInput = false; // Compute() will be called on a compound of solids
102   _iShape=0;
103   _nbShape=0;
104   _compatibleHypothesis.push_back("GHS3D_Parameters");
105 }
106
107 //=============================================================================
108 /*!
109  *  
110  */
111 //=============================================================================
112
113 GHS3DPlugin_GHS3D::~GHS3DPlugin_GHS3D()
114 {
115   MESSAGE("GHS3DPlugin_GHS3D::~GHS3DPlugin_GHS3D");
116 }
117
118 //=============================================================================
119 /*!
120  *  
121  */
122 //=============================================================================
123
124 bool GHS3DPlugin_GHS3D::CheckHypothesis ( SMESH_Mesh&         aMesh,
125                                           const TopoDS_Shape& aShape,
126                                           Hypothesis_Status&  aStatus )
127 {
128   aStatus = SMESH_Hypothesis::HYP_OK;
129
130   // there is only one compatible Hypothesis so far
131   _hyp = 0;
132   _keepFiles = false;
133   const list <const SMESHDS_Hypothesis * >& hyps = GetUsedHypothesis(aMesh, aShape);
134   if ( !hyps.empty() )
135     _hyp = static_cast<const GHS3DPlugin_Hypothesis*> ( hyps.front() );
136   if ( _hyp )
137     _keepFiles = _hyp->GetKeepFiles();
138
139   return true;
140 }
141
142 //=======================================================================
143 //function : findShape
144 //purpose  : 
145 //=======================================================================
146
147 static TopoDS_Shape findShape(const SMDS_MeshNode *aNode[],
148                               TopoDS_Shape        aShape,
149                               const TopoDS_Shape  shape[],
150                               double**            box,
151                               const int           nShape,
152                               TopAbs_State *      state = 0)
153 {
154   gp_XYZ aPnt(0,0,0);
155   int j, iShape, nbNode = 4;
156
157   for ( j=0; j<nbNode; j++ )
158     aPnt += gp_XYZ( aNode[j]->X(), aNode[j]->Y(), aNode[j]->Z() );
159   aPnt /= nbNode;
160
161   BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
162   if (state) *state = SC.State();
163   if ( SC.State() != TopAbs_IN || aShape.IsNull() || aShape.ShapeType() != TopAbs_SOLID) {
164     for (iShape = 0; iShape < nShape; iShape++) {
165       aShape = shape[iShape];
166       if ( !( aPnt.X() < box[iShape][0] || box[iShape][1] < aPnt.X() ||
167               aPnt.Y() < box[iShape][2] || box[iShape][3] < aPnt.Y() ||
168               aPnt.Z() < box[iShape][4] || box[iShape][5] < aPnt.Z()) ) {
169         BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
170         if (state) *state = SC.State();
171         if (SC.State() == TopAbs_IN)
172           break;
173       }
174     }
175   }
176   return aShape;
177 }
178
179 //=======================================================================
180 //function : readMapIntLine
181 //purpose  : 
182 //=======================================================================
183
184 static char* readMapIntLine(char* ptr, int tab[]) {
185   long int intVal;
186   cout << endl;
187
188   for ( int i=0; i<17; i++ ) {
189     intVal = strtol(ptr, &ptr, 10);
190     if ( i < 3 )
191       tab[i] = intVal;
192   }
193   return ptr;
194 }
195
196 //=======================================================================
197 //function : readLine
198 //purpose  : 
199 //=======================================================================
200
201 #define GHS3DPlugin_BUFLENGTH 256
202 #define GHS3DPlugin_ReadLine(aPtr,aBuf,aFile,aLineNb) \
203 {  aPtr = fgets( aBuf, GHS3DPlugin_BUFLENGTH - 2, aFile ); aLineNb++; DUMP(endl); }
204
205 //=======================================================================
206 //function : countShape
207 //purpose  :
208 //=======================================================================
209
210 template < class Mesh, class Shape >
211 static int countShape( Mesh* mesh, Shape shape ) {
212   TopExp_Explorer expShape ( mesh->ShapeToMesh(), shape );
213   int nbShape = 0;
214   for ( ; expShape.More(); expShape.Next() ) {
215       nbShape++;
216   }
217   return nbShape;
218 }
219
220 //=======================================================================
221 //function : writeFaces
222 //purpose  : 
223 //=======================================================================
224
225 static bool writeFaces (ofstream &            theFile,
226                         SMESHDS_Mesh *        theMesh,
227                         const map <int,int> & theSmdsToGhs3dIdMap)
228 {
229   // record structure:
230   //
231   // NB_ELEMS DUMMY_INT
232   // Loop from 1 to NB_ELEMS
233   // NB_NODES NODE_NB_1 NODE_NB_2 ... (NB_NODES + 1) times: DUMMY_INT
234
235   int nbShape = countShape( theMesh, TopAbs_FACE );
236
237   int *tabID;             tabID    = new int[nbShape];
238   TopoDS_Shape *tabShape; tabShape = new TopoDS_Shape[nbShape];
239   TopoDS_Shape aShape;
240   SMESHDS_SubMesh* theSubMesh;
241   const SMDS_MeshElement* aFace;
242   const char* space    = "  ";
243   const int   dummyint = 0;
244   map<int,int>::const_iterator itOnMap;
245   SMDS_ElemIteratorPtr itOnSubMesh, itOnSubFace;
246   int shapeID, nbNodes, aSmdsID;
247   bool idFound;
248
249   cout << "    " << theMesh->NbFaces() << " shapes of 2D dimension" << endl;
250   cout << endl;
251
252   theFile << space << theMesh->NbFaces() << space << dummyint << endl;
253
254   TopExp_Explorer expface( theMesh->ShapeToMesh(), TopAbs_FACE );
255   for ( int i = 0; expface.More(); expface.Next(), i++ ) {
256     tabID[i] = 0;
257     aShape   = expface.Current();
258     shapeID  = theMesh->ShapeToIndex( aShape );
259     idFound  = false;
260     for ( int j=0; j<=i; j++) {
261       if ( shapeID == tabID[j] ) {
262         idFound = true;
263         break;
264       }
265     }
266     if ( ! idFound ) {
267       tabID[i]    = shapeID;
268       tabShape[i] = aShape;
269     }
270   }
271   for ( int i =0; i < nbShape; i++ ) {
272     if ( tabID[i] != 0 ) {
273       aShape      = tabShape[i];
274       shapeID     = tabID[i];
275       theSubMesh  = theMesh->MeshElements( aShape );
276       if ( !theSubMesh ) continue;
277       itOnSubMesh = theSubMesh->GetElements();
278       while ( itOnSubMesh->more() ) {
279         aFace   = itOnSubMesh->next();
280         nbNodes = aFace->NbNodes();
281
282         theFile << space << nbNodes;
283
284         itOnSubFace = aFace->nodesIterator();
285         while ( itOnSubFace->more() ) {
286           // find GHS3D ID
287           aSmdsID = itOnSubFace->next()->GetID();
288           itOnMap = theSmdsToGhs3dIdMap.find( aSmdsID );
289           ASSERT( itOnMap != theSmdsToGhs3dIdMap.end() );
290
291           theFile << space << (*itOnMap).second;
292         }
293
294         // (NB_NODES + 1) times: DUMMY_INT
295         for ( int j=0; j<=nbNodes; j++)
296           theFile << space << dummyint;
297
298         theFile << endl;
299       }
300     }
301   }
302
303   delete [] tabID;
304   delete [] tabShape;
305
306   return true;
307 }
308
309 //=======================================================================
310 //function : writeFaces
311 //purpose  : Write Faces in case if generate 3D mesh w/o geometry
312 //=======================================================================
313
314 static bool writeFaces (ofstream &            theFile,
315                         SMESHDS_Mesh *        theMesh,
316                         vector <const SMDS_MeshNode*> & theNodeByGhs3dId)
317 {
318   // record structure:
319   //
320   // NB_ELEMS DUMMY_INT
321   // Loop from 1 to NB_ELEMS
322   //   NB_NODES NODE_NB_1 NODE_NB_2 ... (NB_NODES + 1) times: DUMMY_INT
323
324
325   int nbFaces = 0;
326   list< const SMDS_MeshElement* > faces;
327   list< const SMDS_MeshElement* >::iterator f;
328   map< const SMDS_MeshNode*,int >::iterator it;
329   SMDS_ElemIteratorPtr nodeIt;
330   const SMDS_MeshElement* elem;
331   int nbNodes;
332
333   const char* space    = "  ";
334   const int   dummyint = 0;
335
336   //get all faces from mesh
337   SMDS_FaceIteratorPtr eIt = theMesh->facesIterator();
338   while ( eIt->more() ) {
339     const SMDS_MeshElement* elem = eIt->next();
340     if ( !elem )
341       return false;
342     faces.push_back( elem );
343     nbFaces++;
344   }
345
346   if ( nbFaces == 0 )
347     return false;
348   
349   cout << "The initial 2D mesh contains " << nbFaces << " faces and ";
350
351   // NB_ELEMS DUMMY_INT
352   theFile << space << nbFaces << space << dummyint << endl;
353
354   // Loop from 1 to NB_ELEMS
355
356   map<const SMDS_MeshNode*,int> aNodeToGhs3dIdMap;
357   f = faces.begin();
358   for ( ; f != faces.end(); ++f )
359   {
360     // NB_NODES PER FACE
361     elem = *f;
362     nbNodes = elem->NbNodes();
363     theFile << space << nbNodes;
364
365     // NODE_NB_1 NODE_NB_2 ...
366     nodeIt = elem->nodesIterator();
367     while ( nodeIt->more() )
368     {
369       // find GHS3D ID
370       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
371       int newId = aNodeToGhs3dIdMap.size() + 1; // ghs3d ids count from 1
372       it = aNodeToGhs3dIdMap.insert( make_pair( node, newId )).first;
373       theFile << space << it->second;
374     }
375
376     // (NB_NODES + 1) times: DUMMY_INT
377     for ( int i=0; i<=nbNodes; i++)
378       theFile << space << dummyint;
379
380     theFile << endl;
381   }
382
383   // put nodes to theNodeByGhs3dId vector
384   theNodeByGhs3dId.resize( aNodeToGhs3dIdMap.size() );
385   map<const SMDS_MeshNode*,int>::const_iterator n2id = aNodeToGhs3dIdMap.begin();
386   for ( ; n2id != aNodeToGhs3dIdMap.end(); ++ n2id)
387   {
388     theNodeByGhs3dId[ n2id->second - 1 ] = n2id->first; // ghs3d ids count from 1
389   }
390
391   return true;
392 }
393
394 //=======================================================================
395 //function : writePoints
396 //purpose  : 
397 //=======================================================================
398
399 static bool writePoints (ofstream &                       theFile,
400                          SMESHDS_Mesh *                   theMesh,
401                          map <int,int> &                  theSmdsToGhs3dIdMap,
402                          map <int,const SMDS_MeshNode*> & theGhs3dIdToNodeMap)
403 {
404   // record structure:
405   //
406   // NB_NODES
407   // Loop from 1 to NB_NODES
408   //   X Y Z DUMMY_INT
409
410   int nbNodes = theMesh->NbNodes();
411   if ( nbNodes == 0 )
412     return false;
413
414   const char* space    = "  ";
415   const int   dummyint = 0;
416
417   int aGhs3dID = 1;
418   SMDS_NodeIteratorPtr it = theMesh->nodesIterator();
419   const SMDS_MeshNode* node;
420
421   // NB_NODES
422   theFile << space << nbNodes << endl;
423   cout << endl;
424   cout << "The initial 2D mesh contains :" << endl;
425   cout << "    " << nbNodes << " vertices" << endl;
426
427   // Loop from 1 to NB_NODES
428
429   while ( it->more() )
430   {
431     node = it->next();
432     theSmdsToGhs3dIdMap.insert( map <int,int>::value_type( node->GetID(), aGhs3dID ));
433     theGhs3dIdToNodeMap.insert (map <int,const SMDS_MeshNode*>::value_type( aGhs3dID, node ));
434     aGhs3dID++;
435
436     // X Y Z DUMMY_INT
437     theFile
438       << space << node->X()
439       << space << node->Y()
440       << space << node->Z()
441       << space << dummyint;
442
443     theFile << endl;
444   }
445
446   return true;
447 }
448
449 //=======================================================================
450 //function : writePoints
451 //purpose  : 
452 //=======================================================================
453
454 static bool writePoints (ofstream &                            theFile,
455                          SMESHDS_Mesh *                        theMesh,
456                          const vector <const SMDS_MeshNode*> & theNodeByGhs3dId)
457 {
458   // record structure:
459   //
460   // NB_NODES
461   // Loop from 1 to NB_NODES
462   //   X Y Z DUMMY_INT
463
464   //int nbNodes = theMesh->NbNodes();
465   int nbNodes = theNodeByGhs3dId.size();
466   if ( nbNodes == 0 )
467     return false;
468
469   const char* space    = "  ";
470   const int   dummyint = 0;
471
472   const SMDS_MeshNode* node;
473
474   // NB_NODES
475   theFile << space << nbNodes << endl;
476   cout << nbNodes << " nodes" << endl;
477
478   // Loop from 1 to NB_NODES
479
480   vector<const SMDS_MeshNode*>::const_iterator nodeIt = theNodeByGhs3dId.begin();
481   vector<const SMDS_MeshNode*>::const_iterator after  = theNodeByGhs3dId.end();
482   for ( ; nodeIt != after; ++nodeIt )
483   {
484     node = *nodeIt;
485
486     // X Y Z DUMMY_INT
487     theFile
488       << space << node->X()
489       << space << node->Y()
490       << space << node->Z()
491       << space << dummyint;
492
493     theFile << endl;
494   }
495
496   return true;
497 }
498
499 //=======================================================================
500 //function : findShapeID
501 //purpose  : find the solid corresponding to GHS3D sub-domain following
502 //           the technique proposed in GHS3D manual in chapter
503 //           "B.4 Subdomain (sub-region) assignment"
504 //=======================================================================
505
506 static int findShapeID(SMESH_Mesh&          mesh,
507                        const SMDS_MeshNode* node1,
508                        const SMDS_MeshNode* node2,
509                        const SMDS_MeshNode* node3)
510 {
511   const int invalidID = 0;
512   SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
513
514   // face th enodes belong to
515   const SMDS_MeshElement * face = meshDS->FindFace(node1,node2,node3);
516   if ( !face )
517     return invalidID;
518
519   // geom face the face assigned to
520   SMESH_MeshEditor editor(&mesh);
521   int geomFaceID = editor.FindShape( face );
522   if ( !geomFaceID )
523     return invalidID;
524   TopoDS_Shape shape = meshDS->IndexToShape( geomFaceID );
525   if ( shape.IsNull() || shape.ShapeType() != TopAbs_FACE )
526     return invalidID;
527   TopoDS_Face geomFace = TopoDS::Face( shape );
528
529   // solids bounded by geom face
530   TopTools_IndexedMapOfShape solids;
531   TopTools_ListIteratorOfListOfShape ansIt = mesh.GetAncestors(geomFace);
532   for ( ; ansIt.More(); ansIt.Next() ) {
533     if ( ansIt.Value().ShapeType() == TopAbs_SOLID )
534       solids.Add( ansIt.Value() );
535   }
536   // analyse found solids
537   if ( solids.Extent() == 0 )
538     return invalidID;
539   if ( solids.Extent() == 1 )
540     return meshDS->ShapeToIndex( solids(1) );
541
542   // find orientation of geom face within the first solid
543   TopoDS_Shape solid1 = solids(1);
544   TopExp_Explorer fExp( solid1, TopAbs_FACE );
545   for ( ; fExp.More(); fExp.Next() )
546     if ( geomFace.IsSame( fExp.Current() )) {
547       geomFace = TopoDS::Face( fExp.Current() );
548       break;
549     }
550   if ( !fExp.More() )
551     return invalidID; // face not found
552
553   // find UV of node1 on geomFace
554   SMESH_MesherHelper helper( mesh );
555   gp_XY uv = helper.GetNodeUV( geomFace, node1 );
556
557   // check that uv is correct
558   gp_Pnt node1Pnt ( node1->X(), node1->Y(), node1->Z() );
559   double tol = BRep_Tool::Tolerance( geomFace );
560   BRepAdaptor_Surface surface( geomFace );
561   if ( node1Pnt.Distance( surface.Value( uv.X(), uv.Y() )) > 2 * tol ) {
562     // project node1 onto geomFace to get right UV
563     GeomAPI_ProjectPointOnSurf projector( node1Pnt, surface.Surface().Surface() );
564     if ( !projector.IsDone() || projector.NbPoints() < 1 )
565       return invalidID;
566     Quantity_Parameter U,V;
567     projector.LowerDistanceParameters(U,V);
568     uv = gp_XY( U,V );
569   }
570   // normale to face at node1
571   gp_Pnt node2Pnt ( node2->X(), node2->Y(), node2->Z() );
572   gp_Pnt node3Pnt ( node3->X(), node3->Y(), node3->Z() );
573   gp_Vec vec12( node1Pnt, node2Pnt );
574   gp_Vec vec13( node1Pnt, node3Pnt );
575   gp_Vec meshNormal = vec12 ^ vec13;
576   if ( meshNormal.SquareMagnitude() < DBL_MIN )
577     return invalidID;
578   
579   // normale to geomFace at UV
580   gp_Vec du, dv;
581   surface.D1( uv.X(), uv.Y(), node1Pnt, du, dv );
582   gp_Vec geomNormal = du ^ dv;
583   if ( geomNormal.SquareMagnitude() < DBL_MIN )
584     return findShapeID( mesh, node2, node3, node1 );
585   if ( geomFace.Orientation() == TopAbs_REVERSED )
586     geomNormal.Reverse();
587
588   // compare normals
589   bool isReverse = ( meshNormal * geomNormal ) < 0;
590   if ( isReverse )
591     return meshDS->ShapeToIndex( solids(2) );
592   else
593     return meshDS->ShapeToIndex( solid1 );
594 }
595                        
596 //=======================================================================
597 //function : readResultFile
598 //purpose  : 
599 //=======================================================================
600
601 static bool readResultFile(const int                       fileOpen,
602                            SMESH_Mesh&                     theMesh,
603                            TopoDS_Shape                    tabShape[],
604                            double**                        tabBox,
605                            const int                       nbShape,
606                            map <int,const SMDS_MeshNode*>& theGhs3dIdToNodeMap,
607                            bool                            toMeshHoles)
608 {
609   struct stat status;
610   size_t      length;
611
612   char *ptr, *mapPtr;
613   char *tetraPtr;
614   char *shapePtr;
615
616   SMESHDS_Mesh* theMeshDS = theMesh.GetMeshDS();
617
618   int fileStat;
619   int nbElems, nbNodes, nbInputNodes;
620   int nodeId/*, triangleId*/;
621   int nbTriangle;
622   int ID, shapeID, ghs3dShapeID;
623   int IdShapeRef = 1;
624   int compoundID =
625     nbShape ? theMeshDS->ShapeToIndex( tabShape[0] ) : theMeshDS->ShapeToIndex( theMeshDS->ShapeToMesh() );
626
627   int *tab, *tabID, *nodeID, *nodeAssigne;
628   double *coord;
629   const SMDS_MeshNode **node;
630
631   tab    = new int[3];
632   //tabID  = new int[nbShape];
633   nodeID = new int[4];
634   coord  = new double[3];
635   node   = new const SMDS_MeshNode*[4];
636
637   TopoDS_Shape aSolid;
638   SMDS_MeshNode * aNewNode;
639   map <int,const SMDS_MeshNode*>::iterator itOnNode;
640   SMDS_MeshElement* aTet;
641 #ifdef _DEBUG_
642   set<int> shapeIDs;
643 #endif
644
645   // Read the file state
646   fileStat = fstat(fileOpen, &status);
647   length   = status.st_size;
648
649   // Mapping the result file into memory
650   ptr = (char *) mmap(0,length,PROT_READ,MAP_PRIVATE,fileOpen,0);
651   mapPtr = ptr;
652
653   ptr      = readMapIntLine(ptr, tab);
654   tetraPtr = ptr;
655
656   nbElems      = tab[0];
657   nbNodes      = tab[1];
658   nbInputNodes = tab[2];
659
660   nodeAssigne = new int[ nbNodes+1 ];
661
662   if (nbShape > 0)
663     aSolid = tabShape[0];
664
665   // Reading the nodeId
666   for (int i=0; i < 4*nbElems; i++)
667     nodeId = strtol(ptr, &ptr, 10);
668
669   // Reading the nodeCoor and update the nodeMap
670   for (int iNode=1; iNode <= nbNodes; iNode++) {
671     for (int iCoor=0; iCoor < 3; iCoor++)
672       coord[ iCoor ] = strtod(ptr, &ptr);
673     nodeAssigne[ iNode ] = 1;
674     if ( iNode > nbInputNodes ) {
675       nodeAssigne[ iNode ] = 0;
676       aNewNode = theMeshDS->AddNode( coord[0],coord[1],coord[2] );
677       theGhs3dIdToNodeMap.insert(theGhs3dIdToNodeMap.end(), make_pair( iNode, aNewNode ));
678     }
679   }
680
681   // Reading the number of triangles which corresponds to the number of sub-domains
682   nbTriangle = strtol(ptr, &ptr, 10);
683
684   tabID = new int[nbTriangle];
685   for (int i=0; i < nbTriangle; i++) {
686     tabID[i] = 0;
687     // find the solid corresponding to GHS3D sub-domain following
688     // the technique proposed in GHS3D manual in chapter
689     // "B.4 Subdomain (sub-region) assignment"
690     int nodeId1 = strtol(ptr, &ptr, 10);
691     int nodeId2 = strtol(ptr, &ptr, 10);
692     int nodeId3 = strtol(ptr, &ptr, 10);
693     if ( nbTriangle > 1 ) {
694       const SMDS_MeshNode* n1 = theGhs3dIdToNodeMap[ nodeId1 ];
695       const SMDS_MeshNode* n2 = theGhs3dIdToNodeMap[ nodeId2 ];
696       const SMDS_MeshNode* n3 = theGhs3dIdToNodeMap[ nodeId3 ];
697       try {
698         OCC_CATCH_SIGNALS;
699         tabID[i] = findShapeID( theMesh, n1, n2, n3 );
700 #ifdef _DEBUG_
701         cout << i+1 << " subdomain: findShapeID() returns " << tabID[i] << endl;
702 #endif
703       } catch ( Standard_Failure ) {
704       } catch (...) {}
705     }
706   }
707
708   shapePtr = ptr;
709
710   if ( nbTriangle <= nbShape ) // no holes
711     toMeshHoles = true; // not avoid creating tetras in holes
712
713   // Associating the tetrahedrons to the shapes
714   shapeID = compoundID;
715   for (int iElem = 0; iElem < nbElems; iElem++) {
716     for (int iNode = 0; iNode < 4; iNode++) {
717       ID = strtol(tetraPtr, &tetraPtr, 10);
718       itOnNode = theGhs3dIdToNodeMap.find(ID);
719       node[ iNode ] = itOnNode->second;
720       nodeID[ iNode ] = ID;
721     }
722     // We always run GHS3D with "to mesh holes'==TRUE but we must not create
723     // tetras within holes depending on hypo option,
724     // so we first check if aTet is inside a hole and then create it 
725     //aTet = theMeshDS->AddVolume( node[1], node[0], node[2], node[3] );
726     if ( nbTriangle > 1 ) {
727       shapeID = -1; // negative shapeID means not to create tetras if !toMeshHoles
728       ghs3dShapeID = strtol(shapePtr, &shapePtr, 10) - IdShapeRef;
729       if ( tabID[ ghs3dShapeID ] == 0 ) {
730         TopAbs_State state;
731         aSolid = findShape(node, aSolid, tabShape, tabBox, nbShape, &state);
732         if ( toMeshHoles || state == TopAbs_IN )
733           shapeID = theMeshDS->ShapeToIndex( aSolid );
734         tabID[ ghs3dShapeID ] = shapeID;
735       }
736       else
737         shapeID = tabID[ ghs3dShapeID ];
738     }
739     else if ( nbShape > 1 ) {
740       // Case where nbTriangle == 1 while nbShape == 2 encountered
741       // with compound of 2 boxes and "To mesh holes"==False,
742       // so there are no subdomains specified for each tetrahedron.
743       // Try to guess a solid by a node already bound to shape
744       shapeID = 0;
745       for ( int i=0; i<4 && shapeID==0; i++ ) {
746         if ( nodeAssigne[ nodeID[i] ] == 1 &&
747              node[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE &&
748              node[i]->GetPosition()->GetShapeId() > 1 )
749         {
750           shapeID = node[i]->GetPosition()->GetShapeId();
751         }
752       }
753       if ( shapeID==0 ) {
754         aSolid = findShape(node, aSolid, tabShape, tabBox, nbShape);
755         shapeID = theMeshDS->ShapeToIndex( aSolid );
756       }
757     }
758     // set new nodes and tetrahedron onto the shape
759     for ( int i=0; i<4; i++ ) {
760       if ( nodeAssigne[ nodeID[i] ] == 0 ) {
761         if ( shapeID > 0 )
762           theMeshDS->SetNodeInVolume( node[i], shapeID );
763         nodeAssigne[ nodeID[i] ] = shapeID;
764       }
765     }
766     if ( toMeshHoles || shapeID > 0 ) {
767       aTet = theMeshDS->AddVolume( node[1], node[0], node[2], node[3] );
768       theMeshDS->SetMeshElementOnShape( aTet, shapeID );
769     }
770 #ifdef _DEBUG_
771     shapeIDs.insert( shapeID );
772 #endif
773   }
774   // Remove nodes of tetras inside holes if !toMeshHoles
775   if ( !toMeshHoles ) {
776     itOnNode = theGhs3dIdToNodeMap.find( nbInputNodes );
777     for ( ; itOnNode != theGhs3dIdToNodeMap.end(); ++itOnNode) {
778       ID = itOnNode->first;
779       if ( nodeAssigne[ ID ] < 0 )
780         theMeshDS->RemoveFreeNode( itOnNode->second, 0 );
781     }
782   }
783
784   if ( nbElems )
785     cout << nbElems << " tetrahedrons have been associated to " << nbShape << " shapes" << endl;
786   munmap(mapPtr, length);
787   close(fileOpen);
788
789   delete [] tab;
790   delete [] tabID;
791   delete [] nodeID;
792   delete [] coord;
793   delete [] node;
794   delete [] nodeAssigne;
795
796 #ifdef _DEBUG_
797   if ( shapeIDs.size() != nbShape ) {
798     cout << "Only " << shapeIDs.size() << " solids of " << nbShape << " found" << endl;
799     for (int i=0; i<nbShape; i++) {
800       shapeID = theMeshDS->ShapeToIndex( tabShape[i] );
801       if ( shapeIDs.find( shapeID ) == shapeIDs.end() )
802         cout << "  Solid #" << shapeID << " not found" << endl;
803     }
804   }
805 #endif
806
807   return true;
808 }
809
810 //=======================================================================
811 //function : readResultFile
812 //purpose  : 
813 //=======================================================================
814
815 static bool readResultFile(const int                      fileOpen,
816                            SMESHDS_Mesh*                  theMeshDS,
817                            TopoDS_Shape                   aSolid,
818                            vector <const SMDS_MeshNode*>& theNodeByGhs3dId) {
819
820   struct stat  status;
821   size_t       length;
822
823   char *ptr, *mapPtr;
824   char *tetraPtr;
825   char *shapePtr;
826
827   int fileStat;
828   int nbElems, nbNodes, nbInputNodes;
829   int nodeId, triangleId;
830   int nbTriangle;
831   int ID, shapeID;
832
833   int *tab;
834   double *coord;
835   const SMDS_MeshNode **node;
836
837   tab   = new int[3];
838   coord = new double[3];
839   node  = new const SMDS_MeshNode*[4];
840
841   SMDS_MeshNode * aNewNode;
842   map <int,const SMDS_MeshNode*>::iterator IdNode;
843   SMDS_MeshElement* aTet;
844
845   // Read the file state
846   fileStat = fstat(fileOpen, &status);
847   length   = status.st_size;
848
849   // Mapping the result file into memory
850   ptr = (char *) mmap(0,length,PROT_READ,MAP_PRIVATE,fileOpen,0);
851   mapPtr = ptr;
852
853   ptr      = readMapIntLine(ptr, tab);
854   tetraPtr = ptr;
855
856   nbElems      = tab[0];
857   nbNodes      = tab[1];
858   nbInputNodes = tab[2];
859
860   theNodeByGhs3dId.resize( nbNodes );
861
862   // Reading the nodeId
863   for (int i=0; i < 4*nbElems; i++)
864     nodeId = strtol(ptr, &ptr, 10);
865
866   // Reading the nodeCoor and update the nodeMap
867   shapeID = theMeshDS->ShapeToIndex( aSolid );
868   for (int iNode=0; iNode < nbNodes; iNode++) {
869     for (int iCoor=0; iCoor < 3; iCoor++)
870       coord[ iCoor ] = strtod(ptr, &ptr);
871     if ((iNode+1) > nbInputNodes) {
872       aNewNode = theMeshDS->AddNode( coord[0],coord[1],coord[2] );
873       theMeshDS->SetNodeInVolume( aNewNode, shapeID );
874       theNodeByGhs3dId[ iNode ] = aNewNode;
875     }
876   }
877
878   // Reading the triangles
879   nbTriangle = strtol(ptr, &ptr, 10);
880
881   for (int i=0; i < 3*nbTriangle; i++)
882     triangleId = strtol(ptr, &ptr, 10);
883
884   shapePtr = ptr;
885
886   // Associating the tetrahedrons to the shapes
887   for (int iElem = 0; iElem < nbElems; iElem++) {
888     for (int iNode = 0; iNode < 4; iNode++) {
889       ID = strtol(tetraPtr, &tetraPtr, 10);
890       node[ iNode ] = theNodeByGhs3dId[ ID-1 ];
891     }
892     aTet = theMeshDS->AddVolume( node[1], node[0], node[2], node[3] );
893     shapeID = theMeshDS->ShapeToIndex( aSolid );
894     theMeshDS->SetMeshElementOnShape( aTet, shapeID );
895   }
896   if ( nbElems )
897     cout << nbElems << " tetrahedrons have been associated to " << nbTriangle << " shapes" << endl;
898   munmap(mapPtr, length);
899   close(fileOpen);
900
901   delete [] tab;
902   delete [] coord;
903   delete [] node;
904
905   return true;
906 }
907
908 //================================================================================
909 /*!
910  * \brief Look for a line containing a text in a file
911   * \retval bool - true if the line is found
912  */
913 //================================================================================
914
915 static bool findLineContaing(const TCollection_AsciiString& theText,
916                              const TCollection_AsciiString& theFile,
917                              TCollection_AsciiString &      theFoundLine)
918 {
919   bool found = false;
920   if ( FILE * aFile = fopen( theFile.ToCString(), "r" ))
921   {
922     char * aPtr;
923     char aBuffer[ GHS3DPlugin_BUFLENGTH ];
924     int aLineNb = 0;
925     do {
926       GHS3DPlugin_ReadLine( aPtr, aBuffer, aFile, aLineNb );
927       if ( aPtr ) {
928         theFoundLine = aPtr;
929         found = theFoundLine.Search( theText ) >= 0;
930       }
931     } while ( aPtr && !found );
932
933     fclose( aFile );
934   }
935   return found;
936 }
937
938 //================================================================================
939 /*!
940  * \brief Provide human readable text by error code reported by ghs3d
941  */
942 //================================================================================
943
944 static TCollection_AsciiString translateError(const TCollection_AsciiString& errorLine)
945 {
946   int beg = errorLine.Location("ERR ", 1, errorLine.Length());
947   if ( !beg ) return errorLine;
948
949   TCollection_AsciiString errCodeStr = errorLine.SubString( beg + 4 , errorLine.Length());
950   if ( !errCodeStr.IsIntegerValue() )
951     return errorLine;
952   Standard_Integer errCode = errCodeStr.IntegerValue();
953
954   int codeEnd = beg + 7;
955   while ( codeEnd < errorLine.Length() && isdigit( errorLine.Value(codeEnd+1) ))
956     codeEnd++;
957   TCollection_AsciiString error = errorLine.SubString( beg, codeEnd ) + ": ";
958
959   switch ( errCode ) {
960   case 0:
961     return "The surface mesh includes a face of type type other than edge, "
962       "triangle or quadrilateral. This face type is not supported.";
963   case 1:
964     return error + "Not enough memory for the face table";
965   case 2:
966     return error + "Not enough memory";
967   case 3:
968     return error + "Not enough memory";
969   case 4:
970     return error + "Face is ignored";
971   case 5:
972     return error + errorLine.SubString( beg + 5, errorLine.Length()) +
973       ": End of file. Some data are missing in the file.";
974   case 6:
975     return error + errorLine.SubString( beg + 5, errorLine.Length()) +
976       ": Read error on the file. There are wrong data in the file.";
977   case 7:
978     return error + "the metric file is inadequate (dimension other than 3).";
979   case 8:
980     return error + "the metric file is inadequate (values not per vertices).";
981   case 9:
982       return error + "the metric file contains more than one field.";
983   case 10:
984     return error + "the number of values in the \".bb\" (metric file) is incompatible with the expected"
985       "value of number of mesh vertices in the \".noboite\" file.";
986   case 12:
987     return error + "Too many sub-domains";
988   case 13:
989     return error + "the number of vertices is negative or null.";
990   case 14:
991     return error + "the number of faces is negative or null.";
992   case 15:
993     return error + "A facehas a null vertex.";
994   case 22:
995     return error + "incompatible data";
996   case 131:
997     return error + "the number of vertices is negative or null.";
998   case 132:
999     return error + "the number of vertices is negative or null (in the \".mesh\" file).";
1000   case 133:
1001     return error + "the number of faces is negative or null.";
1002   case 1000:
1003     return error + "A face appears more than once in the input surface mesh.";
1004   case 1001:
1005     return error + "An edge appears more than once in the input surface mesh.";
1006   case 1002:
1007     return error + "A face has a vertex negative or null.";
1008   case 1003:
1009     return error + "NOT ENOUGH MEMORY";
1010   case 2000:
1011     return error + "Not enough available memory.";
1012   case 2002:
1013     return error + "Some initial points cannot be inserted. The surface mesh is probably very bad "
1014       "in terms of quality or the input list of points is wrong";
1015   case 2003:
1016     return error + "Some vertices are too close to one another or coincident.";
1017   case 2004:
1018     return error + "Some vertices are too close to one another or coincident.";
1019   case 2012:
1020     return error + "A vertex cannot be inserted.";
1021   case 2014:
1022     return error + "There are at least two points considered as coincident";
1023   case 2103:
1024     return error + "Some vertices are too close to one another or coincident";
1025   case 3000:
1026     return error + "The surface mesh regeneration step has failed";
1027   case 3009:
1028     return error + "Constrained edge cannot be enforced";
1029   case 3019:
1030     return error + "Constrained face cannot be enforced";
1031   case 3029:
1032     return error + "Missing faces";
1033   case 3100:
1034     return error + "No guess to start the definition of the connected component(s)";
1035   case 3101:
1036     return error + "The surface mesh includes at least one hole. The domain is not well defined";
1037   case 3102:
1038     return error + "Impossible to define a component";
1039   case 3103:
1040     return error + "The surface edge intersects another surface edge";
1041   case 3104:
1042     return error + "The surface edge intersects the surface face";
1043   case 3105:
1044     return error + "One boundary point lies within a surface face";
1045   case 3106:
1046     return error + "One surface edge intersects a surface face";
1047   case 3107:
1048     return error + "One boundary point lies within a surface edge";
1049   case 3108:
1050     return error + "Insufficient memory ressources detected due to a bad quality surface mesh leading "
1051       "to too many swaps";
1052   case 3109:
1053     return error + "Edge is unique (i.e., bounds a hole in the surface)";
1054   case 3122:
1055     return error + "Presumably, the surface mesh is not compatible with the domain being processed";
1056   case 3123:
1057     return error + "Too many components, too many sub-domain";
1058   case 3209:
1059     return error + "The surface mesh includes at least one hole. "
1060       "Therefore there is no domain properly defined";
1061   case 3300:
1062     return error + "Statistics.";
1063   case 3400:
1064     return error + "Statistics.";
1065   case 3500:
1066     return error + "Warning, it is dramatically tedious to enforce the boundary items";
1067   case 4000:
1068     return error + "Not enough memory at this time, nevertheless, the program continues. "
1069       "The expected mesh will be correct but not really as large as required";
1070   case 4002:
1071     return error + "see above error code, resulting quality may be poor.";
1072   case 4003:
1073     return error + "Not enough memory at this time, nevertheless, the program continues (warning)";
1074   case 8000:
1075     return error + "Unknown face type.";
1076   case 8005:
1077   case 8006:
1078     return error + errorLine.SubString( beg + 5, errorLine.Length()) +
1079       ": End of file. Some data are missing in the file.";
1080   case 9000:
1081     return error + "A too small volume element is detected";
1082   case 9001:
1083     return error + "There exists at least a null or negative volume element";
1084   case 9002:
1085     return error + "There exist null or negative volume elements";
1086   case 9003:
1087     return error + "A too small volume element is detected. A face is considered being degenerated";
1088   case 9100:
1089     return error + "Some element is suspected to be very bad shaped or wrong";
1090   case 9102:
1091     return error + "A too bad quality face is detected. This face is considered degenerated";
1092   case 9112:
1093     return error + "A too bad quality face is detected. This face is degenerated";
1094   case 9122:
1095     return error + "Presumably, the surface mesh is not compatible with the domain being processed";
1096   case 9999:
1097     return error + "Abnormal error occured, contact hotline";
1098   case 23600:
1099     return error + "Not enough memory for the face table";
1100   case 23601:
1101     return error + "The algorithm cannot run further. "
1102       "The surface mesh is probably very bad in terms of quality.";
1103   case 23602:
1104     return error + "Bad vertex number";
1105   }
1106   return errorLine;
1107 }
1108
1109 //=============================================================================
1110 /*!
1111  *Here we are going to use the GHS3D mesher
1112  */
1113 //=============================================================================
1114
1115 bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
1116                                 const TopoDS_Shape& theShape)
1117 {
1118   bool Ok(false);
1119   SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
1120
1121   _nbShape = countShape( meshDS, TopAbs_SOLID ); // we count the number of shapes
1122
1123   // create bounding box for every shape inside the compound
1124
1125   int iShape = 0;
1126   TopoDS_Shape* tabShape;
1127   double**      tabBox;
1128   tabShape = new TopoDS_Shape[_nbShape];
1129   tabBox   = new double*[_nbShape];
1130   for (int i=0; i<_nbShape; i++)
1131     tabBox[i] = new double[6];
1132   Standard_Real Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
1133
1134   TopExp_Explorer expBox (meshDS->ShapeToMesh(), TopAbs_SOLID);
1135   for (; expBox.More(); expBox.Next()) {
1136     tabShape[iShape] = expBox.Current();
1137     Bnd_Box BoundingBox;
1138     BRepBndLib::Add(expBox.Current(), BoundingBox);
1139     BoundingBox.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
1140     tabBox[iShape][0] = Xmin; tabBox[iShape][1] = Xmax;
1141     tabBox[iShape][2] = Ymin; tabBox[iShape][3] = Ymax;
1142     tabBox[iShape][4] = Zmin; tabBox[iShape][5] = Zmax;
1143     iShape++;
1144   }
1145
1146   // a unique working file name
1147   // to avoid access to the same files by eg different users
1148   TCollection_AsciiString aGenericName
1149     = (char*) GHS3DPlugin_Hypothesis::GetFileName(_hyp).c_str();
1150
1151   TCollection_AsciiString aFacesFileName, aPointsFileName, aResultFileName;
1152   TCollection_AsciiString aBadResFileName, aBbResFileName, aLogFileName;
1153   aFacesFileName  = aGenericName + ".faces";  // in faces
1154   aPointsFileName = aGenericName + ".points"; // in points
1155   aResultFileName = aGenericName + ".noboite";// out points and volumes
1156   aBadResFileName = aGenericName + ".boite";  // out bad result
1157   aBbResFileName  = aGenericName + ".bb";     // out vertex stepsize
1158   aLogFileName    = aGenericName + ".log";    // log
1159
1160   // -----------------
1161   // make input files
1162   // -----------------
1163
1164   ofstream aFacesFile  ( aFacesFileName.ToCString()  , ios::out);
1165   ofstream aPointsFile ( aPointsFileName.ToCString() , ios::out);
1166
1167   Ok =
1168 #ifdef WIN32
1169     aFacesFile->is_open() && aPointsFile->is_open();
1170 #else
1171     aFacesFile.rdbuf()->is_open() && aPointsFile.rdbuf()->is_open();
1172 #endif
1173   if (!Ok) {
1174     INFOS( "Can't write into " << aFacesFileName);
1175     return error(SMESH_Comment("Can't write into ") << aFacesFileName);
1176   }
1177   map <int,int> aSmdsToGhs3dIdMap;
1178   map <int,const SMDS_MeshNode*> aGhs3dIdToNodeMap;
1179
1180   Ok = writePoints( aPointsFile, meshDS, aSmdsToGhs3dIdMap, aGhs3dIdToNodeMap ) &&
1181        writeFaces ( aFacesFile,  meshDS, aSmdsToGhs3dIdMap );
1182
1183   aFacesFile.close();
1184   aPointsFile.close();
1185
1186   if ( ! Ok ) {
1187     if ( !_keepFiles ) {
1188       OSD_File( aFacesFileName ).Remove();
1189       OSD_File( aPointsFileName ).Remove();
1190     }
1191     return error(COMPERR_BAD_INPUT_MESH);
1192   }
1193   OSD_File( aResultFileName ).Remove(); // needed for boundary recovery module usage
1194
1195   // -----------------
1196   // run ghs3d mesher
1197   // -----------------
1198
1199   TCollection_AsciiString cmd( (char*)GHS3DPlugin_Hypothesis::CommandToRun( _hyp ).c_str() );
1200   cmd += TCollection_AsciiString(" -f ") + aGenericName;  // file to read
1201   cmd += TCollection_AsciiString(" 1>" ) + aLogFileName;  // dump into file
1202
1203   cout << endl;
1204   cout << "Ghs3d execution..." << endl;
1205   cout << cmd << endl;
1206
1207   system( cmd.ToCString() ); // run
1208
1209   cout << endl;
1210   cout << "End of Ghs3d execution !" << endl;
1211
1212   // --------------
1213   // read a result
1214   // --------------
1215
1216   // Mapping the result file
1217
1218   int fileOpen;
1219   fileOpen = open( aResultFileName.ToCString(), O_RDONLY);
1220   if ( fileOpen < 0 ) {
1221     cout << endl;
1222     cout << "Can't open the " << aResultFileName.ToCString() << " GHS3D output file" << endl;
1223     Ok = false;
1224   }
1225   else {
1226     bool toMeshHoles =
1227       _hyp ? _hyp->GetToMeshHoles(true) : GHS3DPlugin_Hypothesis::DefaultMeshHoles();
1228     Ok = readResultFile( fileOpen, theMesh, tabShape, tabBox, _nbShape, aGhs3dIdToNodeMap,
1229                          toMeshHoles );
1230   }
1231
1232   // ---------------------
1233   // remove working files
1234   // ---------------------
1235
1236   if ( Ok )
1237   {
1238     if ( !_keepFiles )
1239       OSD_File( aLogFileName ).Remove();
1240   }
1241   else if ( OSD_File( aLogFileName ).Size() > 0 )
1242   {
1243     INFOS( "GHS3D Error, see the " << aLogFileName.ToCString() << " file" );
1244
1245     // get problem description from the log file
1246     SMESH_Comment comment;
1247     TCollection_AsciiString foundLine;
1248     if ( findLineContaing( "has expired",aLogFileName,foundLine) &&
1249          foundLine.Search("Licence") >= 0)
1250     {
1251       foundLine.LeftAdjust();
1252       comment << foundLine;
1253     }
1254     if ( findLineContaing( "%% ERROR",aLogFileName,foundLine) ||
1255          findLineContaing( " ERR ",aLogFileName,foundLine))
1256     {
1257       foundLine.LeftAdjust();
1258       comment << translateError( foundLine );
1259     }
1260     else if ( findLineContaing( "%% NO SAVING OPERATION",aLogFileName,foundLine))
1261     {
1262       comment << "Too many elements generated for a trial version.\n";
1263     }
1264     if ( comment.empty() )
1265       comment << "See " << aLogFileName << " for problem description";
1266     else
1267       comment << "\nSee " << aLogFileName << " for more information";
1268     error(COMPERR_ALGO_FAILED, comment);
1269   }
1270   else
1271   {
1272     // the log file is empty
1273     OSD_File( aLogFileName ).Remove();
1274     INFOS( "GHS3D Error, command '" << cmd.ToCString() << "' failed" );
1275     error(COMPERR_ALGO_FAILED, "ghs3d: command not found" );
1276   }
1277
1278   if ( !_keepFiles ) {
1279     OSD_File( aFacesFileName ).Remove();
1280     OSD_File( aPointsFileName ).Remove();
1281     OSD_File( aResultFileName ).Remove();
1282     OSD_File( aBadResFileName ).Remove();
1283     OSD_File( aBbResFileName ).Remove();
1284   }
1285   cout << "<" << aResultFileName.ToCString() << "> GHS3D output file ";
1286   if ( !Ok )
1287     cout << "not ";
1288   cout << "treated !" << endl;
1289   cout << endl;
1290
1291   _nbShape = 0;    // re-initializing _nbShape for the next Compute() method call
1292   delete [] tabShape;
1293   delete [] tabBox;
1294
1295   return Ok;
1296 }
1297
1298 //=============================================================================
1299 /*!
1300  *Here we are going to use the GHS3D mesher w/o geometry
1301  */
1302 //=============================================================================
1303 bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
1304                                 SMESH_MesherHelper* aHelper)
1305 {
1306   MESSAGE("GHS3DPlugin_GHS3D::Compute()");
1307
1308   SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
1309   TopoDS_Shape theShape = aHelper->GetSubShape();
1310
1311   // a unique working file name
1312   // to avoid access to the same files by eg different users
1313   TCollection_AsciiString aGenericName
1314     = (char*) GHS3DPlugin_Hypothesis::GetFileName(_hyp).c_str();
1315
1316   TCollection_AsciiString aFacesFileName, aPointsFileName, aResultFileName;
1317   TCollection_AsciiString aBadResFileName, aBbResFileName, aLogFileName;
1318   aFacesFileName  = aGenericName + ".faces";  // in faces
1319   aPointsFileName = aGenericName + ".points"; // in points
1320   aResultFileName = aGenericName + ".noboite";// out points and volumes
1321   aBadResFileName = aGenericName + ".boite";  // out bad result
1322   aBbResFileName  = aGenericName + ".bb";     // out vertex stepsize
1323   aLogFileName    = aGenericName + ".log";    // log
1324
1325   // -----------------
1326   // make input files
1327   // -----------------
1328
1329   ofstream aFacesFile  ( aFacesFileName.ToCString()  , ios::out);
1330   ofstream aPointsFile  ( aPointsFileName.ToCString()  , ios::out);
1331   bool Ok =
1332 #ifdef WIN32
1333     aFacesFile->is_open() && aPointsFile->is_open();
1334 #else
1335     aFacesFile.rdbuf()->is_open() && aPointsFile.rdbuf()->is_open();
1336 #endif
1337
1338   if (!Ok)
1339     return error( SMESH_Comment("Can't write into ") << aPointsFileName);
1340
1341   vector <const SMDS_MeshNode*> aNodeByGhs3dId;
1342
1343   Ok = (writeFaces ( aFacesFile, meshDS, aNodeByGhs3dId ) &&
1344         writePoints( aPointsFile, meshDS, aNodeByGhs3dId));
1345   
1346   aFacesFile.close();
1347   aPointsFile.close();
1348   
1349   if ( ! Ok ) {
1350     if ( !_keepFiles ) {
1351       OSD_File( aFacesFileName ).Remove();
1352       OSD_File( aPointsFileName ).Remove();
1353     }
1354     return error(COMPERR_BAD_INPUT_MESH);
1355   }
1356   OSD_File( aResultFileName ).Remove(); // needed for boundary recovery module usage
1357
1358   // -----------------
1359   // run ghs3d mesher
1360   // -----------------
1361
1362   TCollection_AsciiString cmd =
1363     (char*)GHS3DPlugin_Hypothesis::CommandToRun( _hyp, false ).c_str();
1364   cmd += TCollection_AsciiString(" -f ") + aGenericName;  // file to read
1365   cmd += TCollection_AsciiString(" 1>" ) + aLogFileName;  // dump into file
1366   
1367   system( cmd.ToCString() ); // run
1368
1369   // --------------
1370   // read a result
1371   // --------------
1372   int fileOpen;
1373   fileOpen = open( aResultFileName.ToCString(), O_RDONLY);
1374   if ( fileOpen < 0 ) {
1375     cout << endl;
1376     cout << "Error when opening the " << aResultFileName.ToCString() << " file" << endl;
1377     cout << endl;
1378     Ok = false;
1379   }
1380   else {
1381     Ok = readResultFile( fileOpen, meshDS, theShape ,aNodeByGhs3dId );
1382   }
1383   
1384   // ---------------------
1385   // remove working files
1386   // ---------------------
1387
1388   if ( Ok )
1389   {
1390     if ( !_keepFiles )
1391       OSD_File( aLogFileName ).Remove();
1392   }
1393   else if ( OSD_File( aLogFileName ).Size() > 0 )
1394   {
1395     INFOS( "GHS3D Error, see the " << aLogFileName.ToCString() << " file" );
1396
1397     // get problem description from the log file
1398     SMESH_Comment comment;
1399     TCollection_AsciiString foundLine;
1400     if ( findLineContaing( "has expired",aLogFileName,foundLine) &&
1401          foundLine.Search("Licence") >= 0)
1402     {
1403       foundLine.LeftAdjust();
1404       comment << foundLine;
1405     }
1406     if ( findLineContaing( "%% ERROR",aLogFileName,foundLine) ||
1407          findLineContaing( " ERR ",aLogFileName,foundLine))
1408     {
1409       foundLine.LeftAdjust();
1410       comment << translateError( foundLine );
1411     }
1412     else if ( findLineContaing( "%% NO SAVING OPERATION",aLogFileName,foundLine))
1413     {
1414       comment << "Too many elements generated for a trial version.\n";
1415     }
1416     if ( comment.empty() )
1417       comment << "See " << aLogFileName << " for problem description";
1418     else
1419       comment << "\nSee " << aLogFileName << " for more information";
1420     error(COMPERR_ALGO_FAILED, comment);
1421   }
1422   else {
1423     // the log file is empty
1424     OSD_File( aLogFileName ).Remove();
1425     INFOS( "GHS3D Error, command '" << cmd.ToCString() << "' failed" );
1426     error(COMPERR_ALGO_FAILED, "ghs3d: command not found" );
1427   }
1428
1429   if ( !_keepFiles )
1430   {
1431     OSD_File( aFacesFileName ).Remove();
1432     OSD_File( aPointsFileName ).Remove();
1433     OSD_File( aResultFileName ).Remove();
1434     OSD_File( aBadResFileName ).Remove();
1435     OSD_File( aBbResFileName ).Remove();
1436   }
1437   
1438   return Ok;
1439 }