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