Salome HOME
0020042: EDF 864 SMESH: Mesh of holes (GHS3D/BLSurf)
[plugins/ghs3dplugin.git] / src / GHS3DPlugin_GHS3D.cxx
1 //  Copyright (C) 2004-2008  CEA/DEN, EDF R&D
2 //
3 //  This library is free software; you can redistribute it and/or
4 //  modify it under the terms of the GNU Lesser General Public
5 //  License as published by the Free Software Foundation; either
6 //  version 2.1 of the License.
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 // $Header$
25 //=============================================================================
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 #include "SMDS_FaceOfNodes.hxx"
41 #include "SMDS_VolumeOfNodes.hxx"
42
43 #include <BRepAdaptor_Surface.hxx>
44 #include <BRepBndLib.hxx>
45 #include <BRepClass3d_SolidClassifier.hxx>
46 #include <BRepTools.hxx>
47 #include <BRep_Tool.hxx>
48 #include <Bnd_Box.hxx>
49 #include <GeomAPI_ProjectPointOnSurf.hxx>
50 #include <OSD_File.hxx>
51 #include <Precision.hxx>
52 #include <Quantity_Parameter.hxx>
53 #include <Standard_ErrorHandler.hxx>
54 #include <Standard_Failure.hxx>
55 #include <TopExp.hxx>
56 #include <TopExp_Explorer.hxx>
57 #include <TopTools_IndexedMapOfShape.hxx>
58 #include <TopTools_ListIteratorOfListOfShape.hxx>
59 #include <TopoDS.hxx>
60 //#include <BRepClass_FaceClassifier.hxx>
61 //#include <BRepGProp.hxx>
62 //#include <GProp_GProps.hxx>
63
64 #include "utilities.h"
65
66 #ifndef WIN32
67 #include <sys/sysinfo.h>
68 #endif
69
70 //#include <Standard_Stream.hxx>
71
72
73 #define castToNode(n) static_cast<const SMDS_MeshNode *>( n );
74
75 #ifdef _DEBUG_
76 #define DUMP(txt) \
77 //  cout << txt
78 #else
79 #define DUMP(txt)
80 #endif
81
82 extern "C"
83 {
84 #ifndef WNT
85 #include <unistd.h>
86 #include <sys/mman.h>
87 #endif
88 #include <sys/stat.h>
89 #include <fcntl.h>
90 }
91
92 #define HOLE_ID -1
93
94 //=============================================================================
95 /*!
96  *  
97  */
98 //=============================================================================
99
100 GHS3DPlugin_GHS3D::GHS3DPlugin_GHS3D(int hypId, int studyId, SMESH_Gen* gen)
101   : SMESH_3D_Algo(hypId, studyId, gen)
102 {
103   MESSAGE("GHS3DPlugin_GHS3D::GHS3DPlugin_GHS3D");
104   _name = "GHS3D_3D";
105   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
106   _onlyUnaryInput = false; // Compute() will be called on a compound of solids
107   _iShape=0;
108   _nbShape=0;
109   _compatibleHypothesis.push_back("GHS3D_Parameters");
110   _requireShape = false; // can work without shape
111 }
112
113 //=============================================================================
114 /*!
115  *  
116  */
117 //=============================================================================
118
119 GHS3DPlugin_GHS3D::~GHS3DPlugin_GHS3D()
120 {
121   MESSAGE("GHS3DPlugin_GHS3D::~GHS3DPlugin_GHS3D");
122 }
123
124 //=============================================================================
125 /*!
126  *  
127  */
128 //=============================================================================
129
130 bool GHS3DPlugin_GHS3D::CheckHypothesis ( SMESH_Mesh&         aMesh,
131                                           const TopoDS_Shape& aShape,
132                                           Hypothesis_Status&  aStatus )
133 {
134   aStatus = SMESH_Hypothesis::HYP_OK;
135
136   // there is only one compatible Hypothesis so far
137   _hyp = 0;
138   _keepFiles = false;
139   const list <const SMESHDS_Hypothesis * >& hyps = GetUsedHypothesis(aMesh, aShape);
140   if ( !hyps.empty() )
141     _hyp = static_cast<const GHS3DPlugin_Hypothesis*> ( hyps.front() );
142   if ( _hyp )
143     _keepFiles = _hyp->GetKeepFiles();
144
145   return true;
146 }
147
148 //=======================================================================
149 //function : findShape
150 //purpose  : 
151 //=======================================================================
152
153 static TopoDS_Shape findShape(const SMDS_MeshNode *aNode[],
154                               TopoDS_Shape        aShape,
155                               const TopoDS_Shape  shape[],
156                               double**            box,
157                               const int           nShape,
158                               TopAbs_State *      state = 0)
159 {
160   gp_XYZ aPnt(0,0,0);
161   int j, iShape, nbNode = 4;
162
163   for ( j=0; j<nbNode; j++ )
164     aPnt += gp_XYZ( aNode[j]->X(), aNode[j]->Y(), aNode[j]->Z() );
165   aPnt /= nbNode;
166
167   BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
168   if (state) *state = SC.State();
169   if ( SC.State() != TopAbs_IN || aShape.IsNull() || aShape.ShapeType() != TopAbs_SOLID) {
170     for (iShape = 0; iShape < nShape; iShape++) {
171       aShape = shape[iShape];
172       if ( !( aPnt.X() < box[iShape][0] || box[iShape][1] < aPnt.X() ||
173               aPnt.Y() < box[iShape][2] || box[iShape][3] < aPnt.Y() ||
174               aPnt.Z() < box[iShape][4] || box[iShape][5] < aPnt.Z()) ) {
175         BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
176         if (state) *state = SC.State();
177         if (SC.State() == TopAbs_IN)
178           break;
179       }
180     }
181   }
182   return aShape;
183 }
184
185 //=======================================================================
186 //function : readMapIntLine
187 //purpose  : 
188 //=======================================================================
189
190 static char* readMapIntLine(char* ptr, int tab[]) {
191   long int intVal;
192   cout << endl;
193
194   for ( int i=0; i<17; i++ ) {
195     intVal = strtol(ptr, &ptr, 10);
196     if ( i < 3 )
197       tab[i] = intVal;
198   }
199   return ptr;
200 }
201
202 //=======================================================================
203 //function : countShape
204 //purpose  :
205 //=======================================================================
206
207 template < class Mesh, class Shape >
208 static int countShape( Mesh* mesh, Shape shape ) {
209   TopExp_Explorer expShape ( mesh->ShapeToMesh(), shape );
210   int nbShape = 0;
211   for ( ; expShape.More(); expShape.Next() ) {
212       nbShape++;
213   }
214   return nbShape;
215 }
216
217 //=======================================================================
218 //function : writeFaces
219 //purpose  : 
220 //=======================================================================
221
222 static bool writeFaces (ofstream &            theFile,
223                         SMESHDS_Mesh *        theMesh,
224                         const map <int,int> & theSmdsToGhs3dIdMap)
225 {
226   // record structure:
227   //
228   // NB_ELEMS DUMMY_INT
229   // Loop from 1 to NB_ELEMS
230   // NB_NODES NODE_NB_1 NODE_NB_2 ... (NB_NODES + 1) times: DUMMY_INT
231
232   int nbShape = countShape( theMesh, TopAbs_FACE );
233
234   int *tabID;             tabID    = new int[nbShape];
235   TopoDS_Shape *tabShape; tabShape = new TopoDS_Shape[nbShape];
236   TopoDS_Shape aShape;
237   SMESHDS_SubMesh* theSubMesh;
238   const SMDS_MeshElement* aFace;
239   const char* space    = "  ";
240   const int   dummyint = 0;
241   map<int,int>::const_iterator itOnMap;
242   SMDS_ElemIteratorPtr itOnSubMesh, itOnSubFace;
243   int shapeID, nbNodes, aSmdsID;
244   bool idFound;
245
246   cout << "    " << theMesh->NbFaces() << " shapes of 2D dimension" << endl;
247   cout << endl;
248
249   theFile << space << theMesh->NbFaces() << space << dummyint << endl;
250
251   TopExp_Explorer expface( theMesh->ShapeToMesh(), TopAbs_FACE );
252   for ( int i = 0; expface.More(); expface.Next(), i++ ) {
253     tabID[i] = 0;
254     aShape   = expface.Current();
255     shapeID  = theMesh->ShapeToIndex( aShape );
256     idFound  = false;
257     for ( int j=0; j<=i; j++) {
258       if ( shapeID == tabID[j] ) {
259         idFound = true;
260         break;
261       }
262     }
263     if ( ! idFound ) {
264       tabID[i]    = shapeID;
265       tabShape[i] = aShape;
266     }
267   }
268   for ( int i =0; i < nbShape; i++ ) {
269     if ( tabID[i] != 0 ) {
270       aShape      = tabShape[i];
271       shapeID     = tabID[i];
272       theSubMesh  = theMesh->MeshElements( aShape );
273       if ( !theSubMesh ) continue;
274       itOnSubMesh = theSubMesh->GetElements();
275       while ( itOnSubMesh->more() ) {
276         aFace   = itOnSubMesh->next();
277         nbNodes = aFace->NbNodes();
278
279         theFile << space << nbNodes;
280
281         itOnSubFace = aFace->nodesIterator();
282         while ( itOnSubFace->more() ) {
283           // find GHS3D ID
284           aSmdsID = itOnSubFace->next()->GetID();
285           itOnMap = theSmdsToGhs3dIdMap.find( aSmdsID );
286           ASSERT( itOnMap != theSmdsToGhs3dIdMap.end() );
287
288           theFile << space << (*itOnMap).second;
289         }
290
291         // (NB_NODES + 1) times: DUMMY_INT
292         for ( int j=0; j<=nbNodes; j++)
293           theFile << space << dummyint;
294
295         theFile << endl;
296       }
297     }
298   }
299
300   delete [] tabID;
301   delete [] tabShape;
302
303   return true;
304 }
305
306 //=======================================================================
307 //function : writeFaces
308 //purpose  : Write Faces in case if generate 3D mesh w/o geometry
309 //=======================================================================
310
311 static bool writeFaces (ofstream &            theFile,
312                         SMESHDS_Mesh *        theMesh,
313                         vector <const SMDS_MeshNode*> & theNodeByGhs3dId)
314 {
315   // record structure:
316   //
317   // NB_ELEMS DUMMY_INT
318   // Loop from 1 to NB_ELEMS
319   //   NB_NODES NODE_NB_1 NODE_NB_2 ... (NB_NODES + 1) times: DUMMY_INT
320
321
322   int nbFaces = 0;
323   list< const SMDS_MeshElement* > faces;
324   list< const SMDS_MeshElement* >::iterator f;
325   map< const SMDS_MeshNode*,int >::iterator it;
326   SMDS_ElemIteratorPtr nodeIt;
327   const SMDS_MeshElement* elem;
328   int nbNodes;
329
330   const char* space    = "  ";
331   const int   dummyint = 0;
332
333   //get all faces from mesh
334   SMDS_FaceIteratorPtr eIt = theMesh->facesIterator();
335   while ( eIt->more() ) {
336     const SMDS_MeshElement* elem = eIt->next();
337     if ( !elem )
338       return false;
339     faces.push_back( elem );
340     nbFaces++;
341   }
342
343   if ( nbFaces == 0 )
344     return false;
345   
346   cout << "The initial 2D mesh contains " << nbFaces << " faces and ";
347
348   // NB_ELEMS DUMMY_INT
349   theFile << space << nbFaces << space << dummyint << endl;
350
351   // Loop from 1 to NB_ELEMS
352
353   map<const SMDS_MeshNode*,int> aNodeToGhs3dIdMap;
354   f = faces.begin();
355   for ( ; f != faces.end(); ++f )
356   {
357     // NB_NODES PER FACE
358     elem = *f;
359     nbNodes = elem->NbNodes();
360     theFile << space << nbNodes;
361
362     // NODE_NB_1 NODE_NB_2 ...
363     nodeIt = elem->nodesIterator();
364     while ( nodeIt->more() )
365     {
366       // find GHS3D ID
367       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
368       int newId = aNodeToGhs3dIdMap.size() + 1; // ghs3d ids count from 1
369       it = aNodeToGhs3dIdMap.insert( make_pair( node, newId )).first;
370       theFile << space << it->second;
371     }
372
373     // (NB_NODES + 1) times: DUMMY_INT
374     for ( int i=0; i<=nbNodes; i++)
375       theFile << space << dummyint;
376
377     theFile << endl;
378   }
379
380   // put nodes to theNodeByGhs3dId vector
381   theNodeByGhs3dId.resize( aNodeToGhs3dIdMap.size() );
382   map<const SMDS_MeshNode*,int>::const_iterator n2id = aNodeToGhs3dIdMap.begin();
383   for ( ; n2id != aNodeToGhs3dIdMap.end(); ++ n2id)
384   {
385     theNodeByGhs3dId[ n2id->second - 1 ] = n2id->first; // ghs3d ids count from 1
386   }
387
388   return true;
389 }
390
391 //=======================================================================
392 //function : writePoints
393 //purpose  : 
394 //=======================================================================
395
396 static bool writePoints (ofstream &                       theFile,
397                          SMESHDS_Mesh *                   theMesh,
398                          map <int,int> &                  theSmdsToGhs3dIdMap,
399                          map <int,const SMDS_MeshNode*> & theGhs3dIdToNodeMap)
400 {
401   // record structure:
402   //
403   // NB_NODES
404   // Loop from 1 to NB_NODES
405   //   X Y Z DUMMY_INT
406
407   int nbNodes = theMesh->NbNodes();
408   if ( nbNodes == 0 )
409     return false;
410
411   const char* space    = "  ";
412   const int   dummyint = 0;
413
414   int aGhs3dID = 1;
415   SMDS_NodeIteratorPtr it = theMesh->nodesIterator();
416   const SMDS_MeshNode* node;
417
418   // NB_NODES
419   theFile << space << nbNodes << endl;
420   cout << endl;
421   cout << "The initial 2D mesh contains :" << endl;
422   cout << "    " << nbNodes << " vertices" << endl;
423
424   // Loop from 1 to NB_NODES
425
426   while ( it->more() )
427   {
428     node = it->next();
429     theSmdsToGhs3dIdMap.insert( make_pair( node->GetID(), aGhs3dID ));
430     theGhs3dIdToNodeMap.insert( make_pair( aGhs3dID, node ));
431     aGhs3dID++;
432
433     // X Y Z DUMMY_INT
434     theFile
435       << space << node->X()
436       << space << node->Y()
437       << space << node->Z()
438       << space << dummyint;
439
440     theFile << endl;
441   }
442
443   return true;
444 }
445
446 //=======================================================================
447 //function : writePoints
448 //purpose  : 
449 //=======================================================================
450
451 static bool writePoints (ofstream &                            theFile,
452                          SMESHDS_Mesh *                        theMesh,
453                          const vector <const SMDS_MeshNode*> & theNodeByGhs3dId)
454 {
455   // record structure:
456   //
457   // NB_NODES
458   // Loop from 1 to NB_NODES
459   //   X Y Z DUMMY_INT
460
461   //int nbNodes = theMesh->NbNodes();
462   int nbNodes = theNodeByGhs3dId.size();
463   if ( nbNodes == 0 )
464     return false;
465
466   const char* space    = "  ";
467   const int   dummyint = 0;
468
469   const SMDS_MeshNode* node;
470
471   // NB_NODES
472   theFile << space << nbNodes << endl;
473   cout << nbNodes << " nodes" << endl;
474
475   // Loop from 1 to NB_NODES
476
477   vector<const SMDS_MeshNode*>::const_iterator nodeIt = theNodeByGhs3dId.begin();
478   vector<const SMDS_MeshNode*>::const_iterator after  = theNodeByGhs3dId.end();
479   for ( ; nodeIt != after; ++nodeIt )
480   {
481     node = *nodeIt;
482
483     // X Y Z DUMMY_INT
484     theFile
485       << space << node->X()
486       << space << node->Y()
487       << space << node->Z()
488       << space << dummyint;
489
490     theFile << endl;
491   }
492
493   return true;
494 }
495
496 //=======================================================================
497 //function : findShapeID
498 //purpose  : find the solid corresponding to GHS3D sub-domain following
499 //           the technique proposed in GHS3D manual in chapter
500 //           "B.4 Subdomain (sub-region) assignment"
501 //=======================================================================
502
503 static int findShapeID(SMESH_Mesh&          mesh,
504                        const SMDS_MeshNode* node1,
505                        const SMDS_MeshNode* node2,
506                        const SMDS_MeshNode* node3,
507                        const bool           toMeshHoles)
508 {
509   const int invalidID = 0;
510   SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
511
512   // face th enodes belong to
513   const SMDS_MeshElement * face = meshDS->FindFace(node1,node2,node3);
514   if ( !face )
515     return invalidID;
516
517   // geom face the face assigned to
518   SMESH_MeshEditor editor(&mesh);
519   int geomFaceID = editor.FindShape( face );
520   if ( !geomFaceID )
521     return invalidID;
522   TopoDS_Shape shape = meshDS->IndexToShape( geomFaceID );
523   if ( shape.IsNull() || shape.ShapeType() != TopAbs_FACE )
524     return invalidID;
525   TopoDS_Face geomFace = TopoDS::Face( shape );
526
527   // solids bounded by geom face
528   TopTools_IndexedMapOfShape solids, shells;
529   TopTools_ListIteratorOfListOfShape ansIt = mesh.GetAncestors(geomFace);
530   for ( ; ansIt.More(); ansIt.Next() ) {
531     switch ( ansIt.Value().ShapeType() ) {
532     case TopAbs_SOLID:
533       solids.Add( ansIt.Value() ); break;
534     case TopAbs_SHELL:
535       shells.Add( ansIt.Value() ); break;
536     default:;
537     }
538   }
539   // analyse found solids
540   if ( solids.Extent() == 0 || shells.Extent() == 0)
541     return invalidID;
542
543   const TopoDS_Solid& solid1 = TopoDS::Solid( solids(1) );
544   if ( solids.Extent() == 1 )
545   {
546     if ( toMeshHoles )
547       return meshDS->ShapeToIndex( solid1 );
548
549     // - Are we at a hole boundary face?
550     if ( shells(1).IsSame( BRepTools::OuterShell( solid1 )) )
551     { // - No, but maybe a hole is bound by two shapes? Does shells(1) touches another shell?
552       bool touch = false;
553       TopExp_Explorer eExp( shells(1), TopAbs_EDGE );
554       // check if any edge of shells(1) belongs to another shell
555       for ( ; eExp.More() && !touch; eExp.Next() ) {
556         ansIt = mesh.GetAncestors( eExp.Current() );
557         for ( ; ansIt.More() && !touch; ansIt.Next() ) {
558           if ( ansIt.Value().ShapeType() == TopAbs_SHELL )
559             touch = ( !ansIt.Value().IsSame( shells(1) ));
560         }
561       }
562       if (!touch)
563         return meshDS->ShapeToIndex( solid1 );
564     }
565   }
566   // find orientation of geom face within the first solid
567   TopExp_Explorer fExp( solid1, TopAbs_FACE );
568   for ( ; fExp.More(); fExp.Next() )
569     if ( geomFace.IsSame( fExp.Current() )) {
570       geomFace = TopoDS::Face( fExp.Current() );
571       break;
572     }
573   if ( !fExp.More() )
574     return invalidID; // face not found
575
576   // find UV of the center of triangle on geomFace
577   SMESH_MesherHelper helper( mesh );
578   BRepAdaptor_Surface surface( geomFace );
579   gp_XY UV(0,0);
580   const SMDS_MeshNode* nodes[3] = { node1, node2, node3 };
581   const SMDS_MeshNode* nNotOnSeamEdge = 0;
582   for ( int n = 0; !nNotOnSeamEdge && n < 3; ++n )
583     if ( !helper.IsSeamShape( nodes[n]->GetPosition()->GetShapeId() ))
584       nNotOnSeamEdge = nodes[n];
585   for ( int n = 0; n < 3; ++n )
586   {
587     const SMDS_MeshNode* node = nodes[n];
588     gp_XY uv = helper.GetNodeUV( geomFace, node, nNotOnSeamEdge );
589
590     // check that uv is correct
591     gp_Pnt nodePnt ( node->X(), node->Y(), node->Z() );
592     double tol = BRep_Tool::Tolerance( geomFace );
593     if ( nodePnt.Distance( surface.Value( uv.X(), uv.Y() )) > 2 * tol ) {
594       // project node onto geomFace to get right UV
595       GeomAPI_ProjectPointOnSurf projector( nodePnt, surface.Surface().Surface() );
596       if ( !projector.IsDone() || projector.NbPoints() < 1 )
597         return invalidID;
598       Quantity_Parameter U,V;
599       projector.LowerDistanceParameters(U,V);
600       uv = gp_XY( U,V );
601     }
602     UV += uv / 3.;
603   }
604   // normale to face at node1
605   gp_Pnt node1Pnt ( node1->X(), node1->Y(), node1->Z() );
606   gp_Pnt node2Pnt ( node2->X(), node2->Y(), node2->Z() );
607   gp_Pnt node3Pnt ( node3->X(), node3->Y(), node3->Z() );
608   gp_Vec vec12( node1Pnt, node2Pnt );
609   gp_Vec vec13( node1Pnt, node3Pnt );
610   gp_Vec meshNormal = vec12 ^ vec13;
611   if ( meshNormal.SquareMagnitude() < DBL_MIN )
612     return invalidID;
613   
614   // normale to geomFace at UV
615   gp_Vec du, dv;
616   surface.D1( UV.X(), UV.Y(), node1Pnt, du, dv );
617   gp_Vec geomNormal = du ^ dv;
618   if ( geomNormal.SquareMagnitude() < DBL_MIN )
619     return findShapeID( mesh, node2, node3, node1, toMeshHoles );
620   if ( geomFace.Orientation() == TopAbs_REVERSED )
621     geomNormal.Reverse();
622
623   // compare normals
624   bool isReverse = ( meshNormal * geomNormal ) < 0;
625   if ( !isReverse )
626     return meshDS->ShapeToIndex( solid1 );
627
628   if ( solids.Extent() == 1 )
629     return HOLE_ID; // we are inside a hole
630   else
631     return meshDS->ShapeToIndex( solids(2) );
632 }
633                        
634 //=======================================================================
635 //function : readResultFile
636 //purpose  : 
637 //=======================================================================
638
639 static bool readResultFile(const int                       fileOpen,
640                            SMESH_Mesh&                     theMesh,
641                            TopoDS_Shape                    tabShape[],
642                            double**                        tabBox,
643                            const int                       nbShape,
644                            map <int,const SMDS_MeshNode*>& theGhs3dIdToNodeMap,
645                            bool                            toMeshHoles)
646 {
647   struct stat status;
648   size_t      length;
649
650   char *ptr, *mapPtr;
651   char *tetraPtr;
652   char *shapePtr;
653
654   SMESHDS_Mesh* theMeshDS = theMesh.GetMeshDS();
655
656   int fileStat;
657   int nbElems, nbNodes, nbInputNodes;
658   int nodeId/*, triangleId*/;
659   int nbTriangle;
660   int ID, shapeID, ghs3dShapeID;
661   int IdShapeRef = 1;
662   int compoundID =
663     nbShape ? theMeshDS->ShapeToIndex( tabShape[0] ) : theMeshDS->ShapeToIndex( theMeshDS->ShapeToMesh() );
664
665   int *tab, *tabID, *nodeID, *nodeAssigne;
666   double *coord;
667   const SMDS_MeshNode **node;
668
669   tab    = new int[3];
670   //tabID  = new int[nbShape];
671   nodeID = new int[4];
672   coord  = new double[3];
673   node   = new const SMDS_MeshNode*[4];
674
675   TopoDS_Shape aSolid;
676   SMDS_MeshNode * aNewNode;
677   map <int,const SMDS_MeshNode*>::iterator itOnNode;
678   SMDS_MeshElement* aTet;
679 #ifdef _DEBUG_
680   set<int> shapeIDs;
681 #endif
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   nodeAssigne = new int[ nbNodes+1 ];
699
700   if (nbShape > 0)
701     aSolid = tabShape[0];
702
703   // Reading the nodeId
704   for (int i=0; i < 4*nbElems; i++)
705     nodeId = strtol(ptr, &ptr, 10);
706
707   // Reading the nodeCoor and update the nodeMap
708   for (int iNode=1; iNode <= nbNodes; iNode++) {
709     for (int iCoor=0; iCoor < 3; iCoor++)
710       coord[ iCoor ] = strtod(ptr, &ptr);
711     nodeAssigne[ iNode ] = 1;
712     if ( iNode > nbInputNodes ) {
713       nodeAssigne[ iNode ] = 0;
714       aNewNode = theMeshDS->AddNode( coord[0],coord[1],coord[2] );
715       theGhs3dIdToNodeMap.insert(theGhs3dIdToNodeMap.end(), make_pair( iNode, aNewNode ));
716     }
717   }
718
719   // Reading the number of triangles which corresponds to the number of sub-domains
720   nbTriangle = strtol(ptr, &ptr, 10);
721
722   tabID = new int[nbTriangle];
723   for (int i=0; i < nbTriangle; i++) {
724     tabID[i] = 0;
725     // find the solid corresponding to GHS3D sub-domain following
726     // the technique proposed in GHS3D manual in chapter
727     // "B.4 Subdomain (sub-region) assignment"
728     int nodeId1 = strtol(ptr, &ptr, 10);
729     int nodeId2 = strtol(ptr, &ptr, 10);
730     int nodeId3 = strtol(ptr, &ptr, 10);
731     if ( nbTriangle > 1 ) {
732       const SMDS_MeshNode* n1 = theGhs3dIdToNodeMap[ nodeId1 ];
733       const SMDS_MeshNode* n2 = theGhs3dIdToNodeMap[ nodeId2 ];
734       const SMDS_MeshNode* n3 = theGhs3dIdToNodeMap[ nodeId3 ];
735       try {
736         OCC_CATCH_SIGNALS;
737         tabID[i] = findShapeID( theMesh, n1, n2, n3, toMeshHoles );
738 #ifdef _DEBUG_
739         cout << i+1 << " subdomain: findShapeID() returns " << tabID[i] << endl;
740 #endif
741       } catch ( Standard_Failure ) {
742       } catch (...) {}
743     }
744   }
745
746   shapePtr = ptr;
747
748   if ( nbTriangle <= nbShape ) // no holes
749     toMeshHoles = true; // not avoid creating tetras in holes
750
751   // Associating the tetrahedrons to the shapes
752   shapeID = compoundID;
753   for (int iElem = 0; iElem < nbElems; iElem++) {
754     for (int iNode = 0; iNode < 4; iNode++) {
755       ID = strtol(tetraPtr, &tetraPtr, 10);
756       itOnNode = theGhs3dIdToNodeMap.find(ID);
757       node[ iNode ] = itOnNode->second;
758       nodeID[ iNode ] = ID;
759     }
760     // We always run GHS3D with "to mesh holes'==TRUE but we must not create
761     // tetras within holes depending on hypo option,
762     // so we first check if aTet is inside a hole and then create it 
763     //aTet = theMeshDS->AddVolume( node[1], node[0], node[2], node[3] );
764     if ( nbTriangle > 1 ) {
765       shapeID = HOLE_ID; // negative shapeID means not to create tetras if !toMeshHoles
766       ghs3dShapeID = strtol(shapePtr, &shapePtr, 10) - IdShapeRef;
767       if ( tabID[ ghs3dShapeID ] == 0 ) {
768         TopAbs_State state;
769         aSolid = findShape(node, aSolid, tabShape, tabBox, nbShape, &state);
770         if ( toMeshHoles || state == TopAbs_IN )
771           shapeID = theMeshDS->ShapeToIndex( aSolid );
772         tabID[ ghs3dShapeID ] = shapeID;
773       }
774       else
775         shapeID = tabID[ ghs3dShapeID ];
776     }
777     else if ( nbShape > 1 ) {
778       // Case where nbTriangle == 1 while nbShape == 2 encountered
779       // with compound of 2 boxes and "To mesh holes"==False,
780       // so there are no subdomains specified for each tetrahedron.
781       // Try to guess a solid by a node already bound to shape
782       shapeID = 0;
783       for ( int i=0; i<4 && shapeID==0; i++ ) {
784         if ( nodeAssigne[ nodeID[i] ] == 1 &&
785              node[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE &&
786              node[i]->GetPosition()->GetShapeId() > 1 )
787         {
788           shapeID = node[i]->GetPosition()->GetShapeId();
789         }
790       }
791       if ( shapeID==0 ) {
792         aSolid = findShape(node, aSolid, tabShape, tabBox, nbShape);
793         shapeID = theMeshDS->ShapeToIndex( aSolid );
794       }
795     }
796     // set new nodes and tetrahedron onto the shape
797     for ( int i=0; i<4; i++ ) {
798       if ( nodeAssigne[ nodeID[i] ] == 0 ) {
799         if ( shapeID != HOLE_ID )
800           theMeshDS->SetNodeInVolume( node[i], shapeID );
801         nodeAssigne[ nodeID[i] ] = shapeID;
802       }
803     }
804     if ( toMeshHoles || shapeID != HOLE_ID ) {
805       aTet = theMeshDS->AddVolume( node[1], node[0], node[2], node[3] );
806       theMeshDS->SetMeshElementOnShape( aTet, shapeID );
807     }
808 #ifdef _DEBUG_
809     shapeIDs.insert( shapeID );
810 #endif
811   }
812   // Remove nodes of tetras inside holes if !toMeshHoles
813   if ( !toMeshHoles ) {
814     itOnNode = theGhs3dIdToNodeMap.find( nbInputNodes );
815     for ( ; itOnNode != theGhs3dIdToNodeMap.end(); ++itOnNode) {
816       ID = itOnNode->first;
817       if ( nodeAssigne[ ID ] == HOLE_ID )
818         theMeshDS->RemoveFreeNode( itOnNode->second, 0 );
819     }
820   }
821
822   if ( nbElems )
823     cout << nbElems << " tetrahedrons have been associated to " << nbShape << " shapes" << endl;
824   munmap(mapPtr, length);
825   close(fileOpen);
826
827   delete [] tab;
828   delete [] tabID;
829   delete [] nodeID;
830   delete [] coord;
831   delete [] node;
832   delete [] nodeAssigne;
833
834 #ifdef _DEBUG_
835   if ( shapeIDs.size() != nbShape ) {
836     cout << "Only " << shapeIDs.size() << " solids of " << nbShape << " found" << endl;
837     for (int i=0; i<nbShape; i++) {
838       shapeID = theMeshDS->ShapeToIndex( tabShape[i] );
839       if ( shapeIDs.find( shapeID ) == shapeIDs.end() )
840         cout << "  Solid #" << shapeID << " not found" << endl;
841     }
842   }
843 #endif
844
845   return true;
846 }
847
848 //=======================================================================
849 //function : readResultFile
850 //purpose  : 
851 //=======================================================================
852
853 static bool readResultFile(const int                      fileOpen,
854                            SMESHDS_Mesh*                  theMeshDS,
855                            TopoDS_Shape                   aSolid,
856                            vector <const SMDS_MeshNode*>& theNodeByGhs3dId) {
857
858   struct stat  status;
859   size_t       length;
860
861   char *ptr, *mapPtr;
862   char *tetraPtr;
863   char *shapePtr;
864
865   int fileStat;
866   int nbElems, nbNodes, nbInputNodes;
867   int nodeId, triangleId;
868   int nbTriangle;
869   int ID, shapeID;
870
871   int *tab;
872   double *coord;
873   const SMDS_MeshNode **node;
874
875   tab   = new int[3];
876   coord = new double[3];
877   node  = new const SMDS_MeshNode*[4];
878
879   SMDS_MeshNode * aNewNode;
880   map <int,const SMDS_MeshNode*>::iterator IdNode;
881   SMDS_MeshElement* aTet;
882
883   // Read the file state
884   fileStat = fstat(fileOpen, &status);
885   length   = status.st_size;
886
887   // Mapping the result file into memory
888   ptr = (char *) mmap(0,length,PROT_READ,MAP_PRIVATE,fileOpen,0);
889   mapPtr = ptr;
890
891   ptr      = readMapIntLine(ptr, tab);
892   tetraPtr = ptr;
893
894   nbElems      = tab[0];
895   nbNodes      = tab[1];
896   nbInputNodes = tab[2];
897
898   theNodeByGhs3dId.resize( nbNodes );
899
900   // Reading the nodeId
901   for (int i=0; i < 4*nbElems; i++)
902     nodeId = strtol(ptr, &ptr, 10);
903
904   // Reading the nodeCoor and update the nodeMap
905   shapeID = theMeshDS->ShapeToIndex( aSolid );
906   for (int iNode=0; iNode < nbNodes; iNode++) {
907     for (int iCoor=0; iCoor < 3; iCoor++)
908       coord[ iCoor ] = strtod(ptr, &ptr);
909     if ((iNode+1) > nbInputNodes) {
910       aNewNode = theMeshDS->AddNode( coord[0],coord[1],coord[2] );
911       theMeshDS->SetNodeInVolume( aNewNode, shapeID );
912       theNodeByGhs3dId[ iNode ] = aNewNode;
913     }
914   }
915
916   // Reading the triangles
917   nbTriangle = strtol(ptr, &ptr, 10);
918
919   for (int i=0; i < 3*nbTriangle; i++)
920     triangleId = strtol(ptr, &ptr, 10);
921
922   shapePtr = ptr;
923
924   // Associating the tetrahedrons to the shapes
925   for (int iElem = 0; iElem < nbElems; iElem++) {
926     for (int iNode = 0; iNode < 4; iNode++) {
927       ID = strtol(tetraPtr, &tetraPtr, 10);
928       node[ iNode ] = theNodeByGhs3dId[ ID-1 ];
929     }
930     aTet = theMeshDS->AddVolume( node[1], node[0], node[2], node[3] );
931     shapeID = theMeshDS->ShapeToIndex( aSolid );
932     theMeshDS->SetMeshElementOnShape( aTet, shapeID );
933   }
934   if ( nbElems )
935     cout << nbElems << " tetrahedrons have been associated to " << nbTriangle << " shapes" << endl;
936   munmap(mapPtr, length);
937   close(fileOpen);
938
939   delete [] tab;
940   delete [] coord;
941   delete [] node;
942
943   return true;
944 }
945
946 //=============================================================================
947 /*!
948  *Here we are going to use the GHS3D mesher
949  */
950 //=============================================================================
951
952 bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
953                                 const TopoDS_Shape& theShape)
954 {
955   bool Ok(false);
956   SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
957
958   _nbShape = countShape( meshDS, TopAbs_SOLID ); // we count the number of shapes
959
960   // create bounding box for every shape inside the compound
961
962   int iShape = 0;
963   TopoDS_Shape* tabShape;
964   double**      tabBox;
965   tabShape = new TopoDS_Shape[_nbShape];
966   tabBox   = new double*[_nbShape];
967   for (int i=0; i<_nbShape; i++)
968     tabBox[i] = new double[6];
969   Standard_Real Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
970
971   TopExp_Explorer expBox (meshDS->ShapeToMesh(), TopAbs_SOLID);
972   for (; expBox.More(); expBox.Next()) {
973     tabShape[iShape] = expBox.Current();
974     Bnd_Box BoundingBox;
975     BRepBndLib::Add(expBox.Current(), BoundingBox);
976     BoundingBox.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
977     tabBox[iShape][0] = Xmin; tabBox[iShape][1] = Xmax;
978     tabBox[iShape][2] = Ymin; tabBox[iShape][3] = Ymax;
979     tabBox[iShape][4] = Zmin; tabBox[iShape][5] = Zmax;
980     iShape++;
981   }
982
983   // a unique working file name
984   // to avoid access to the same files by eg different users
985   TCollection_AsciiString aGenericName
986     = (char*) GHS3DPlugin_Hypothesis::GetFileName(_hyp).c_str();
987
988   TCollection_AsciiString aFacesFileName, aPointsFileName, aResultFileName;
989   TCollection_AsciiString aBadResFileName, aBbResFileName, aLogFileName;
990   aFacesFileName  = aGenericName + ".faces";  // in faces
991   aPointsFileName = aGenericName + ".points"; // in points
992   aResultFileName = aGenericName + ".noboite";// out points and volumes
993   aBadResFileName = aGenericName + ".boite";  // out bad result
994   aBbResFileName  = aGenericName + ".bb";     // out vertex stepsize
995   aLogFileName    = aGenericName + ".log";    // log
996
997   // -----------------
998   // make input files
999   // -----------------
1000
1001   ofstream aFacesFile  ( aFacesFileName.ToCString()  , ios::out);
1002   ofstream aPointsFile ( aPointsFileName.ToCString() , ios::out);
1003
1004   Ok =
1005 #ifdef WIN32
1006     aFacesFile->is_open() && aPointsFile->is_open();
1007 #else
1008     aFacesFile.rdbuf()->is_open() && aPointsFile.rdbuf()->is_open();
1009 #endif
1010   if (!Ok) {
1011     INFOS( "Can't write into " << aFacesFileName);
1012     return error(SMESH_Comment("Can't write into ") << aFacesFileName);
1013   }
1014   map <int,int> aSmdsToGhs3dIdMap;
1015   map <int,const SMDS_MeshNode*> aGhs3dIdToNodeMap;
1016
1017   Ok = writePoints( aPointsFile, meshDS, aSmdsToGhs3dIdMap, aGhs3dIdToNodeMap ) &&
1018        writeFaces ( aFacesFile,  meshDS, aSmdsToGhs3dIdMap );
1019
1020   aFacesFile.close();
1021   aPointsFile.close();
1022
1023   if ( ! Ok ) {
1024     if ( !_keepFiles ) {
1025       OSD_File( aFacesFileName ).Remove();
1026       OSD_File( aPointsFileName ).Remove();
1027     }
1028     return error(COMPERR_BAD_INPUT_MESH);
1029   }
1030   OSD_File( aResultFileName ).Remove(); // needed for boundary recovery module usage
1031
1032   // -----------------
1033   // run ghs3d mesher
1034   // -----------------
1035
1036   TCollection_AsciiString cmd( (char*)GHS3DPlugin_Hypothesis::CommandToRun( _hyp ).c_str() );
1037   cmd += TCollection_AsciiString(" -f ") + aGenericName;  // file to read
1038   cmd += TCollection_AsciiString(" 1>" ) + aLogFileName;  // dump into file
1039
1040   cout << endl;
1041   cout << "Ghs3d execution..." << endl;
1042   cout << cmd << endl;
1043
1044   system( cmd.ToCString() ); // run
1045
1046   cout << endl;
1047   cout << "End of Ghs3d execution !" << endl;
1048
1049   // --------------
1050   // read a result
1051   // --------------
1052
1053   // Mapping the result file
1054
1055   int fileOpen;
1056   fileOpen = open( aResultFileName.ToCString(), O_RDONLY);
1057   if ( fileOpen < 0 ) {
1058     cout << endl;
1059     cout << "Can't open the " << aResultFileName.ToCString() << " GHS3D output file" << endl;
1060     cout << "Log: " << aLogFileName << endl;
1061     Ok = false;
1062   }
1063   else {
1064     bool toMeshHoles =
1065       _hyp ? _hyp->GetToMeshHoles(true) : GHS3DPlugin_Hypothesis::DefaultMeshHoles();
1066     Ok = readResultFile( fileOpen, theMesh, tabShape, tabBox, _nbShape, aGhs3dIdToNodeMap,
1067                          toMeshHoles );
1068   }
1069
1070   // ---------------------
1071   // remove working files
1072   // ---------------------
1073
1074   if ( Ok )
1075   {
1076     if ( !_keepFiles )
1077       OSD_File( aLogFileName ).Remove();
1078   }
1079   else if ( OSD_File( aLogFileName ).Size() > 0 )
1080   {
1081     // get problem description from the log file
1082     _Ghs2smdsConvertor conv( aGhs3dIdToNodeMap );
1083     storeErrorDescription( aLogFileName, conv );
1084   }
1085   else
1086   {
1087     // the log file is empty
1088     OSD_File( aLogFileName ).Remove();
1089     INFOS( "GHS3D Error, command '" << cmd.ToCString() << "' failed" );
1090     error(COMPERR_ALGO_FAILED, "ghs3d: command not found" );
1091   }
1092
1093   if ( !_keepFiles ) {
1094     OSD_File( aFacesFileName ).Remove();
1095     OSD_File( aPointsFileName ).Remove();
1096     OSD_File( aResultFileName ).Remove();
1097     OSD_File( aBadResFileName ).Remove();
1098     OSD_File( aBbResFileName ).Remove();
1099   }
1100   cout << "<" << aResultFileName.ToCString() << "> GHS3D output file ";
1101   if ( !Ok )
1102     cout << "not ";
1103   cout << "treated !" << endl;
1104   cout << endl;
1105
1106   _nbShape = 0;    // re-initializing _nbShape for the next Compute() method call
1107   delete [] tabShape;
1108   delete [] tabBox;
1109
1110   return Ok;
1111 }
1112
1113 //=============================================================================
1114 /*!
1115  *Here we are going to use the GHS3D mesher w/o geometry
1116  */
1117 //=============================================================================
1118 bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
1119                                 SMESH_MesherHelper* aHelper)
1120 {
1121   MESSAGE("GHS3DPlugin_GHS3D::Compute()");
1122
1123   SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
1124   TopoDS_Shape theShape = aHelper->GetSubShape();
1125
1126   // a unique working file name
1127   // to avoid access to the same files by eg different users
1128   TCollection_AsciiString aGenericName
1129     = (char*) GHS3DPlugin_Hypothesis::GetFileName(_hyp).c_str();
1130
1131   TCollection_AsciiString aFacesFileName, aPointsFileName, aResultFileName;
1132   TCollection_AsciiString aBadResFileName, aBbResFileName, aLogFileName;
1133   aFacesFileName  = aGenericName + ".faces";  // in faces
1134   aPointsFileName = aGenericName + ".points"; // in points
1135   aResultFileName = aGenericName + ".noboite";// out points and volumes
1136   aBadResFileName = aGenericName + ".boite";  // out bad result
1137   aBbResFileName  = aGenericName + ".bb";     // out vertex stepsize
1138   aLogFileName    = aGenericName + ".log";    // log
1139
1140   // -----------------
1141   // make input files
1142   // -----------------
1143
1144   ofstream aFacesFile  ( aFacesFileName.ToCString()  , ios::out);
1145   ofstream aPointsFile  ( aPointsFileName.ToCString()  , ios::out);
1146   bool Ok =
1147 #ifdef WIN32
1148     aFacesFile->is_open() && aPointsFile->is_open();
1149 #else
1150     aFacesFile.rdbuf()->is_open() && aPointsFile.rdbuf()->is_open();
1151 #endif
1152
1153   if (!Ok)
1154     return error( SMESH_Comment("Can't write into ") << aPointsFileName);
1155
1156   vector <const SMDS_MeshNode*> aNodeByGhs3dId;
1157
1158   Ok = (writeFaces ( aFacesFile, meshDS, aNodeByGhs3dId ) &&
1159         writePoints( aPointsFile, meshDS, aNodeByGhs3dId));
1160   
1161   aFacesFile.close();
1162   aPointsFile.close();
1163   
1164   if ( ! Ok ) {
1165     if ( !_keepFiles ) {
1166       OSD_File( aFacesFileName ).Remove();
1167       OSD_File( aPointsFileName ).Remove();
1168     }
1169     return error(COMPERR_BAD_INPUT_MESH);
1170   }
1171   OSD_File( aResultFileName ).Remove(); // needed for boundary recovery module usage
1172
1173   // -----------------
1174   // run ghs3d mesher
1175   // -----------------
1176
1177   TCollection_AsciiString cmd =
1178     (char*)GHS3DPlugin_Hypothesis::CommandToRun( _hyp, false ).c_str();
1179   cmd += TCollection_AsciiString(" -f ") + aGenericName;  // file to read
1180   cmd += TCollection_AsciiString(" 1>" ) + aLogFileName;  // dump into file
1181   
1182   system( cmd.ToCString() ); // run
1183
1184   // --------------
1185   // read a result
1186   // --------------
1187   int fileOpen;
1188   fileOpen = open( aResultFileName.ToCString(), O_RDONLY);
1189   if ( fileOpen < 0 ) {
1190     cout << endl;
1191     cout << "Error when opening the " << aResultFileName.ToCString() << " file" << endl;
1192     cout << "Log: " << aLogFileName << endl;
1193     cout << endl;
1194     Ok = false;
1195   }
1196   else {
1197     Ok = readResultFile( fileOpen, meshDS, theShape ,aNodeByGhs3dId );
1198   }
1199   
1200   // ---------------------
1201   // remove working files
1202   // ---------------------
1203
1204   if ( Ok )
1205   {
1206     if ( !_keepFiles )
1207       OSD_File( aLogFileName ).Remove();
1208   }
1209   else if ( OSD_File( aLogFileName ).Size() > 0 )
1210   {
1211     // get problem description from the log file
1212     _Ghs2smdsConvertor conv( aNodeByGhs3dId );
1213     storeErrorDescription( aLogFileName, conv );
1214   }
1215   else {
1216     // the log file is empty
1217     OSD_File( aLogFileName ).Remove();
1218     INFOS( "GHS3D Error, command '" << cmd.ToCString() << "' failed" );
1219     error(COMPERR_ALGO_FAILED, "ghs3d: command not found" );
1220   }
1221
1222   if ( !_keepFiles )
1223   {
1224     OSD_File( aFacesFileName ).Remove();
1225     OSD_File( aPointsFileName ).Remove();
1226     OSD_File( aResultFileName ).Remove();
1227     OSD_File( aBadResFileName ).Remove();
1228     OSD_File( aBbResFileName ).Remove();
1229   }
1230   
1231   return Ok;
1232 }
1233
1234 //================================================================================
1235 /*!
1236  * \brief Provide human readable text by error code reported by ghs3d
1237  */
1238 //================================================================================
1239
1240 static string translateError(const int errNum)
1241 {
1242   switch ( errNum ) {
1243   case 0:
1244     return "The surface mesh includes a face of type other than edge, "
1245       "triangle or quadrilateral. This face type is not supported.";
1246   case 1:
1247     return "Not enough memory for the face table.";
1248   case 2:
1249     return "Not enough memory.";
1250   case 3:
1251     return "Not enough memory.";
1252   case 4:
1253     return "Face is ignored.";
1254   case 5:
1255     return "End of file. Some data are missing in the file.";
1256   case 6:
1257     return "Read error on the file. There are wrong data in the file.";
1258   case 7:
1259     return "the metric file is inadequate (dimension other than 3).";
1260   case 8:
1261     return "the metric file is inadequate (values not per vertices).";
1262   case 9:
1263     return "the metric file contains more than one field.";
1264   case 10:
1265     return "the number of values in the \".bb\" (metric file) is incompatible with the expected"
1266       "value of number of mesh vertices in the \".noboite\" file.";
1267   case 12:
1268     return "Too many sub-domains.";
1269   case 13:
1270     return "the number of vertices is negative or null.";
1271   case 14:
1272     return "the number of faces is negative or null.";
1273   case 15:
1274     return "A face has a null vertex.";
1275   case 22:
1276     return "incompatible data.";
1277   case 131:
1278     return "the number of vertices is negative or null.";
1279   case 132:
1280     return "the number of vertices is negative or null (in the \".mesh\" file).";
1281   case 133:
1282     return "the number of faces is negative or null.";
1283   case 1000:
1284     return "A face appears more than once in the input surface mesh.";
1285   case 1001:
1286     return "An edge appears more than once in the input surface mesh.";
1287   case 1002:
1288     return "A face has a vertex negative or null.";
1289   case 1003:
1290     return "NOT ENOUGH MEMORY.";
1291   case 2000:
1292     return "Not enough available memory.";
1293   case 2002:
1294     return "Some initial points cannot be inserted. The surface mesh is probably very bad "
1295       "in terms of quality or the input list of points is wrong.";
1296   case 2003:
1297     return "Some vertices are too close to one another or coincident.";
1298   case 2004:
1299     return "Some vertices are too close to one another or coincident.";
1300   case 2012:
1301     return "A vertex cannot be inserted.";
1302   case 2014:
1303     return "There are at least two points considered as coincident.";
1304   case 2103:
1305     return "Some vertices are too close to one another or coincident.";
1306   case 3000:
1307     return "The surface mesh regeneration step has failed.";
1308   case 3009:
1309     return "Constrained edge cannot be enforced.";
1310   case 3019:
1311     return "Constrained face cannot be enforced.";
1312   case 3029:
1313     return "Missing faces.";
1314   case 3100:
1315     return "No guess to start the definition of the connected component(s).";
1316   case 3101:
1317     return "The surface mesh includes at least one hole. The domain is not well defined.";
1318   case 3102:
1319     return "Impossible to define a component.";
1320   case 3103:
1321     return "The surface edge intersects another surface edge.";
1322   case 3104:
1323     return "The surface edge intersects the surface face.";
1324   case 3105:
1325     return "One boundary point lies within a surface face.";
1326   case 3106:
1327     return "One surface edge intersects a surface face.";
1328   case 3107:
1329     return "One boundary point lies within a surface edge.";
1330   case 3108:
1331     return "Insufficient memory ressources detected due to a bad quality surface mesh leading "
1332       "to too many swaps.";
1333   case 3109:
1334     return "Edge is unique (i.e., bounds a hole in the surface).";
1335   case 3122:
1336     return "Presumably, the surface mesh is not compatible with the domain being processed.";
1337   case 3123:
1338     return "Too many components, too many sub-domain.";
1339   case 3209:
1340     return "The surface mesh includes at least one hole. "
1341       "Therefore there is no domain properly defined.";
1342   case 3300:
1343     return "Statistics.";
1344   case 3400:
1345     return "Statistics.";
1346   case 3500:
1347     return "Warning, it is dramatically tedious to enforce the boundary items.";
1348   case 4000:
1349     return "Not enough memory at this time, nevertheless, the program continues. "
1350       "The expected mesh will be correct but not really as large as required.";
1351   case 4002:
1352     return "see above error code, resulting quality may be poor.";
1353   case 4003:
1354     return "Not enough memory at this time, nevertheless, the program continues (warning).";
1355   case 8000:
1356     return "Unknown face type.";
1357   case 8005:
1358   case 8006:
1359     return "End of file. Some data are missing in the file.";
1360   case 9000:
1361     return "A too small volume element is detected.";
1362   case 9001:
1363     return "There exists at least a null or negative volume element.";
1364   case 9002:
1365     return "There exist null or negative volume elements.";
1366   case 9003:
1367     return "A too small volume element is detected. A face is considered being degenerated.";
1368   case 9100:
1369     return "Some element is suspected to be very bad shaped or wrong.";
1370   case 9102:
1371     return "A too bad quality face is detected. This face is considered degenerated.";
1372   case 9112:
1373     return "A too bad quality face is detected. This face is degenerated.";
1374   case 9122:
1375     return "Presumably, the surface mesh is not compatible with the domain being processed.";
1376   case 9999:
1377     return "Abnormal error occured, contact hotline.";
1378   case 23600:
1379     return "Not enough memory for the face table.";
1380   case 23601:
1381     return "The algorithm cannot run further. "
1382       "The surface mesh is probably very bad in terms of quality.";
1383   case 23602:
1384     return "Bad vertex number.";
1385   }
1386   return "";
1387 }
1388
1389 //================================================================================
1390 /*!
1391  * \brief Retrieve from a string given number of integers
1392  */
1393 //================================================================================
1394
1395 static char* getIds( char* ptr, int nbIds, vector<int>& ids )
1396 {
1397   ids.clear();
1398   ids.reserve( nbIds );
1399   while ( nbIds )
1400   {
1401     while ( !isdigit( *ptr )) ++ptr;
1402     if ( ptr[-1] == '-' ) --ptr;
1403     ids.push_back( strtol( ptr, &ptr, 10 ));
1404     --nbIds;
1405   }
1406   return ptr;
1407 }
1408
1409 //================================================================================
1410 /*!
1411  * \brief Retrieve problem description form a log file
1412  *  \retval bool - always false
1413  */
1414 //================================================================================
1415
1416 bool GHS3DPlugin_GHS3D::storeErrorDescription(const TCollection_AsciiString& logFile,
1417                                               const _Ghs2smdsConvertor &     toSmdsConvertor )
1418 {
1419   // open file
1420 #ifdef WNT
1421   int file = ::_open (logFile.ToCString(), _O_RDONLY|_O_BINARY);
1422 #else
1423   int file = ::open (logFile.ToCString(), O_RDONLY);
1424 #endif
1425   if ( file < 0 )
1426     return error( SMESH_Comment("See ") << logFile << " for problem description");
1427
1428   // get file size
1429 //   struct stat status;
1430 //   fstat(file, &status);
1431 //   size_t length = status.st_size;
1432   off_t length = lseek( file, 0, SEEK_END);
1433   lseek( file, 0, SEEK_SET);
1434
1435   // read file
1436   vector< char > buf( length );
1437   int nBytesRead = ::read (file, & buf[0], length);
1438   ::close (file);
1439   char* ptr = & buf[0];
1440   char* bufEnd = ptr + nBytesRead;
1441
1442   SMESH_Comment errDescription;
1443
1444   enum { NODE = 1, EDGE, TRIA, VOL, ID = 1 };
1445
1446   // look for errors "ERR #"
1447
1448   set<string> foundErrorStr; // to avoid reporting same error several times
1449   set<int>    elemErrorNums; // not to report different types of errors with bad elements
1450   while ( ++ptr < bufEnd )
1451   {
1452     if ( strncmp( ptr, "ERR ", 4 ) != 0 )
1453       continue;
1454
1455     list<const SMDS_MeshElement*> badElems;
1456     vector<int> nodeIds;
1457
1458     ptr += 4;
1459     char* errBeg = ptr;
1460     int   errNum = strtol(ptr, &ptr, 10);
1461     switch ( errNum ) { // we treat errors enumerated in [SALOME platform 0019316] issue
1462     case 0015:
1463       // The face number (numfac) with vertices (f 1, f 2, f 3) has a null vertex.
1464       ptr = getIds(ptr, NODE, nodeIds);
1465       ptr = getIds(ptr, TRIA, nodeIds);
1466       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1467       break;
1468     case 1000: // ERR  1000 :  1 3 2
1469       // Face (f 1, f 2, f 3) appears more than once in the input surface mesh.
1470       ptr = getIds(ptr, TRIA, nodeIds);
1471       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1472       break;
1473     case 1001:
1474       // Edge (e1, e2) appears more than once in the input surface mesh
1475       ptr = getIds(ptr, EDGE, nodeIds);
1476       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1477       break;
1478     case 1002:
1479       // Face (f 1, f 2, f 3) has a vertex negative or null
1480       ptr = getIds(ptr, TRIA, nodeIds);
1481       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1482       break;
1483     case 2004:
1484       // Vertex v1 and vertex v2 are too close to one another or coincident (warning).
1485       ptr = getIds(ptr, NODE, nodeIds);
1486       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1487       ptr = getIds(ptr, NODE, nodeIds);
1488       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1489       break;
1490     case 2012:
1491       // Vertex v1 cannot be inserted (warning).
1492       ptr = getIds(ptr, NODE, nodeIds);
1493       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1494       break;
1495     case 2014:
1496       // There are at least two points whose distance is dist, i.e., considered as coincident
1497     case 2103: // ERR  2103 :  16 WITH  3
1498       // Vertex v1 and vertex v2 are too close to one another or coincident (warning).
1499       ptr = getIds(ptr, NODE, nodeIds);
1500       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1501       ptr = getIds(ptr, NODE, nodeIds);
1502       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1503       break;
1504     case 3009:
1505       // Constrained edge (e1, e2) cannot be enforced (warning).
1506       ptr = getIds(ptr, EDGE, nodeIds);
1507       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1508       break;
1509     case 3019:
1510       // Constrained face (f 1, f 2, f 3) cannot be enforced
1511       ptr = getIds(ptr, TRIA, nodeIds);
1512       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1513       break;
1514     case 3103: // ERR  3103 :  1 2 WITH  7 3
1515       // The surface edge (e1, e2) intersects another surface edge (e3, e4)
1516       ptr = getIds(ptr, EDGE, nodeIds);
1517       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1518       ptr = getIds(ptr, EDGE, nodeIds);
1519       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1520       break;
1521     case 3104: // ERR  3104 :  9 10 WITH  1 2 3
1522       // The surface edge (e1, e2) intersects the surface face (f 1, f 2, f 3)
1523       ptr = getIds(ptr, EDGE, nodeIds);
1524       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1525       ptr = getIds(ptr, TRIA, nodeIds);
1526       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1527       break;
1528     case 3105: // ERR  3105 :  8 IN  2 3 5
1529       // One boundary point (say p1) lies within a surface face (f 1, f 2, f 3)
1530       ptr = getIds(ptr, NODE, nodeIds);
1531       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1532       ptr = getIds(ptr, TRIA, nodeIds);
1533       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1534       break;
1535     case 3106:
1536       // One surface edge (say e1, e2) intersects a surface face (f 1, f 2, f 3)
1537       ptr = getIds(ptr, EDGE, nodeIds);
1538       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1539       ptr = getIds(ptr, TRIA, nodeIds);
1540       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1541       break;
1542     case 3107: // ERR  3107 :  2 IN  4 1
1543       // One boundary point (say p1) lies within a surface edge (e1, e2) (stop).
1544       ptr = getIds(ptr, NODE, nodeIds);
1545       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1546       ptr = getIds(ptr, EDGE, nodeIds);
1547       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1548       break;
1549     case 3109: // ERR  3109 :  EDGE  5 6 UNIQUE
1550       // Edge (e1, e2) is unique (i.e., bounds a hole in the surface)
1551       ptr = getIds(ptr, EDGE, nodeIds);
1552       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1553       break;
1554     case 9000: // ERR  9000 
1555       //  ELEMENT  261 WITH VERTICES :  7 396 -8 242 
1556       //  VOLUME   : -1.11325045E+11 W.R.T. EPSILON   0.
1557       // A too small volume element is detected. Are reported the index of the element,
1558       // its four vertex indices, its volume and the tolerance threshold value
1559       ptr = getIds(ptr, ID, nodeIds);
1560       ptr = getIds(ptr, VOL, nodeIds);
1561       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1562       // even if all nodes found, volume it most probably invisible,
1563       // add its faces to demenstrate it anyhow
1564       {
1565         vector<int> faceNodes( nodeIds.begin(), --nodeIds.end() ); // 012
1566         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
1567         faceNodes[2] = nodeIds[3]; // 013
1568         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
1569         faceNodes[1] = nodeIds[2]; // 023
1570         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
1571         faceNodes[0] = nodeIds[1]; // 123
1572         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
1573       }
1574       break;
1575     case 9001: // ERR  9001
1576       //  %% NUMBER OF NEGATIVE VOLUME TETS  :  1 
1577       //  %% THE LARGEST NEGATIVE TET        :   1.75376581E+11 
1578       //  %%  NUMBER OF NULL VOLUME TETS     :  0
1579       // There exists at least a null or negative volume element
1580       break;
1581     case 9002:
1582       // There exist n null or negative volume elements
1583       break;
1584     case 9003:
1585       // A too small volume element is detected
1586       break;
1587     case 9102:
1588       // A too bad quality face is detected. This face is considered degenerated,
1589       // its index, its three vertex indices together with its quality value are reported
1590       break; // same as next
1591     case 9112: // ERR  9112 
1592       //  FACE   2 WITH VERTICES :  4 2 5 
1593       //  SMALL INRADIUS :   0.
1594       // A too bad quality face is detected. This face is degenerated,
1595       // its index, its three vertex indices together with its inradius are reported
1596       ptr = getIds(ptr, ID, nodeIds);
1597       ptr = getIds(ptr, TRIA, nodeIds);
1598       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1599       // add triangle edges as it most probably has zero area and hence invisible
1600       {
1601         vector<int> edgeNodes(2);
1602         edgeNodes[0] = nodeIds[0]; edgeNodes[1] = nodeIds[1]; // 0-1
1603         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
1604         edgeNodes[1] = nodeIds[2]; // 0-2
1605         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
1606         edgeNodes[0] = nodeIds[1]; // 1-2
1607         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
1608       }
1609       break;
1610     }
1611
1612     bool isNewError = foundErrorStr.insert( string( errBeg, ptr )).second;
1613     if ( !isNewError )
1614       continue; // not to report same error several times
1615
1616 //     const SMDS_MeshElement* nullElem = 0;
1617 //     bool allElemsOk = ( find( badElems.begin(), badElems.end(), nullElem) == badElems.end());
1618
1619 //     if ( allElemsOk && !badElems.empty() && !elemErrorNums.empty() ) {
1620 //       bool oneMoreErrorType = elemErrorNums.insert( errNum ).second;
1621 //       if ( oneMoreErrorType )
1622 //         continue; // not to report different types of errors with bad elements
1623 //     }
1624
1625     // store bad elements
1626     //if ( allElemsOk ) {
1627       list<const SMDS_MeshElement*>::iterator elem = badElems.begin();
1628       for ( ; elem != badElems.end(); ++elem )
1629         addBadInputElement( *elem );
1630       //}
1631
1632     // make error text
1633     string text = translateError( errNum );
1634     if ( errDescription.find( text ) == text.npos ) {
1635       if ( !errDescription.empty() )
1636         errDescription << "\n";
1637       errDescription << text;
1638     }
1639
1640   } // end while
1641
1642   if ( errDescription.empty() ) { // no errors found
1643     char msg[] = "connection to server failed";
1644     if ( search( &buf[0], bufEnd, msg, msg + strlen(msg)) != bufEnd )
1645       errDescription << "Licence problems.";
1646   }
1647
1648   if ( errDescription.empty() )
1649     errDescription << "See " << logFile << " for problem description";
1650   else
1651     errDescription << "\nSee " << logFile << " for more information";
1652
1653   return error( errDescription );
1654 }
1655
1656 //================================================================================
1657 /*!
1658  * \brief Creates _Ghs2smdsConvertor
1659  */
1660 //================================================================================
1661
1662 _Ghs2smdsConvertor::_Ghs2smdsConvertor( const map <int,const SMDS_MeshNode*> & ghs2NodeMap)
1663   :_ghs2NodeMap( & ghs2NodeMap ), _nodeByGhsId( 0 )
1664 {
1665 }
1666
1667 //================================================================================
1668 /*!
1669  * \brief Creates _Ghs2smdsConvertor
1670  */
1671 //================================================================================
1672
1673 _Ghs2smdsConvertor::_Ghs2smdsConvertor( const vector <const SMDS_MeshNode*> &  nodeByGhsId)
1674   : _ghs2NodeMap( 0 ), _nodeByGhsId( &nodeByGhsId )
1675 {
1676 }
1677
1678 //================================================================================
1679 /*!
1680  * \brief Return SMDS element by ids of GHS3D nodes
1681  */
1682 //================================================================================
1683
1684 const SMDS_MeshElement* _Ghs2smdsConvertor::getElement(const vector<int>& ghsNodes) const
1685 {
1686   size_t nbNodes = ghsNodes.size();
1687   vector<const SMDS_MeshNode*> nodes( nbNodes, 0 );
1688   for ( size_t i = 0; i < nbNodes; ++i ) {
1689     int ghsNode = ghsNodes[ i ];
1690     if ( _ghs2NodeMap ) {
1691       map <int,const SMDS_MeshNode*>::const_iterator in = _ghs2NodeMap->find( ghsNode);
1692       if ( in == _ghs2NodeMap->end() )
1693         return 0;
1694       nodes[ i ] = in->second;
1695     }
1696     else {
1697       if ( ghsNode < 1 || ghsNode > _nodeByGhsId->size() )
1698         return 0;
1699       nodes[ i ] = (*_nodeByGhsId)[ ghsNode-1 ];
1700     }
1701   }
1702   if ( nbNodes == 1 )
1703     return nodes[0];
1704
1705   if ( nbNodes == 2 ) {
1706     const SMDS_MeshElement* edge= SMDS_Mesh::FindEdge( nodes[0], nodes[1] );
1707     if ( !edge )
1708       edge = new SMDS_MeshEdge( nodes[0], nodes[1] );
1709     return edge;
1710   }
1711   if ( nbNodes == 3 ) {
1712     const SMDS_MeshElement* face = SMDS_Mesh::FindFace( nodes );
1713     if ( !face )
1714       face = new SMDS_FaceOfNodes( nodes[0], nodes[1], nodes[2] );
1715     return face;
1716   }
1717   if ( nbNodes == 4 )
1718     return new SMDS_VolumeOfNodes( nodes[0], nodes[1], nodes[2], nodes[3] );
1719
1720   return 0;
1721 }
1722