Salome HOME
Fix canceling of Compute()
[plugins/ghs3dplugin.git] / src / GHS3DPlugin / GHS3DPlugin_GHS3D.cxx
1 // Copyright (C) 2004-2013  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 //=============================================================================
21 // File      : GHS3DPlugin_GHS3D.cxx
22 // Created   : 
23 // Author    : Edward AGAPOV, modified by Lioka RAZAFINDRAZAKA (CEA) 09/02/2007
24 // Project   : SALOME
25 //=============================================================================
26 //
27 #include "GHS3DPlugin_GHS3D.hxx"
28 #include "GHS3DPlugin_Hypothesis.hxx"
29
30 #include <Basics_Utils.hxx>
31
32 //#include <SMESH_Gen.hxx>
33 #include <SMESH_Client.hxx>
34 #include <SMESH_Mesh.hxx>
35 #include <SMESH_Comment.hxx>
36 #include <SMESH_MesherHelper.hxx>
37 #include <SMESH_MeshEditor.hxx>
38 #include <SMESH_OctreeNode.hxx>
39 #include <SMESH_Group.hxx>
40 #include <SMESH_subMeshEventListener.hxx>
41 #include <SMESH_HypoFilter.hxx>
42 #include <SMESH_MeshAlgos.hxx>
43
44 #include <SMDS_MeshElement.hxx>
45 #include <SMDS_MeshNode.hxx>
46 #include <SMDS_FaceOfNodes.hxx>
47 #include <SMDS_VolumeOfNodes.hxx>
48
49 #include <SMESHDS_Group.hxx>
50
51 #include <StdMeshers_QuadToTriaAdaptor.hxx>
52 #include <StdMeshers_ViscousLayers.hxx>
53
54 #include <BRepAdaptor_Surface.hxx>
55 #include <BRepBndLib.hxx>
56 #include <BRepBuilderAPI_MakeVertex.hxx>
57 #include <BRepClass3d_SolidClassifier.hxx>
58 #include <BRepExtrema_DistShapeShape.hxx>
59 #include <BRepGProp.hxx>
60 #include <BRepTools.hxx>
61 #include <BRep_Tool.hxx>
62 #include <Bnd_Box.hxx>
63 #include <GProp_GProps.hxx>
64 #include <GeomAPI_ProjectPointOnSurf.hxx>
65 #include <OSD_File.hxx>
66 #include <Precision.hxx>
67 #include <Quantity_Parameter.hxx>
68 #include <Standard_ErrorHandler.hxx>
69 #include <Standard_Failure.hxx>
70 #include <Standard_ProgramError.hxx>
71 #include <TopExp.hxx>
72 #include <TopExp_Explorer.hxx>
73 #include <TopTools_IndexedMapOfShape.hxx>
74 #include <TopTools_ListIteratorOfListOfShape.hxx>
75 #include <TopTools_MapOfShape.hxx>
76 #include <TopoDS.hxx>
77 #include <TopoDS_Shape.hxx>
78 #include <TopoDS_Solid.hxx>
79
80 #include <utilities.h>
81
82 #ifdef WIN32
83 #include <io.h>
84 #else
85 #include <sys/sysinfo.h>
86 #endif
87 #include <algorithm>
88
89 //#include <Standard_Stream.hxx>
90
91
92 #define castToNode(n) static_cast<const SMDS_MeshNode *>( n );
93
94 #ifdef _DEBUG_
95 #define DUMP(txt) \
96 //  std::cout << txt
97 #else
98 #define DUMP(txt)
99 #endif
100
101 extern "C"
102 {
103 #ifndef WNT
104 #include <unistd.h>
105 #include <sys/mman.h>
106 #endif
107 #include <sys/stat.h>
108 #include <fcntl.h>
109 }
110
111 #define HOLE_ID -1
112
113 typedef const list<const SMDS_MeshFace*> TTriaList;
114
115 static const char theDomainGroupNamePrefix[] = "Domain_";
116
117 static void removeFile( const TCollection_AsciiString& fileName )
118 {
119   try {
120     OSD_File( fileName ).Remove();
121   }
122   catch ( Standard_ProgramError ) {
123     MESSAGE("Can't remove file: " << fileName.ToCString() << " ; file does not exist or permission denied");
124   }
125 }
126
127 //=============================================================================
128 /*!
129  *  
130  */
131 //=============================================================================
132
133 GHS3DPlugin_GHS3D::GHS3DPlugin_GHS3D(int hypId, int studyId, SMESH_Gen* gen)
134   : SMESH_3D_Algo(hypId, studyId, gen)
135 {
136   MESSAGE("GHS3DPlugin_GHS3D::GHS3DPlugin_GHS3D");
137   _name = Name();
138   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
139   _onlyUnaryInput = false; // Compute() will be called on a compound of solids
140   _iShape=0;
141   _nbShape=0;
142   _compatibleHypothesis.push_back( GHS3DPlugin_Hypothesis::GetHypType());
143   _compatibleHypothesis.push_back( StdMeshers_ViscousLayers::GetHypType() );
144   _requireShape = false; // can work without shape_studyId
145
146   smeshGen_i = SMESH_Gen_i::GetSMESHGen();
147   CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
148   SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
149
150   MESSAGE("studyid = " << _studyId);
151
152   myStudy = NULL;
153   myStudy = aStudyMgr->GetStudyByID(_studyId);
154   if (myStudy)
155     MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
156   
157   _compute_canceled = false;
158 }
159
160 //=============================================================================
161 /*!
162  *  
163  */
164 //=============================================================================
165
166 GHS3DPlugin_GHS3D::~GHS3DPlugin_GHS3D()
167 {
168   MESSAGE("GHS3DPlugin_GHS3D::~GHS3DPlugin_GHS3D");
169 }
170
171 //=============================================================================
172 /*!
173  *  
174  */
175 //=============================================================================
176
177 bool GHS3DPlugin_GHS3D::CheckHypothesis ( SMESH_Mesh&         aMesh,
178                                           const TopoDS_Shape& aShape,
179                                           Hypothesis_Status&  aStatus )
180 {
181   aStatus = SMESH_Hypothesis::HYP_OK;
182
183   _hyp = 0;
184   _viscousLayersHyp = 0;
185   _keepFiles = false;
186
187   const list <const SMESHDS_Hypothesis * >& hyps =
188     GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
189   list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
190   for ( ; h != hyps.end(); ++h )
191   {
192     if ( !_hyp )
193       _hyp = dynamic_cast< const GHS3DPlugin_Hypothesis*> ( *h );
194     if ( !_viscousLayersHyp )
195       _viscousLayersHyp = dynamic_cast< const StdMeshers_ViscousLayers*> ( *h );
196   }
197   if ( _hyp )
198     _keepFiles = _hyp->GetKeepFiles();
199
200   return true;
201 }
202
203
204 //=======================================================================
205 //function : entryToShape
206 //purpose  : 
207 //=======================================================================
208
209 TopoDS_Shape GHS3DPlugin_GHS3D::entryToShape(std::string entry)
210 {
211   MESSAGE("GHS3DPlugin_GHS3D::entryToShape "<<entry );
212   GEOM::GEOM_Object_var aGeomObj;
213   TopoDS_Shape S = TopoDS_Shape();
214   SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
215   if (!aSObj->_is_nil() ) {
216     CORBA::Object_var obj = aSObj->GetObject();
217     aGeomObj = GEOM::GEOM_Object::_narrow(obj);
218     aSObj->UnRegister();
219   }
220   if ( !aGeomObj->_is_nil() )
221     S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
222   return S;
223 }
224
225 //=======================================================================
226 //function : findShape
227 //purpose  : 
228 //=======================================================================
229
230 static TopoDS_Shape findShape(const SMDS_MeshNode *aNode[],
231                               TopoDS_Shape        aShape,
232                               const TopoDS_Shape  shape[],
233                               double**            box,
234                               const int           nShape,
235                               TopAbs_State *      state = 0)
236 {
237   gp_XYZ aPnt(0,0,0);
238   int j, iShape, nbNode = 4;
239
240   for ( j=0; j<nbNode; j++ ) {
241     gp_XYZ p ( aNode[j]->X(), aNode[j]->Y(), aNode[j]->Z() );
242     if ( aNode[j]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE ) {
243       aPnt = p;
244       break;
245     }
246     aPnt += p / nbNode;
247   }
248
249   BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
250   if (state) *state = SC.State();
251   if ( SC.State() != TopAbs_IN || aShape.IsNull() || aShape.ShapeType() != TopAbs_SOLID) {
252     for (iShape = 0; iShape < nShape; iShape++) {
253       aShape = shape[iShape];
254       if ( !( aPnt.X() < box[iShape][0] || box[iShape][1] < aPnt.X() ||
255               aPnt.Y() < box[iShape][2] || box[iShape][3] < aPnt.Y() ||
256               aPnt.Z() < box[iShape][4] || box[iShape][5] < aPnt.Z()) ) {
257         BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
258         if (state) *state = SC.State();
259         if (SC.State() == TopAbs_IN)
260           break;
261       }
262     }
263   }
264   return aShape;
265 }
266
267 //=======================================================================
268 //function : readMapIntLine
269 //purpose  : 
270 //=======================================================================
271
272 static char* readMapIntLine(char* ptr, int tab[]) {
273   long int intVal;
274   std::cout << std::endl;
275
276   for ( int i=0; i<17; i++ ) {
277     intVal = strtol(ptr, &ptr, 10);
278     if ( i < 3 )
279       tab[i] = intVal;
280   }
281   return ptr;
282 }
283
284 //================================================================================
285 /*!
286  * \brief returns true if a triangle defined by the nodes is a temporary face on a
287  * side facet of pyramid and defines sub-domian inside the pyramid
288  */
289 //================================================================================
290
291 static bool isTmpFace(const SMDS_MeshNode* node1,
292                       const SMDS_MeshNode* node2,
293                       const SMDS_MeshNode* node3)
294 {
295   // find a pyramid sharing the 3 nodes
296   //const SMDS_MeshElement* pyram = 0;
297   SMDS_ElemIteratorPtr vIt1 = node1->GetInverseElementIterator(SMDSAbs_Volume);
298   while ( vIt1->more() )
299   {
300     const SMDS_MeshElement* pyram = vIt1->next();
301     if ( pyram->NbCornerNodes() != 5 ) continue;
302     int i2, i3;
303     if ( (i2 = pyram->GetNodeIndex( node2 )) >= 0 &&
304          (i3 = pyram->GetNodeIndex( node3 )) >= 0 )
305     {
306       // Triangle defines sub-domian inside the pyramid if it's
307       // normal points out of the pyram
308
309       // make i2 and i3 hold indices of base nodes of the pyram while
310       // keeping the nodes order in the triangle
311       const int iApex = 4;
312       if ( i2 == iApex )
313         i2 = i3, i3 = pyram->GetNodeIndex( node1 );
314       else if ( i3 == iApex )
315         i3 = i2, i2 = pyram->GetNodeIndex( node1 );
316
317       int i3base = (i2+1) % 4; // next index after i2 within the pyramid base
318       return ( i3base != i3 );
319     }
320   }
321   return false;
322 }
323
324 //=======================================================================
325 //function : findShapeID
326 //purpose  : find the solid corresponding to GHS3D sub-domain following
327 //           the technique proposed in GHS3D manual (available within
328 //           ghs3d installation) in chapter "B.4 Subdomain (sub-region) assignment".
329 //           In brief: normal of the triangle defined by the given nodes
330 //           points out of the domain it is associated to
331 //=======================================================================
332
333 static int findShapeID(SMESH_Mesh&          mesh,
334                        const SMDS_MeshNode* node1,
335                        const SMDS_MeshNode* node2,
336                        const SMDS_MeshNode* node3,
337                        const bool           toMeshHoles)
338 {
339   const int invalidID = 0;
340   SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
341
342   // face the nodes belong to
343   const SMDS_MeshElement * face = meshDS->FindFace(node1,node2,node3);
344   if ( !face )
345     return isTmpFace(node1, node2, node3) ? HOLE_ID : invalidID;
346 #ifdef _DEBUG_
347   std::cout << "bnd face " << face->GetID() << " - ";
348 #endif
349   // geom face the face assigned to
350   SMESH_MeshEditor editor(&mesh);
351   int geomFaceID = editor.FindShape( face );
352   if ( !geomFaceID )
353     return isTmpFace(node1, node2, node3) ? HOLE_ID : invalidID;
354   TopoDS_Shape shape = meshDS->IndexToShape( geomFaceID );
355   if ( shape.IsNull() || shape.ShapeType() != TopAbs_FACE )
356     return invalidID;
357   TopoDS_Face geomFace = TopoDS::Face( shape );
358
359   // solids bounded by geom face
360   TopTools_IndexedMapOfShape solids, shells;
361   TopTools_ListIteratorOfListOfShape ansIt = mesh.GetAncestors(geomFace);
362   for ( ; ansIt.More(); ansIt.Next() ) {
363     switch ( ansIt.Value().ShapeType() ) {
364     case TopAbs_SOLID:
365       solids.Add( ansIt.Value() ); break;
366     case TopAbs_SHELL:
367       shells.Add( ansIt.Value() ); break;
368     default:;
369     }
370   }
371   // analyse found solids
372   if ( solids.Extent() == 0 || shells.Extent() == 0)
373     return invalidID;
374
375   const TopoDS_Solid& solid1 = TopoDS::Solid( solids(1) );
376   if ( solids.Extent() == 1 )
377   {
378     if ( toMeshHoles )
379       return meshDS->ShapeToIndex( solid1 );
380
381     //////////// UNCOMMENT AS SOON AS
382     //////////// http://tracker.dev.opencascade.org/view.php?id=23129
383     //////////// IS SOLVED
384     // - Are we at a hole boundary face?
385     // if ( shells(1).IsSame( BRepTools::OuterShell( solid1 )) )
386     // { // - No, but maybe a hole is bound by two shapes? Does shells(1) touches another shell?
387     //   bool touch = false;
388     //   TopExp_Explorer eExp( shells(1), TopAbs_EDGE );
389     //   // check if any edge of shells(1) belongs to another shell
390     //   for ( ; eExp.More() && !touch; eExp.Next() ) {
391     //     ansIt = mesh.GetAncestors( eExp.Current() );
392     //     for ( ; ansIt.More() && !touch; ansIt.Next() ) {
393     //       if ( ansIt.Value().ShapeType() == TopAbs_SHELL )
394     //         touch = ( !ansIt.Value().IsSame( shells(1) ));
395     //     }
396     //   }
397     //   if (!touch)
398     //     return meshDS->ShapeToIndex( solid1 );
399     // }
400   }
401   // find orientation of geom face within the first solid
402   TopExp_Explorer fExp( solid1, TopAbs_FACE );
403   for ( ; fExp.More(); fExp.Next() )
404     if ( geomFace.IsSame( fExp.Current() )) {
405       geomFace = TopoDS::Face( fExp.Current() );
406       break;
407     }
408   if ( !fExp.More() )
409     return invalidID; // face not found
410
411   // normale to triangle
412   gp_Pnt node1Pnt ( node1->X(), node1->Y(), node1->Z() );
413   gp_Pnt node2Pnt ( node2->X(), node2->Y(), node2->Z() );
414   gp_Pnt node3Pnt ( node3->X(), node3->Y(), node3->Z() );
415   gp_Vec vec12( node1Pnt, node2Pnt );
416   gp_Vec vec13( node1Pnt, node3Pnt );
417   gp_Vec meshNormal = vec12 ^ vec13;
418   if ( meshNormal.SquareMagnitude() < DBL_MIN )
419     return invalidID;
420
421   // get normale to geomFace at any node
422   bool geomNormalOK = false;
423   gp_Vec geomNormal;
424   const SMDS_MeshNode* nodes[3] = { node1, node2, node3 };
425   SMESH_MesherHelper helper( mesh ); helper.SetSubShape( geomFace );
426   for ( int i = 0; !geomNormalOK && i < 3; ++i )
427   {
428     // find UV of i-th node on geomFace
429     const SMDS_MeshNode* nNotOnSeamEdge = 0;
430     if ( helper.IsSeamShape( nodes[i]->getshapeId() )) {
431       if ( helper.IsSeamShape( nodes[(i+1)%3]->getshapeId() ))
432         nNotOnSeamEdge = nodes[(i+2)%3];
433       else
434         nNotOnSeamEdge = nodes[(i+1)%3];
435     }
436     bool uvOK;
437     gp_XY uv = helper.GetNodeUV( geomFace, nodes[i], nNotOnSeamEdge, &uvOK );
438     // check that uv is correct
439     if (uvOK) {
440       double tol = 1e-6;
441       TopoDS_Shape nodeShape = helper.GetSubShapeByNode( nodes[i], meshDS );
442       if ( !nodeShape.IsNull() )
443         switch ( nodeShape.ShapeType() )
444         {
445         case TopAbs_FACE:   tol = BRep_Tool::Tolerance( TopoDS::Face( nodeShape )); break;
446         case TopAbs_EDGE:   tol = BRep_Tool::Tolerance( TopoDS::Edge( nodeShape )); break;
447         case TopAbs_VERTEX: tol = BRep_Tool::Tolerance( TopoDS::Vertex( nodeShape )); break;
448         default:;
449         }
450       gp_Pnt nodePnt ( nodes[i]->X(), nodes[i]->Y(), nodes[i]->Z() );
451       BRepAdaptor_Surface surface( geomFace );
452       uvOK = ( nodePnt.Distance( surface.Value( uv.X(), uv.Y() )) < 2 * tol );
453       if ( uvOK ) {
454         // normale to geomFace at UV
455         gp_Vec du, dv;
456         surface.D1( uv.X(), uv.Y(), nodePnt, du, dv );
457         geomNormal = du ^ dv;
458         if ( geomFace.Orientation() == TopAbs_REVERSED )
459           geomNormal.Reverse();
460         geomNormalOK = ( geomNormal.SquareMagnitude() > DBL_MIN * 1e3 );
461       }
462     }
463   }
464   if ( !geomNormalOK)
465     return invalidID;
466
467   // compare normals
468   bool isReverse = ( meshNormal * geomNormal ) < 0;
469   if ( !isReverse )
470     return meshDS->ShapeToIndex( solid1 );
471
472   if ( solids.Extent() == 1 )
473     return HOLE_ID; // we are inside a hole
474   else
475     return meshDS->ShapeToIndex( solids(2) );
476 }
477
478 // //=======================================================================
479 // //function : countShape
480 // //purpose  :
481 // //=======================================================================
482 // 
483 // template < class Mesh, class Shape >
484 // static int countShape( Mesh* mesh, Shape shape ) {
485 //   TopExp_Explorer expShape ( mesh->ShapeToMesh(), shape );
486 //   TopTools_MapOfShape mapShape;
487 //   int nbShape = 0;
488 //   for ( ; expShape.More(); expShape.Next() ) {
489 //     if (mapShape.Add(expShape.Current())) {
490 //       nbShape++;
491 //     }
492 //   }
493 //   return nbShape;
494 // }
495 // 
496 // //=======================================================================
497 // //function : getShape
498 // //purpose  :
499 // //=======================================================================
500 // 
501 // template < class Mesh, class Shape, class Tab >
502 // void getShape(Mesh* mesh, Shape shape, Tab *t_Shape) {
503 //   TopExp_Explorer expShape ( mesh->ShapeToMesh(), shape );
504 //   TopTools_MapOfShape mapShape;
505 //   for ( int i=0; expShape.More(); expShape.Next() ) {
506 //     if (mapShape.Add(expShape.Current())) {
507 //       t_Shape[i] = expShape.Current();
508 //       i++;
509 //     }
510 //   }
511 //   return;
512 // }
513 // 
514 // // //=======================================================================
515 // // //function : findEdgeID
516 // // //purpose  :
517 // // //=======================================================================
518 // 
519 // static int findEdgeID(const SMDS_MeshNode* aNode,
520 //                       const SMESHDS_Mesh*  theMesh,
521 //                       const int            nEdge,
522 //                       const TopoDS_Shape*  t_Edge) {
523 // 
524 //   TopoDS_Shape aPntShape, foundEdge;
525 //   TopoDS_Vertex aVertex;
526 //   gp_Pnt aPnt( aNode->X(), aNode->Y(), aNode->Z() );
527 // 
528 //   int foundInd, ind;
529 //   double nearest = RealLast(), *t_Dist;
530 //   double epsilon = Precision::Confusion();
531 // 
532 //   t_Dist = new double[ nEdge ];
533 //   aPntShape = BRepBuilderAPI_MakeVertex( aPnt ).Shape();
534 //   aVertex   = TopoDS::Vertex( aPntShape );
535 // 
536 //   for ( ind=0; ind < nEdge; ind++ ) {
537 //     BRepExtrema_DistShapeShape aDistance ( aVertex, t_Edge[ind] );
538 //     t_Dist[ind] = aDistance.Value();
539 //     if ( t_Dist[ind] < nearest ) {
540 //       nearest   = t_Dist[ind];
541 //       foundEdge = t_Edge[ind];
542 //       foundInd  = ind;
543 //       if ( nearest < epsilon )
544 //         ind = nEdge;
545 //     }
546 //   }
547 // 
548 //   delete [] t_Dist;
549 //   return theMesh->ShapeToIndex( foundEdge );
550 // }
551 // 
552 // 
553 // // =======================================================================
554 // // function : readGMFFile
555 // // purpose  : read GMF file with geometry associated to mesh
556 // // =======================================================================
557 // 
558 // static bool readGMFFile(const int                       fileOpen,
559 //                         const char*                     theFileName, 
560 //                         SMESH_Mesh&                     theMesh,
561 //                         const int                       nbShape,
562 //                         const TopoDS_Shape*             tabShape,
563 //                         double**                        tabBox,
564 //                         map <int,const SMDS_MeshNode*>& theGhs3dIdToNodeMap,
565 //                         bool                            toMeshHoles,
566 //                         int                             nbEnforcedVertices,
567 //                         int                             nbEnforcedNodes)
568 // {
569 //   TopoDS_Shape aShape;
570 //   TopoDS_Vertex aVertex;
571 //   SMESHDS_Mesh* theMeshDS = theMesh.GetMeshDS();
572 //   int nbElem = 0, nbRef = 0, IdShapeRef = 1;
573 //   int *tabID;
574 //   int aGMFNodeID = 0;
575 //   int compoundID =
576 //     nbShape ? theMeshDS->ShapeToIndex( tabShape[0] ) : theMeshDS->ShapeToIndex( theMeshDS->ShapeToMesh() );
577 //   int tetraShapeID = compoundID;
578 //   double epsilon = Precision::Confusion();
579 //   int *nodeAssigne, *GMFNodeAssigne;
580 //   SMDS_MeshNode** GMFNode;
581 //   TopoDS_Shape *tabCorner, *tabEdge;
582 //   std::map <GmfKwdCod,int> tabRef;
583 //   
584 //   
585 //   int ver, dim;
586 //   MESSAGE("Read " << theFileName << " file");
587 //   int InpMsh = GmfOpenMesh(theFileName, GmfRead, &ver, &dim);
588 //   if (!InpMsh)
589 //     return false;
590 //   
591 //   // ===========================
592 //   // Fill the tabID array: BEGIN
593 //   // ===========================
594 //   
595 //   /*
596 //   The output .mesh file does not contain yet the subdomain-info (Ghs3D 4.2)
597 //   */
598 //   Kernel_Utils::Localizer loc;
599 //   struct stat status;
600 //   size_t      length;
601 // 
602 //   char *ptr, *mapPtr;
603 //   char *tetraPtr;
604 //   int *tab = new int[3];
605 //   
606 //   // Read the file state
607 //   fstat(fileOpen, &status);
608 //   length   = status.st_size;
609 //   
610 //   // Mapping the result file into memory
611 // #ifdef WNT
612 //   HANDLE fd = CreateFile(theFileName, GENERIC_READ, FILE_SHARE_READ,
613 //                          NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
614 //   HANDLE hMapObject = CreateFileMapping(fd, NULL, PAGE_READONLY,
615 //                                         0, (DWORD)length, NULL);
616 //   ptr = ( char* ) MapViewOfFile(hMapObject, FILE_MAP_READ, 0, 0, 0 );
617 // #else
618 //   ptr = (char *) mmap(0,length,PROT_READ,MAP_PRIVATE,fileOpen,0);
619 // #endif
620 //   mapPtr = ptr;
621 // 
622 //   ptr      = readMapIntLine(ptr, tab);
623 //   tetraPtr = ptr;
624 // 
625 //   nbElem            = tab[0];
626 //   int nbNodes       = tab[1];
627 //   
628 //   for (int i=0; i < 4*nbElem; i++)
629 //     strtol(ptr, &ptr, 10);
630 //   
631 //   for (int iNode=1; iNode <= nbNodes; iNode++)
632 //     for (int iCoor=0; iCoor < 3; iCoor++)
633 //       strtod(ptr, &ptr);
634 // 
635 //     
636 //   // Reading the number of triangles which corresponds to the number of sub-domains
637 //   int nbTriangle = strtol(ptr, &ptr, 10);
638 // 
639 //   
640 //   // The keyword does not exist yet => to update when it is created
641 // //   int nbSubdomains = GmfStatKwd(InpMsh, GmfSubdomain);
642 // //   int id_tri[3];
643 // 
644 // 
645 //   tabID = new int[nbTriangle];
646 //   for (int i=0; i < nbTriangle; i++) {
647 //     tabID[i] = 0;
648 //     int nodeId1, nodeId2, nodeId3;
649 //     // find the solid corresponding to GHS3D sub-domain following
650 //     // the technique proposed in GHS3D manual in chapter
651 //     // "B.4 Subdomain (sub-region) assignment"
652 // 
653 //     nodeId1 = strtol(ptr, &ptr, 10);
654 //     nodeId2 = strtol(ptr, &ptr, 10);
655 //     nodeId3 = strtol(ptr, &ptr, 10);
656 // 
657 // //   // The keyword does not exist yet => to update when it is created
658 // //     GmfGetLin(InpMsh, GmfSubdomain, &id_tri[0], &id_tri[1], &id_tri[2]);
659 // //     nodeId1 = id_tri[0];
660 // //     nodeId2 = id_tri[1];
661 // //     nodeId3 = id_tri[2];
662 // 
663 //     if ( nbTriangle > 1 ) {
664 //       // get the nodes indices
665 //       const SMDS_MeshNode* n1 = theGhs3dIdToNodeMap[ nodeId1 ];
666 //       const SMDS_MeshNode* n2 = theGhs3dIdToNodeMap[ nodeId2 ];
667 //       const SMDS_MeshNode* n3 = theGhs3dIdToNodeMap[ nodeId3 ];
668 //       try {
669 //         OCC_CATCH_SIGNALS;
670 //         tabID[i] = findShapeID( theMesh, n1, n2, n3, toMeshHoles );
671 //         // -- 0020330: Pb with ghs3d as a submesh
672 //         // check that found shape is to be meshed
673 //         if ( tabID[i] > 0 ) {
674 //           const TopoDS_Shape& foundShape = theMeshDS->IndexToShape( tabID[i] );
675 //           bool isToBeMeshed = false;
676 //           for ( int iS = 0; !isToBeMeshed && iS < nbShape; ++iS )
677 //             isToBeMeshed = foundShape.IsSame( tabShape[ iS ]);
678 //           if ( !isToBeMeshed )
679 //             tabID[i] = HOLE_ID;
680 //         }
681 //         // END -- 0020330: Pb with ghs3d as a submesh
682 // #ifdef _DEBUG_
683 //         std::cout << i+1 << " subdomain: findShapeID() returns " << tabID[i] << std::endl;
684 // #endif
685 //       }
686 //       catch ( Standard_Failure & ex)
687 //       {
688 // #ifdef _DEBUG_
689 //         std::cout << i+1 << " subdomain: Exception caugt: " << ex.GetMessageString() << std::endl;
690 // #endif
691 //       }
692 //       catch (...) {
693 // #ifdef _DEBUG_
694 //         std::cout << i+1 << " subdomain: unknown exception caught " << std::endl;
695 // #endif
696 //       }
697 //     }
698 //   }
699 //   
700 //   // ===========================
701 //   // Fill the tabID array: END
702 //   // ===========================
703 //   
704 // 
705 //   tabRef[GmfVertices]       = 3;
706 //   tabRef[GmfCorners]        = 1;
707 //   tabRef[GmfEdges]          = 2;
708 //   tabRef[GmfRidges]         = 1;
709 //   tabRef[GmfTriangles]      = 3;
710 // //   tabRef[GmfQuadrilaterals] = 4;
711 //   tabRef[GmfTetrahedra]     = 4;
712 // //   tabRef[GmfHexahedra]      = 8;
713 //   
714 //   SMDS_NodeIteratorPtr itOnGMFInputNode = theMeshDS->nodesIterator();
715 //   while ( itOnGMFInputNode->more() )
716 //     theMeshDS->RemoveNode( itOnGMFInputNode->next() );
717 // 
718 //   
719 //   int nbVertices = GmfStatKwd(InpMsh, GmfVertices);
720 //   int nbCorners = max(countShape( theMeshDS, TopAbs_VERTEX ) , GmfStatKwd(InpMsh, GmfCorners));
721 //   int nbShapeEdge = countShape( theMeshDS, TopAbs_EDGE );
722 // 
723 //   tabCorner       = new TopoDS_Shape[ nbCorners ];
724 //   tabEdge         = new TopoDS_Shape[ nbShapeEdge ];
725 //   nodeAssigne     = new int[ nbVertices + 1 ];
726 //   GMFNodeAssigne  = new int[ nbVertices + 1 ];
727 //   GMFNode         = new SMDS_MeshNode*[ nbVertices + 1 ];
728 // 
729 //   getShape(theMeshDS, TopAbs_VERTEX, tabCorner);
730 //   getShape(theMeshDS, TopAbs_EDGE,   tabEdge);
731 // 
732 //   std::map <GmfKwdCod,int>::const_iterator it = tabRef.begin();
733 //   for ( ; it != tabRef.end() ; ++it)
734 //   {
735 // //     int dummy;
736 //     GmfKwdCod token = it->first;
737 //     nbRef    = it->second;
738 // 
739 //     nbElem = GmfStatKwd(InpMsh, token);
740 //     if (nbElem > 0) {
741 //       GmfGotoKwd(InpMsh, token);
742 //       std::cout << "Read " << nbElem;
743 //     }
744 //     else
745 //       continue;
746 // 
747 //     int id[nbElem*tabRef[token]];
748 //     int ghs3dShapeID[nbElem];
749 // 
750 //     if (token == GmfVertices) {
751 //       std::cout << " vertices" << std::endl;
752 //       int aGMFID;
753 // 
754 //       float VerTab_f[nbElem][3];
755 //       double VerTab_d[nbElem][3];
756 //       SMDS_MeshNode * aGMFNode;
757 // 
758 //       for ( int iElem = 0; iElem < nbElem; iElem++ ) {
759 //         aGMFID = iElem + 1;
760 //         if (ver == GmfFloat) {
761 //           GmfGetLin(InpMsh, token, &VerTab_f[nbElem][0], &VerTab_f[nbElem][1], &VerTab_f[nbElem][2], &ghs3dShapeID[iElem]);
762 //           aGMFNode = theMeshDS->AddNode(VerTab_f[nbElem][0], VerTab_f[nbElem][1], VerTab_f[nbElem][2]);
763 //         }
764 //         else {
765 //           GmfGetLin(InpMsh, token, &VerTab_d[nbElem][0], &VerTab_d[nbElem][1], &VerTab_d[nbElem][2], &ghs3dShapeID[iElem]);
766 //           aGMFNode = theMeshDS->AddNode(VerTab_d[nbElem][0], VerTab_d[nbElem][1], VerTab_d[nbElem][2]);
767 //         }
768 //         GMFNode[ aGMFID ] = aGMFNode;
769 //         nodeAssigne[ aGMFID ] = 0;
770 //         GMFNodeAssigne[ aGMFID ] = 0;
771 //       }
772 //     }
773 //     else if (token == GmfCorners && nbElem > 0) {
774 //       std::cout << " corners" << std::endl;
775 //       for ( int iElem = 0; iElem < nbElem; iElem++ )
776 //         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]]);
777 //     }
778 //     else if (token == GmfRidges && nbElem > 0) {
779 //       std::cout << " ridges" << std::endl;
780 //       for ( int iElem = 0; iElem < nbElem; iElem++ )
781 //         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]]);
782 //     }
783 //     else if (token == GmfEdges && nbElem > 0) {
784 //       std::cout << " edges" << std::endl;
785 //       for ( int iElem = 0; iElem < nbElem; iElem++ )
786 //         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &ghs3dShapeID[iElem]);
787 //     }
788 //     else if (token == GmfTriangles && nbElem > 0) {
789 //       std::cout << " triangles" << std::endl;
790 //       for ( int iElem = 0; iElem < nbElem; iElem++ )
791 //         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &ghs3dShapeID[iElem]);
792 //     }
793 // //     else if (token == GmfQuadrilaterals && nbElem > 0) {
794 // //       std::cout << " Quadrilaterals" << std::endl;
795 // //       for ( int iElem = 0; iElem < nbElem; iElem++ )
796 // //         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3], &ghs3dShapeID[iElem]);
797 // //     }
798 //     else if (token == GmfTetrahedra && nbElem > 0) {
799 //       std::cout << " Tetrahedra" << std::endl;
800 //       for ( int iElem = 0; iElem < nbElem; iElem++ )
801 //         GmfGetLin(InpMsh, token, 
802 //                   &id[iElem*tabRef[token]], 
803 //                   &id[iElem*tabRef[token]+1], 
804 //                   &id[iElem*tabRef[token]+2], 
805 //                   &id[iElem*tabRef[token]+3], 
806 //                   &ghs3dShapeID[iElem]);
807 //     }
808 // //     else if (token == GmfHexahedra && nbElem > 0) {
809 // //       std::cout << " Hexahedra" << std::endl;
810 // //       for ( int iElem = 0; iElem < nbElem; iElem++ )
811 // //         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3],
812 // //                   &id[iElem*tabRef[token]+4], &id[iElem*tabRef[token]+5], &id[iElem*tabRef[token]+6], &id[iElem*tabRef[token]+7], &ghs3dShapeID[iElem]);
813 // //     }
814 // 
815 //     switch (token) {
816 //     case GmfCorners:
817 //     case GmfRidges:
818 //     case GmfEdges:
819 //     case GmfTriangles:
820 // //     case GmfQuadrilaterals:
821 //     case GmfTetrahedra:
822 // //     case GmfHexahedra:
823 //     {
824 //       int nodeDim, shapeID, *nodeID;
825 //       const SMDS_MeshNode** node;
826 // //       std::vector< SMDS_MeshNode* > enfNode( nbRef );
827 //       SMDS_MeshElement * aGMFElement;
828 //       
829 //       node    = new const SMDS_MeshNode*[nbRef];
830 //       nodeID  = new int[ nbRef ];
831 // 
832 //       for ( int iElem = 0; iElem < nbElem; iElem++ )
833 //       {
834 //         for ( int iRef = 0; iRef < nbRef; iRef++ )
835 //         {
836 //           aGMFNodeID = id[iElem*tabRef[token]+iRef]; // read nbRef aGMFNodeID
837 //           node  [ iRef ] = GMFNode[ aGMFNodeID ];
838 //           nodeID[ iRef ] = aGMFNodeID;
839 //         }
840 // 
841 //         switch (token)
842 //         {
843 //         case GmfCorners: {
844 //           nodeDim = 1;
845 //           gp_Pnt GMFPnt ( node[0]->X(), node[0]->Y(), node[0]->Z() );
846 //           for ( int i=0; i<nbElem; i++ ) {
847 //             aVertex = TopoDS::Vertex( tabCorner[i] );
848 //             gp_Pnt aPnt = BRep_Tool::Pnt( aVertex );
849 //             if ( aPnt.Distance( GMFPnt ) < epsilon )
850 //               break;
851 //           }
852 //           break;
853 //         }
854 //         case GmfEdges: {
855 //           nodeDim = 2;
856 //           aGMFElement = theMeshDS->AddEdge( node[0], node[1] );
857 //           int iNode = 1;
858 //           if ( GMFNodeAssigne[ nodeID[0] ] == 0 || GMFNodeAssigne[ nodeID[0] ] == 2 )
859 //             iNode = 0;
860 //           shapeID = findEdgeID( node[iNode], theMeshDS, nbShapeEdge, tabEdge );
861 //           break;
862 //         }
863 //         case GmfRidges:
864 //           break;
865 //         case GmfTriangles: {
866 //           nodeDim = 3;
867 //           aGMFElement = theMeshDS->AddFace( node[0], node[1], node[2]);
868 //           shapeID = -1;
869 //           break;
870 //         }
871 // //         case GmfQuadrilaterals: {
872 // //           nodeDim = 4;
873 // //           aGMFElement = theMeshDS->AddFace( node[0], node[1], node[2], node[3] );
874 // //           shapeID = -1;
875 // //           break;
876 // //         }
877 //         case GmfTetrahedra: {
878 //           
879 //           // IN WORK
880 //           TopoDS_Shape aSolid;
881 //           // We always run GHS3D with "to mesh holes"==TRUE but we must not create
882 //           // tetras within holes depending on hypo option,
883 //           // so we first check if aTet is inside a hole and then create it 
884 //           if ( nbTriangle > 1 ) {
885 //             tetraShapeID = HOLE_ID; // negative tetraShapeID means not to create tetras if !toMeshHoles
886 //             int aGhs3dShapeID = ghs3dShapeID[iElem] - IdShapeRef;
887 //             if ( tabID[ aGhs3dShapeID ] == 0 ) {
888 //               TopAbs_State state;
889 //               aSolid = findShape(node, aSolid, tabShape, tabBox, nbShape, &state);
890 //               if ( toMeshHoles || state == TopAbs_IN )
891 //                 tetraShapeID = theMeshDS->ShapeToIndex( aSolid );
892 //               tabID[ aGhs3dShapeID ] = tetraShapeID;
893 //             }
894 //             else
895 //               tetraShapeID = tabID[ aGhs3dShapeID ];
896 //           }
897 //           else if ( nbShape > 1 ) {
898 //             // Case where nbTriangle == 1 while nbShape == 2 encountered
899 //             // with compound of 2 boxes and "To mesh holes"==False,
900 //             // so there are no subdomains specified for each tetrahedron.
901 //             // Try to guess a solid by a node already bound to shape
902 //             tetraShapeID = 0;
903 //             for ( int i=0; i<4 && tetraShapeID==0; i++ ) {
904 //               if ( nodeAssigne[ nodeID[i] ] == 1 &&
905 //                   node[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE &&
906 //                   node[i]->getshapeId() > 1 )
907 //               {
908 //                 tetraShapeID = node[i]->getshapeId();
909 //               }
910 //             }
911 //             if ( tetraShapeID==0 ) {
912 //               aSolid = findShape(node, aSolid, tabShape, tabBox, nbShape);
913 //               tetraShapeID = theMeshDS->ShapeToIndex( aSolid );
914 //             }
915 //           }
916 //           // set new nodes and tetrahedron onto the shape
917 //           for ( int i=0; i<4; i++ ) {
918 //             if ( nodeAssigne[ nodeID[i] ] == 0 ) {
919 //               if ( tetraShapeID != HOLE_ID )
920 //                 theMeshDS->SetNodeInVolume( node[i], tetraShapeID );
921 //               nodeAssigne[ nodeID[i] ] = tetraShapeID;
922 //             }
923 //           }
924 //           if ( toMeshHoles || tetraShapeID != HOLE_ID ) {
925 //             aGMFElement = theMeshDS->AddVolume( node[1], node[0], node[2], node[3] );
926 //             theMeshDS->SetMeshElementOnShape( aGMFElement, tetraShapeID );
927 //           }
928 //           
929 //           // IN WORK
930 //           
931 //           nodeDim = 5;
932 //           break;
933 //         }
934 // //         case GmfHexahedra: {
935 // //           nodeDim = 6;
936 // //           aGMFElement = theMeshDS->AddVolume( node[0], node[3], node[2], node[1],
937 // //                                             node[4], node[7], node[6], node[5] );
938 // //           break;
939 // //         }
940 //         default: continue;
941 //         }
942 //         if (token != GmfRidges)
943 //         {
944 //           for ( int i=0; i<nbRef; i++ ) {
945 //               if ( GMFNodeAssigne[ nodeID[i] ] == 0 ) {
946 //                 if      ( token == GmfCorners )   theMeshDS->SetNodeOnVertex( node[0], aVertex );
947 //                 else if ( token == GmfEdges )     theMeshDS->SetNodeOnEdge( node[i], shapeID );
948 //                 else if ( token == GmfTriangles ) theMeshDS->SetNodeOnFace( node[i], shapeID );
949 //                 GMFNodeAssigne[ nodeID[i] ] = nodeDim;
950 //               }
951 //             }
952 //             if ( token != "Corners" )
953 //               theMeshDS->SetMeshElementOnShape( aGMFElement, shapeID );
954 //         }
955 //       } // for
956 //       
957 //       if ( !toMeshHoles ) {
958 //         map <int,const SMDS_MeshNode*>::iterator itOnNode = theGhs3dIdToNodeMap.find( nbVertices-(nbEnforcedVertices+nbEnforcedNodes) );
959 //         for ( ; itOnNode != theGhs3dIdToNodeMap.end(); ++itOnNode) {
960 //           if ( nodeAssigne[ itOnNode->first ] == HOLE_ID )
961 //             theMeshDS->RemoveFreeNode( itOnNode->second, 0 );
962 //         }
963 //       }
964 //       
965 //       delete [] node;
966 //       delete [] nodeID;
967 //       break;
968 //       } // case GmfTetrahedra
969 //     } // switch(token)
970 //   } // for
971 //   cout << std::endl;
972 //   
973 // #ifdef WNT
974 //   UnmapViewOfFile(mapPtr);
975 //   CloseHandle(hMapObject);
976 //   CloseHandle(fd);
977 // #else
978 //   munmap(mapPtr, length);
979 // #endif
980 //   close(fileOpen);
981 //   
982 //   delete [] tabID;
983 //   delete [] tabCorner;
984 //   delete [] tabEdge;
985 //   delete [] nodeAssigne;
986 //   delete [] GMFNodeAssigne;
987 //   delete [] GMFNode;
988 //   
989 //   return true;
990 // }
991
992
993 //=======================================================================
994 //function : addElemInMeshGroup
995 //purpose  : Update or create groups in mesh
996 //=======================================================================
997
998 static void addElemInMeshGroup(SMESH_Mesh*             theMesh,
999                                const SMDS_MeshElement* anElem,
1000                                std::string&            groupName,
1001                                std::set<std::string>&  groupsToRemove)
1002 {
1003   if ( !anElem ) return; // issue 0021776
1004
1005   bool groupDone = false;
1006   SMESH_Mesh::GroupIteratorPtr grIt = theMesh->GetGroups();
1007   while (grIt->more()) {
1008     SMESH_Group * group = grIt->next();
1009     if ( !group ) continue;
1010     SMESHDS_GroupBase* groupDS = group->GetGroupDS();
1011     if ( !groupDS ) continue;
1012     if ( groupDS->GetType()==anElem->GetType() &&groupName.compare(group->GetName())==0) {
1013       SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
1014       aGroupDS->SMDSGroup().Add(anElem);
1015       groupDone = true;
1016 //       MESSAGE("Successfully added enforced element to existing group " << groupName);
1017       break;
1018     }
1019   }
1020   
1021   if (!groupDone)
1022   {
1023     int groupId;
1024     SMESH_Group* aGroup = theMesh->AddGroup(anElem->GetType(), groupName.c_str(), groupId);
1025     aGroup->SetName( groupName.c_str() );
1026     SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
1027     aGroupDS->SMDSGroup().Add(anElem);
1028 //     MESSAGE("Successfully created enforced vertex group " << groupName);
1029     groupDone = true;
1030   }
1031   if (!groupDone)
1032     throw SALOME_Exception(LOCALIZED("A given element was not added to a group"));
1033 }
1034
1035
1036 //=======================================================================
1037 //function : updateMeshGroups
1038 //purpose  : Update or create groups in mesh
1039 //=======================================================================
1040
1041 static void updateMeshGroups(SMESH_Mesh* theMesh, std::set<std::string> groupsToRemove)
1042 {
1043   SMESH_Mesh::GroupIteratorPtr grIt = theMesh->GetGroups();
1044   while (grIt->more()) {
1045     SMESH_Group * group = grIt->next();
1046     if ( !group ) continue;
1047     SMESHDS_GroupBase* groupDS = group->GetGroupDS();
1048     if ( !groupDS ) continue;
1049     std::string currentGroupName = (string)group->GetName();
1050     if (groupDS->IsEmpty() && groupsToRemove.find(currentGroupName) != groupsToRemove.end()) {
1051       // Previous group created by enforced elements
1052       MESSAGE("Delete previous group created by removed enforced elements: " << group->GetName())
1053       theMesh->RemoveGroup(groupDS->GetID());
1054     }
1055   }
1056 }
1057
1058 //=======================================================================
1059 //function : removeEmptyGroupsOfDomains
1060 //purpose  : remove empty groups named "Domain_nb" created due to
1061 //           "To make groups of domains" option.
1062 //=======================================================================
1063
1064 static void removeEmptyGroupsOfDomains(SMESH_Mesh* mesh,
1065                                        bool        notEmptyAsWell = false)
1066 {
1067   const char* refName = theDomainGroupNamePrefix;
1068   const size_t refLen = strlen( theDomainGroupNamePrefix );
1069
1070   std::list<int> groupIDs = mesh->GetGroupIds();
1071   std::list<int>::const_iterator id = groupIDs.begin();
1072   for ( ; id != groupIDs.end(); ++id )
1073   {
1074     SMESH_Group* group = mesh->GetGroup( *id );
1075     if ( !group || ( !group->GetGroupDS()->IsEmpty() && !notEmptyAsWell ))
1076       continue;
1077     const char* name = group->GetName();
1078     char* end;
1079     // check the name
1080     if ( strncmp( name, refName, refLen ) == 0 && // starts from refName;
1081          isdigit( *( name + refLen )) &&          // refName is followed by a digit;
1082          strtol( name + refLen, &end, 10) &&      // there are only digits ...
1083          *end == '\0')                            // ... till a string end.
1084     {
1085       mesh->RemoveGroup( *id );
1086     }
1087   }
1088 }
1089
1090 //=======================================================================
1091 //function : readGMFFile
1092 //purpose  : read GMF file w/o geometry associated to mesh
1093 //=======================================================================
1094
1095 static bool readGMFFile(const char*                     theFile,
1096                         GHS3DPlugin_GHS3D*              theAlgo,
1097                         SMESH_MesherHelper*             theHelper,
1098                         TopoDS_Shape                    theSolid,
1099                         vector <const SMDS_MeshNode*> & theNodeByGhs3dId,
1100                         map<const SMDS_MeshNode*,int> & theNodeToGhs3dIdMap,
1101                         std::vector<std::string> &      aNodeGroupByGhs3dId,
1102                         std::vector<std::string> &      anEdgeGroupByGhs3dId,
1103                         std::vector<std::string> &      aFaceGroupByGhs3dId,
1104                         std::set<std::string> &         groupsToRemove,
1105                         bool                            toMakeGroupsOfDomains=false)
1106 {
1107   std::string tmpStr;
1108   SMESHDS_Mesh* theMeshDS = theHelper->GetMeshDS();
1109
1110   int nbInitialNodes = theNodeByGhs3dId.size();
1111   int nbMeshNodes = theMeshDS->NbNodes();
1112   
1113   const bool isQuadMesh = 
1114     theHelper->GetMesh()->NbEdges( ORDER_QUADRATIC ) ||
1115     theHelper->GetMesh()->NbFaces( ORDER_QUADRATIC ) ||
1116     theHelper->GetMesh()->NbVolumes( ORDER_QUADRATIC );
1117     
1118 #ifdef _DEBUG_
1119   std::cout << "theNodeByGhs3dId.size(): " << nbInitialNodes << std::endl;
1120   std::cout << "theHelper->GetMesh()->NbNodes(): " << nbMeshNodes << std::endl;
1121   std::cout << "isQuadMesh: " << isQuadMesh << std::endl;
1122 #endif
1123   
1124   if (theHelper->GetSubShapeID() != 0)
1125     theHelper->IsQuadraticSubMesh( theHelper->GetSubShape() );
1126
1127   // ---------------------------------
1128   // Read generated elements and nodes
1129   // ---------------------------------
1130
1131   int nbElem = 0, nbRef = 0;
1132   int aGMFNodeID = 0;
1133   const SMDS_MeshNode** GMFNode;
1134 #ifdef _DEBUG_
1135   std::map<int, std::set<int> > subdomainId2tetraId;
1136 #endif
1137   std::map <GmfKwdCod,int> tabRef;
1138   const bool force3d = true; // since there is no geometry
1139   const int  noID  = 0;
1140
1141   tabRef[GmfVertices]       = 3; // for new nodes and enforced nodes
1142   tabRef[GmfCorners]        = 1;
1143   tabRef[GmfEdges]          = 2; // for enforced edges
1144   tabRef[GmfRidges]         = 1;
1145   tabRef[GmfTriangles]      = 3; // for enforced faces
1146   tabRef[GmfQuadrilaterals] = 4;
1147   tabRef[GmfTetrahedra]     = 4; // for new tetras
1148   tabRef[GmfHexahedra]      = 8;
1149
1150   int ver, dim;
1151   MESSAGE("Read " << theFile << " file");
1152   int InpMsh = GmfOpenMesh(theFile, GmfRead, &ver, &dim);
1153   if (!InpMsh)
1154     return false;
1155   MESSAGE("Done ");
1156
1157   // Issue 0020682. Avoid creating nodes and tetras at place where
1158   // volumic elements already exist
1159   SMESH_ElementSearcher* elemSearcher = 0;
1160   std::vector< const SMDS_MeshElement* > foundVolumes;
1161   if ( theHelper->GetMesh()->NbVolumes() > 0 )
1162     elemSearcher = SMESH_MeshAlgos::GetElementSearcher( *theHelper->GetMeshDS() );
1163
1164   // IMP 0022172: [CEA 790] create the groups corresponding to domains
1165   std::vector< std::vector< const SMDS_MeshElement* > > elemsOfDomain;
1166
1167   int nbVertices = GmfStatKwd(InpMsh, GmfVertices) - nbInitialNodes;
1168   GMFNode = new const SMDS_MeshNode*[ nbVertices + 1 ];
1169
1170   std::map <GmfKwdCod,int>::const_iterator it = tabRef.begin();
1171   for ( ; it != tabRef.end() ; ++it)
1172   {
1173     if(theAlgo->computeCanceled()) {
1174       GmfCloseMesh(InpMsh);
1175       delete [] GMFNode;
1176       return false;
1177     }
1178     int dummy;
1179     GmfKwdCod token = it->first;
1180     nbRef           = it->second;
1181
1182     nbElem = GmfStatKwd(InpMsh, token);
1183     if (nbElem > 0) {
1184       GmfGotoKwd(InpMsh, token);
1185       std::cout << "Read " << nbElem;
1186     }
1187     else
1188       continue;
1189
1190     std::vector<int> id (nbElem*tabRef[token]); // node ids
1191     std::vector<int> domainID( nbElem ); // domain
1192
1193     if (token == GmfVertices) {
1194       (nbElem <= 1) ? tmpStr = " vertex" : tmpStr = " vertices";
1195 //       std::cout << nbInitialNodes << " from input mesh " << std::endl;
1196
1197       // Remove orphan nodes from previous enforced mesh which was cleared
1198 //       if ( nbElem < nbMeshNodes ) {
1199 //         const SMDS_MeshNode* node;
1200 //         SMDS_NodeIteratorPtr nodeIt = theMeshDS->nodesIterator();
1201 //         while ( nodeIt->more() )
1202 //         {
1203 //           node = nodeIt->next();
1204 //           if (theNodeToGhs3dIdMap.find(node) != theNodeToGhs3dIdMap.end())
1205 //             theMeshDS->RemoveNode(node);
1206 //         }
1207 //       }
1208
1209       
1210       int aGMFID;
1211
1212       float VerTab_f[3];
1213       double x, y, z;
1214       const SMDS_MeshNode * aGMFNode;
1215
1216       for ( int iElem = 0; iElem < nbElem; iElem++ ) {
1217         if(theAlgo->computeCanceled()) {
1218           GmfCloseMesh(InpMsh);
1219           delete [] GMFNode;
1220           return false;
1221         }
1222         if (ver == GmfFloat) {
1223           GmfGetLin(InpMsh, token, &VerTab_f[0], &VerTab_f[1], &VerTab_f[2], &dummy);
1224           x = VerTab_f[0];
1225           y = VerTab_f[1];
1226           z = VerTab_f[2];
1227         }
1228         else {
1229           GmfGetLin(InpMsh, token, &x, &y, &z, &dummy);
1230         }
1231         if (iElem >= nbInitialNodes) {
1232           if ( elemSearcher &&
1233                 elemSearcher->FindElementsByPoint( gp_Pnt(x,y,z), SMDSAbs_Volume, foundVolumes))
1234             aGMFNode = 0;
1235           else
1236             aGMFNode = theHelper->AddNode(x, y, z);
1237           
1238           aGMFID = iElem -nbInitialNodes +1;
1239           GMFNode[ aGMFID ] = aGMFNode;
1240           if (aGMFID-1 < aNodeGroupByGhs3dId.size() && !aNodeGroupByGhs3dId.at(aGMFID-1).empty())
1241             addElemInMeshGroup(theHelper->GetMesh(), aGMFNode, aNodeGroupByGhs3dId.at(aGMFID-1), groupsToRemove);
1242         }
1243       }
1244     }
1245     else if (token == GmfCorners && nbElem > 0) {
1246       (nbElem <= 1) ? tmpStr = " corner" : tmpStr = " corners";
1247       for ( int iElem = 0; iElem < nbElem; iElem++ )
1248         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]]);
1249     }
1250     else if (token == GmfRidges && nbElem > 0) {
1251       (nbElem <= 1) ? tmpStr = " ridge" : tmpStr = " ridges";
1252       for ( int iElem = 0; iElem < nbElem; iElem++ )
1253         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]]);
1254     }
1255     else if (token == GmfEdges && nbElem > 0) {
1256       (nbElem <= 1) ? tmpStr = " edge" : tmpStr = " edges";
1257       for ( int iElem = 0; iElem < nbElem; iElem++ )
1258         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &domainID[iElem]);
1259     }
1260     else if (token == GmfTriangles && nbElem > 0) {
1261       (nbElem <= 1) ? tmpStr = " triangle" : tmpStr = " triangles";
1262       for ( int iElem = 0; iElem < nbElem; iElem++ )
1263         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &domainID[iElem]);
1264     }
1265     else if (token == GmfQuadrilaterals && nbElem > 0) {
1266       (nbElem <= 1) ? tmpStr = " Quadrilateral" : tmpStr = " Quadrilaterals";
1267       for ( int iElem = 0; iElem < nbElem; iElem++ )
1268         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3], &domainID[iElem]);
1269     }
1270     else if (token == GmfTetrahedra && nbElem > 0) {
1271       (nbElem <= 1) ? tmpStr = " Tetrahedron" : tmpStr = " Tetrahedra";
1272       for ( int iElem = 0; iElem < nbElem; iElem++ ) {
1273         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3], &domainID[iElem]);
1274 #ifdef _DEBUG_
1275         subdomainId2tetraId[dummy].insert(iElem+1);
1276 //         MESSAGE("subdomainId2tetraId["<<dummy<<"].insert("<<iElem+1<<")");
1277 #endif
1278       }
1279     }
1280     else if (token == GmfHexahedra && nbElem > 0) {
1281       (nbElem <= 1) ? tmpStr = " Hexahedron" : tmpStr = " Hexahedra";
1282       for ( int iElem = 0; iElem < nbElem; iElem++ )
1283         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3],
1284                   &id[iElem*tabRef[token]+4], &id[iElem*tabRef[token]+5], &id[iElem*tabRef[token]+6], &id[iElem*tabRef[token]+7], &domainID[iElem]);
1285     }
1286     std::cout << tmpStr << std::endl;
1287     std::cout << std::endl;
1288
1289     switch (token) {
1290     case GmfCorners:
1291     case GmfRidges:
1292     case GmfEdges:
1293     case GmfTriangles:
1294     case GmfQuadrilaterals:
1295     case GmfTetrahedra:
1296     case GmfHexahedra:
1297     {
1298       std::vector< const SMDS_MeshNode* > node( nbRef );
1299       std::vector< int >          nodeID( nbRef );
1300       std::vector< SMDS_MeshNode* > enfNode( nbRef );
1301       const SMDS_MeshElement* aCreatedElem;
1302
1303       for ( int iElem = 0; iElem < nbElem; iElem++ )
1304       {
1305         if(theAlgo->computeCanceled()) {
1306           GmfCloseMesh(InpMsh);
1307           delete [] GMFNode;
1308           return false;
1309         }
1310         // Check if elem is already in input mesh. If yes => skip
1311         bool fullyCreatedElement = false; // if at least one of the nodes was created
1312         for ( int iRef = 0; iRef < nbRef; iRef++ )
1313         {
1314           aGMFNodeID = id[iElem*tabRef[token]+iRef]; // read nbRef aGMFNodeID
1315           if (aGMFNodeID <= nbInitialNodes) // input nodes
1316           {
1317             aGMFNodeID--;
1318             node[ iRef ] = theNodeByGhs3dId[aGMFNodeID];
1319           }
1320           else
1321           {
1322             fullyCreatedElement = true;
1323             aGMFNodeID -= nbInitialNodes;
1324             nodeID[ iRef ] = aGMFNodeID ;
1325             node  [ iRef ] = GMFNode[ aGMFNodeID ];
1326           }
1327         }
1328         aCreatedElem = 0;
1329         switch (token)
1330         {
1331         case GmfEdges:
1332           if (fullyCreatedElement) {
1333             aCreatedElem = theHelper->AddEdge( node[0], node[1], noID, force3d );
1334             if (anEdgeGroupByGhs3dId.size() && !anEdgeGroupByGhs3dId[iElem].empty())
1335               addElemInMeshGroup(theHelper->GetMesh(), aCreatedElem, anEdgeGroupByGhs3dId[iElem], groupsToRemove);
1336           }
1337           break;
1338         case GmfTriangles:
1339           if (fullyCreatedElement) {
1340             aCreatedElem = theHelper->AddFace( node[0], node[1], node[2], noID, force3d );
1341             if (aFaceGroupByGhs3dId.size() && !aFaceGroupByGhs3dId[iElem].empty())
1342               addElemInMeshGroup(theHelper->GetMesh(), aCreatedElem, aFaceGroupByGhs3dId[iElem], groupsToRemove);
1343           }
1344           break;
1345         case GmfQuadrilaterals:
1346           if (fullyCreatedElement) {
1347             aCreatedElem = theHelper->AddFace( node[0], node[1], node[2], node[3], noID, force3d );
1348           }
1349           break;
1350         case GmfTetrahedra:
1351           if ( elemSearcher ) {
1352             // Issue 0020682. Avoid creating nodes and tetras at place where
1353             // volumic elements already exist
1354             if ( !node[1] || !node[0] || !node[2] || !node[3] )
1355               continue;
1356             if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
1357                                                     SMESH_TNodeXYZ(node[1]) +
1358                                                     SMESH_TNodeXYZ(node[2]) +
1359                                                     SMESH_TNodeXYZ(node[3]) ) / 4.,
1360                                                     SMDSAbs_Volume, foundVolumes ))
1361             break;
1362           }
1363           aCreatedElem = theHelper->AddVolume( node[1], node[0], node[2], node[3], noID, force3d );
1364           break;
1365         case GmfHexahedra:
1366           if ( elemSearcher ) {
1367             // Issue 0020682. Avoid creating nodes and tetras at place where
1368             // volumic elements already exist
1369             if ( !node[1] || !node[0] || !node[2] || !node[3] || !node[4] || !node[5] || !node[6] || !node[7])
1370               continue;
1371             if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
1372                                                     SMESH_TNodeXYZ(node[1]) +
1373                                                     SMESH_TNodeXYZ(node[2]) +
1374                                                     SMESH_TNodeXYZ(node[3]) +
1375                                                     SMESH_TNodeXYZ(node[4]) +
1376                                                     SMESH_TNodeXYZ(node[5]) +
1377                                                     SMESH_TNodeXYZ(node[6]) +
1378                                                     SMESH_TNodeXYZ(node[7])) / 8.,
1379                                                     SMDSAbs_Volume, foundVolumes ))
1380             break;
1381           }
1382           aCreatedElem = theHelper->AddVolume( node[0], node[3], node[2], node[1],
1383                                                node[4], node[7], node[6], node[5], noID, force3d );
1384           break;
1385         default: continue;
1386         }
1387         if ( aCreatedElem && toMakeGroupsOfDomains )
1388         {
1389           if ( domainID[iElem] >= (int) elemsOfDomain.size() )
1390             elemsOfDomain.resize( domainID[iElem] + 1 );
1391           elemsOfDomain[ domainID[iElem] ].push_back( aCreatedElem );
1392         }
1393       } // loop on elements of one type
1394       break;
1395     } // case ...
1396     } // switch (token)
1397   } // loop on tabRef
1398
1399   GmfCloseMesh(InpMsh);
1400   delete [] GMFNode;
1401
1402   // 0022172: [CEA 790] create the groups corresponding to domains
1403   if ( toMakeGroupsOfDomains )
1404   {
1405     int nbDomains = 0;
1406     for ( size_t i = 0; i < elemsOfDomain.size(); ++i )
1407       nbDomains += ( elemsOfDomain[i].size() > 0 );
1408
1409     if ( nbDomains > 1 )
1410       for ( size_t iDomain = 0; iDomain < elemsOfDomain.size(); ++iDomain )
1411       {
1412         std::vector< const SMDS_MeshElement* > & elems = elemsOfDomain[ iDomain ];
1413         if ( elems.empty() ) continue;
1414
1415         // find existing groups
1416         std::vector< SMESH_Group* > groupOfType( SMDSAbs_NbElementTypes, (SMESH_Group*)NULL );
1417         const std::string domainName = ( SMESH_Comment( theDomainGroupNamePrefix ) << iDomain );
1418         SMESH_Mesh::GroupIteratorPtr groupIt = theHelper->GetMesh()->GetGroups();
1419         while ( groupIt->more() )
1420         {
1421           SMESH_Group* group = groupIt->next();
1422           if ( domainName == group->GetName() &&
1423                dynamic_cast< SMESHDS_Group* >( group->GetGroupDS()) )
1424             groupOfType[ group->GetGroupDS()->GetType() ] = group;
1425         }
1426         // create and fill the groups
1427         size_t iElem = 0;
1428         int groupID;
1429         do
1430         {
1431           SMESH_Group* group = groupOfType[ elems[ iElem ]->GetType() ];
1432           if ( !group )
1433             group = theHelper->GetMesh()->AddGroup( elems[ iElem ]->GetType(),
1434                                                     domainName.c_str(), groupID );
1435           SMDS_MeshGroup& groupDS =
1436             static_cast< SMESHDS_Group* >( group->GetGroupDS() )->SMDSGroup();
1437
1438           while ( iElem < elems.size() && groupDS.Add( elems[iElem] ))
1439             ++iElem;
1440
1441         } while ( iElem < elems.size() );
1442       }
1443   }
1444
1445 #ifdef _DEBUG_
1446   MESSAGE("Nb subdomains " << subdomainId2tetraId.size());
1447   std::map<int, std::set<int> >::const_iterator subdomainIt = subdomainId2tetraId.begin();
1448   TCollection_AsciiString aSubdomainFileName = theFile;
1449   aSubdomainFileName = aSubdomainFileName + ".subdomain";
1450   ofstream aSubdomainFile  ( aSubdomainFileName.ToCString()  , ios::out);
1451
1452   aSubdomainFile << "Nb subdomains " << subdomainId2tetraId.size() << std::endl;
1453   for(;subdomainIt != subdomainId2tetraId.end() ; ++subdomainIt) {
1454     int subdomainId = subdomainIt->first;
1455     std::set<int> tetraIds = subdomainIt->second;
1456     MESSAGE("Subdomain #"<<subdomainId<<": "<<tetraIds.size()<<" tetrahedrons");
1457     std::set<int>::const_iterator tetraIdsIt = tetraIds.begin();
1458     aSubdomainFile << subdomainId << std::endl;
1459     for(;tetraIdsIt != tetraIds.end() ; ++tetraIdsIt) {
1460       aSubdomainFile << (*tetraIdsIt) << " ";
1461     }
1462     aSubdomainFile << std::endl;
1463   }
1464   aSubdomainFile.close();
1465 #endif  
1466   
1467   return true;
1468 }
1469
1470 static bool writeGMFFile(const char*                                     theMeshFileName,
1471                          const char*                                     theRequiredFileName,
1472                          const char*                                     theSolFileName,
1473                          const SMESH_ProxyMesh&                          theProxyMesh,
1474                          SMESH_Mesh *                                    theMesh,
1475                          std::vector <const SMDS_MeshNode*> &            theNodeByGhs3dId,
1476                          std::map<const SMDS_MeshNode*,int> &            aNodeToGhs3dIdMap,
1477                          std::vector<std::string> &                      aNodeGroupByGhs3dId,
1478                          std::vector<std::string> &                      anEdgeGroupByGhs3dId,
1479                          std::vector<std::string> &                      aFaceGroupByGhs3dId,
1480                          GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap & theEnforcedNodes,
1481                          GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedEdges,
1482                          GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedTriangles,
1483                          std::map<std::vector<double>, std::string> &    enfVerticesWithGroup,
1484                          GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues & theEnforcedVertices)
1485 {
1486   MESSAGE("writeGMFFile w/o geometry");
1487   std::string tmpStr;
1488   int idx, idxRequired = 0, idxSol = 0;
1489   const int dummyint = 0;
1490   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues::const_iterator vertexIt;
1491   std::vector<double> enfVertexSizes;
1492   const SMDS_MeshElement* elem;
1493   TIDSortedElemSet anElemSet, theKeptEnforcedEdges, theKeptEnforcedTriangles;
1494   SMDS_ElemIteratorPtr nodeIt;
1495   std::vector <const SMDS_MeshNode*> theEnforcedNodeByGhs3dId;
1496   map<const SMDS_MeshNode*,int> anEnforcedNodeToGhs3dIdMap, anExistingEnforcedNodeToGhs3dIdMap;
1497   std::vector< const SMDS_MeshElement* > foundElems;
1498   map<const SMDS_MeshNode*,TopAbs_State> aNodeToTopAbs_StateMap;
1499   int nbFoundElems;
1500   GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap::iterator elemIt;
1501   TIDSortedElemSet::iterator elemSetIt;
1502   bool isOK;
1503   auto_ptr< SMESH_ElementSearcher > pntCls
1504     ( SMESH_MeshAlgos::GetElementSearcher(*theMesh->GetMeshDS()));
1505   
1506   int nbEnforcedVertices = theEnforcedVertices.size();
1507   
1508   // count faces
1509   int nbFaces = theProxyMesh.NbFaces();
1510   int nbNodes;
1511   
1512   // groups management
1513   int usedEnforcedNodes = 0;
1514   std::string gn = "";
1515
1516   if ( nbFaces == 0 )
1517     return false;
1518   
1519   idx = GmfOpenMesh(theMeshFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1520   if (!idx)
1521     return false;
1522   
1523   /* ========================== FACES ========================== */
1524   /* TRIANGLES ========================== */
1525   SMDS_ElemIteratorPtr eIt = theProxyMesh.GetFaces();
1526   while ( eIt->more() )
1527   {
1528     elem = eIt->next();
1529     anElemSet.insert(elem);
1530     nodeIt = elem->nodesIterator();
1531     nbNodes = elem->NbCornerNodes();
1532     while ( nodeIt->more() && nbNodes--)
1533     {
1534       // find GHS3D ID
1535       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1536       int newId = aNodeToGhs3dIdMap.size() + 1; // ghs3d ids count from 1
1537       aNodeToGhs3dIdMap.insert( make_pair( node, newId ));
1538     }
1539   }
1540   
1541   /* EDGES ========================== */
1542   
1543   // Iterate over the enforced edges
1544   for(elemIt = theEnforcedEdges.begin() ; elemIt != theEnforcedEdges.end() ; ++elemIt) {
1545     elem = elemIt->first;
1546     isOK = true;
1547     nodeIt = elem->nodesIterator();
1548     nbNodes = 2;
1549     while ( nodeIt->more() && nbNodes-- ) {
1550       // find GHS3D ID
1551       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1552       // Test if point is inside shape to mesh
1553       gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1554       TopAbs_State result = pntCls->GetPointState( myPoint );
1555       if ( result == TopAbs_OUT ) {
1556         isOK = false;
1557         break;
1558       }
1559       aNodeToTopAbs_StateMap.insert( make_pair( node, result ));
1560     }
1561     if (isOK) {
1562       nodeIt = elem->nodesIterator();
1563       nbNodes = 2;
1564       int newId = -1;
1565       while ( nodeIt->more() && nbNodes-- ) {
1566         // find GHS3D ID
1567         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1568         gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1569         nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1570 #ifdef _DEBUG_
1571         std::cout << "Node at "<<node->X()<<", "<<node->Y()<<", "<<node->Z()<<std::endl;
1572         std::cout << "Nb nodes found : "<<nbFoundElems<<std::endl;
1573 #endif
1574         if (nbFoundElems ==0) {
1575           if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
1576             newId = aNodeToGhs3dIdMap.size() + anEnforcedNodeToGhs3dIdMap.size() + 1; // ghs3d ids count from 1
1577             anEnforcedNodeToGhs3dIdMap.insert( make_pair( node, newId ));
1578           }
1579         }
1580         else if (nbFoundElems ==1) {
1581           const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1582           newId = (*aNodeToGhs3dIdMap.find(existingNode)).second;
1583           anExistingEnforcedNodeToGhs3dIdMap.insert( make_pair( node, newId ));
1584         }
1585         else
1586           isOK = false;
1587 #ifdef _DEBUG_
1588         std::cout << "GHS3D node ID: "<<newId<<std::endl;
1589 #endif
1590       }
1591       if (isOK)
1592         theKeptEnforcedEdges.insert(elem);
1593     }
1594   }
1595   
1596   /* ENFORCED TRIANGLES ========================== */
1597   
1598   // Iterate over the enforced triangles
1599   for(elemIt = theEnforcedTriangles.begin() ; elemIt != theEnforcedTriangles.end() ; ++elemIt) {
1600     elem = elemIt->first;
1601     isOK = true;
1602     nodeIt = elem->nodesIterator();
1603     nbNodes = 3;
1604     while ( nodeIt->more() && nbNodes--) {
1605       // find GHS3D ID
1606       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1607       // Test if point is inside shape to mesh
1608       gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1609       TopAbs_State result = pntCls->GetPointState( myPoint );
1610       if ( result == TopAbs_OUT ) {
1611         isOK = false;
1612         break;
1613       }
1614       aNodeToTopAbs_StateMap.insert( make_pair( node, result ));
1615     }
1616     if (isOK) {
1617       nodeIt = elem->nodesIterator();
1618       nbNodes = 3;
1619       int newId = -1;
1620       while ( nodeIt->more() && nbNodes--) {
1621         // find GHS3D ID
1622         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1623         gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1624         nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1625 #ifdef _DEBUG_
1626         std::cout << "Nb nodes found : "<<nbFoundElems<<std::endl;
1627 #endif
1628         if (nbFoundElems ==0) {
1629           if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
1630             newId = aNodeToGhs3dIdMap.size() + anEnforcedNodeToGhs3dIdMap.size() + 1; // ghs3d ids count from 1
1631             anEnforcedNodeToGhs3dIdMap.insert( make_pair( node, newId ));
1632           }
1633         }
1634         else if (nbFoundElems ==1) {
1635           const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1636           newId = (*aNodeToGhs3dIdMap.find(existingNode)).second;
1637           anExistingEnforcedNodeToGhs3dIdMap.insert( make_pair( node, newId ));
1638         }
1639         else
1640           isOK = false;
1641 #ifdef _DEBUG_
1642         std::cout << "GHS3D node ID: "<<newId<<std::endl;
1643 #endif
1644       }
1645       if (isOK)
1646         theKeptEnforcedTriangles.insert(elem);
1647     }
1648   }
1649   
1650   // put nodes to theNodeByGhs3dId vector
1651 #ifdef _DEBUG_
1652   std::cout << "aNodeToGhs3dIdMap.size(): "<<aNodeToGhs3dIdMap.size()<<std::endl;
1653 #endif
1654   theNodeByGhs3dId.resize( aNodeToGhs3dIdMap.size() );
1655   map<const SMDS_MeshNode*,int>::const_iterator n2id = aNodeToGhs3dIdMap.begin();
1656   for ( ; n2id != aNodeToGhs3dIdMap.end(); ++ n2id)
1657   {
1658 //     std::cout << "n2id->first: "<<n2id->first<<std::endl;
1659     theNodeByGhs3dId[ n2id->second - 1 ] = n2id->first; // ghs3d ids count from 1
1660   }
1661
1662   // put nodes to anEnforcedNodeToGhs3dIdMap vector
1663 #ifdef _DEBUG_
1664   std::cout << "anEnforcedNodeToGhs3dIdMap.size(): "<<anEnforcedNodeToGhs3dIdMap.size()<<std::endl;
1665 #endif
1666   theEnforcedNodeByGhs3dId.resize( anEnforcedNodeToGhs3dIdMap.size());
1667   n2id = anEnforcedNodeToGhs3dIdMap.begin();
1668   for ( ; n2id != anEnforcedNodeToGhs3dIdMap.end(); ++ n2id)
1669   {
1670     if (n2id->second > aNodeToGhs3dIdMap.size()) {
1671       theEnforcedNodeByGhs3dId[ n2id->second - aNodeToGhs3dIdMap.size() - 1 ] = n2id->first; // ghs3d ids count from 1
1672     }
1673   }
1674   
1675   
1676   /* ========================== NODES ========================== */
1677   vector<const SMDS_MeshNode*> theOrderedNodes, theRequiredNodes;
1678   std::set< std::vector<double> > nodesCoords;
1679   vector<const SMDS_MeshNode*>::const_iterator ghs3dNodeIt = theNodeByGhs3dId.begin();
1680   vector<const SMDS_MeshNode*>::const_iterator after  = theNodeByGhs3dId.end();
1681   
1682   (theNodeByGhs3dId.size() <= 1) ? tmpStr = " node" : " nodes";
1683   std::cout << theNodeByGhs3dId.size() << tmpStr << " from mesh ..." << std::endl;
1684   for ( ; ghs3dNodeIt != after; ++ghs3dNodeIt )
1685   {
1686     const SMDS_MeshNode* node = *ghs3dNodeIt;
1687     std::vector<double> coords;
1688     coords.push_back(node->X());
1689     coords.push_back(node->Y());
1690     coords.push_back(node->Z());
1691     nodesCoords.insert(coords);
1692     theOrderedNodes.push_back(node);
1693   }
1694   
1695   // Iterate over the enforced nodes given by enforced elements
1696   ghs3dNodeIt = theEnforcedNodeByGhs3dId.begin();
1697   after  = theEnforcedNodeByGhs3dId.end();
1698   (theEnforcedNodeByGhs3dId.size() <= 1) ? tmpStr = " node" : " nodes";
1699   std::cout << theEnforcedNodeByGhs3dId.size() << tmpStr << " from enforced elements ..." << std::endl;
1700   for ( ; ghs3dNodeIt != after; ++ghs3dNodeIt )
1701   {
1702     const SMDS_MeshNode* node = *ghs3dNodeIt;
1703     std::vector<double> coords;
1704     coords.push_back(node->X());
1705     coords.push_back(node->Y());
1706     coords.push_back(node->Z());
1707 #ifdef _DEBUG_
1708     std::cout << "Node at " << node->X()<<", " <<node->Y()<<", " <<node->Z();
1709 #endif
1710     
1711     if (nodesCoords.find(coords) != nodesCoords.end()) {
1712       // node already exists in original mesh
1713 #ifdef _DEBUG_
1714       std::cout << " found" << std::endl;
1715 #endif
1716       continue;
1717     }
1718     
1719     if (theEnforcedVertices.find(coords) != theEnforcedVertices.end()) {
1720       // node already exists in enforced vertices
1721 #ifdef _DEBUG_
1722       std::cout << " found" << std::endl;
1723 #endif
1724       continue;
1725     }
1726     
1727 //     gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1728 //     nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1729 //     if (nbFoundElems ==0) {
1730 //       std::cout << " not found" << std::endl;
1731 //       if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
1732 //         nodesCoords.insert(coords);
1733 //         theOrderedNodes.push_back(node);
1734 //       }
1735 //     }
1736 //     else {
1737 //       std::cout << " found in initial mesh" << std::endl;
1738 //       const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1739 //       nodesCoords.insert(coords);
1740 //       theOrderedNodes.push_back(existingNode);
1741 //     }
1742     
1743 #ifdef _DEBUG_
1744     std::cout << " not found" << std::endl;
1745 #endif
1746     
1747     nodesCoords.insert(coords);
1748     theOrderedNodes.push_back(node);
1749 //     theRequiredNodes.push_back(node);
1750   }
1751   
1752   
1753   // Iterate over the enforced nodes
1754   GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap::const_iterator enfNodeIt;
1755   (theEnforcedNodes.size() <= 1) ? tmpStr = " node" : " nodes";
1756   std::cout << theEnforcedNodes.size() << tmpStr << " from enforced nodes ..." << std::endl;
1757   for(enfNodeIt = theEnforcedNodes.begin() ; enfNodeIt != theEnforcedNodes.end() ; ++enfNodeIt)
1758   {
1759     const SMDS_MeshNode* node = enfNodeIt->first;
1760     std::vector<double> coords;
1761     coords.push_back(node->X());
1762     coords.push_back(node->Y());
1763     coords.push_back(node->Z());
1764 #ifdef _DEBUG_
1765     std::cout << "Node at " << node->X()<<", " <<node->Y()<<", " <<node->Z();
1766 #endif
1767     
1768     // Test if point is inside shape to mesh
1769     gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1770     TopAbs_State result = pntCls->GetPointState( myPoint );
1771     if ( result == TopAbs_OUT ) {
1772 #ifdef _DEBUG_
1773       std::cout << " out of volume" << std::endl;
1774 #endif
1775       continue;
1776     }
1777     
1778     if (nodesCoords.find(coords) != nodesCoords.end()) {
1779 #ifdef _DEBUG_
1780       std::cout << " found in nodesCoords" << std::endl;
1781 #endif
1782 //       theRequiredNodes.push_back(node);
1783       continue;
1784     }
1785
1786     if (theEnforcedVertices.find(coords) != theEnforcedVertices.end()) {
1787 #ifdef _DEBUG_
1788       std::cout << " found in theEnforcedVertices" << std::endl;
1789 #endif
1790       continue;
1791     }
1792     
1793 //     nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1794 //     if (nbFoundElems ==0) {
1795 //       std::cout << " not found" << std::endl;
1796 //       if (result == TopAbs_IN) {
1797 //         nodesCoords.insert(coords);
1798 //         theRequiredNodes.push_back(node);
1799 //       }
1800 //     }
1801 //     else {
1802 //       std::cout << " found in initial mesh" << std::endl;
1803 //       const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1804 // //       nodesCoords.insert(coords);
1805 //       theRequiredNodes.push_back(existingNode);
1806 //     }
1807 //     
1808 //     
1809 //     
1810 //     if (pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems) == 0)
1811 //       continue;
1812
1813 //     if ( result != TopAbs_IN )
1814 //       continue;
1815     
1816 #ifdef _DEBUG_
1817     std::cout << " not found" << std::endl;
1818 #endif
1819     nodesCoords.insert(coords);
1820 //     theOrderedNodes.push_back(node);
1821     theRequiredNodes.push_back(node);
1822   }
1823   int requiredNodes = theRequiredNodes.size();
1824   
1825   int solSize = 0;
1826   std::vector<std::vector<double> > ReqVerTab;
1827   if (nbEnforcedVertices) {
1828 //    ReqVerTab.clear();
1829     (nbEnforcedVertices <= 1) ? tmpStr = " node" : " nodes";
1830     std::cout << nbEnforcedVertices << tmpStr << " from enforced vertices ..." << std::endl;
1831     // Iterate over the enforced vertices
1832     for(vertexIt = theEnforcedVertices.begin() ; vertexIt != theEnforcedVertices.end() ; ++vertexIt) {
1833       double x = vertexIt->first[0];
1834       double y = vertexIt->first[1];
1835       double z = vertexIt->first[2];
1836       // Test if point is inside shape to mesh
1837       gp_Pnt myPoint(x,y,z);
1838       TopAbs_State result = pntCls->GetPointState( myPoint );
1839       if ( result == TopAbs_OUT )
1840         continue;
1841       //if (pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems) == 0)
1842       //continue;
1843
1844 //       if ( result != TopAbs_IN )
1845 //         continue;
1846       std::vector<double> coords;
1847       coords.push_back(x);
1848       coords.push_back(y);
1849       coords.push_back(z);
1850       ReqVerTab.push_back(coords);
1851       enfVertexSizes.push_back(vertexIt->second);
1852       solSize++;
1853     }
1854   }
1855   
1856   
1857   // GmfVertices
1858   std::cout << "Begin writting required nodes in GmfVertices" << std::endl;
1859   std::cout << "Nb vertices: " << theOrderedNodes.size() << std::endl;
1860   GmfSetKwd(idx, GmfVertices, theOrderedNodes.size()/*+solSize*/);
1861   for (ghs3dNodeIt = theOrderedNodes.begin();ghs3dNodeIt != theOrderedNodes.end();++ghs3dNodeIt) {
1862     GmfSetLin(idx, GmfVertices, (*ghs3dNodeIt)->X(), (*ghs3dNodeIt)->Y(), (*ghs3dNodeIt)->Z(), dummyint);
1863   }
1864
1865   std::cout << "End writting required nodes in GmfVertices" << std::endl;
1866
1867   if (requiredNodes + solSize) {
1868     std::cout << "Begin writting in req and sol file" << std::endl;
1869     aNodeGroupByGhs3dId.resize( requiredNodes + solSize );
1870     idxRequired = GmfOpenMesh(theRequiredFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1871     if (!idxRequired) {
1872       GmfCloseMesh(idx);
1873       return false;
1874     }
1875     idxSol = GmfOpenMesh(theSolFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1876     if (!idxSol) {
1877       GmfCloseMesh(idx);
1878       if (idxRequired)
1879         GmfCloseMesh(idxRequired);
1880       return false;
1881     }
1882     int TypTab[] = {GmfSca};
1883     double ValTab[] = {0.0};
1884     GmfSetKwd(idxRequired, GmfVertices, requiredNodes + solSize);
1885     GmfSetKwd(idxSol, GmfSolAtVertices, requiredNodes + solSize, 1, TypTab);
1886 //     int usedEnforcedNodes = 0;
1887 //     std::string gn = "";
1888     for (ghs3dNodeIt = theRequiredNodes.begin();ghs3dNodeIt != theRequiredNodes.end();++ghs3dNodeIt) {
1889       GmfSetLin(idxRequired, GmfVertices, (*ghs3dNodeIt)->X(), (*ghs3dNodeIt)->Y(), (*ghs3dNodeIt)->Z(), dummyint);
1890       GmfSetLin(idxSol, GmfSolAtVertices, ValTab);
1891       if (theEnforcedNodes.find((*ghs3dNodeIt)) != theEnforcedNodes.end())
1892         gn = theEnforcedNodes.find((*ghs3dNodeIt))->second;
1893       aNodeGroupByGhs3dId[usedEnforcedNodes] = gn;
1894       usedEnforcedNodes++;
1895     }
1896
1897     for (int i=0;i<solSize;i++) {
1898       std::cout << ReqVerTab[i][0] <<" "<< ReqVerTab[i][1] << " "<< ReqVerTab[i][2] << std::endl;
1899 #ifdef _DEBUG_
1900       std::cout << "enfVertexSizes.at("<<i<<"): " << enfVertexSizes.at(i) << std::endl;
1901 #endif
1902       double solTab[] = {enfVertexSizes.at(i)};
1903       GmfSetLin(idxRequired, GmfVertices, ReqVerTab[i][0], ReqVerTab[i][1], ReqVerTab[i][2], dummyint);
1904       GmfSetLin(idxSol, GmfSolAtVertices, solTab);
1905       aNodeGroupByGhs3dId[usedEnforcedNodes] = enfVerticesWithGroup.find(ReqVerTab[i])->second;
1906 #ifdef _DEBUG_
1907       std::cout << "aNodeGroupByGhs3dId["<<usedEnforcedNodes<<"] = \""<<aNodeGroupByGhs3dId[usedEnforcedNodes]<<"\""<<std::endl;
1908 #endif
1909       usedEnforcedNodes++;
1910     }
1911     std::cout << "End writting in req and sol file" << std::endl;
1912   }
1913
1914   int nedge[2], ntri[3];
1915     
1916   // GmfEdges
1917   int usedEnforcedEdges = 0;
1918   if (theKeptEnforcedEdges.size()) {
1919     anEdgeGroupByGhs3dId.resize( theKeptEnforcedEdges.size() );
1920 //    idxRequired = GmfOpenMesh(theRequiredFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1921 //    if (!idxRequired)
1922 //      return false;
1923     GmfSetKwd(idx, GmfEdges, theKeptEnforcedEdges.size());
1924 //    GmfSetKwd(idxRequired, GmfEdges, theKeptEnforcedEdges.size());
1925     for(elemSetIt = theKeptEnforcedEdges.begin() ; elemSetIt != theKeptEnforcedEdges.end() ; ++elemSetIt) {
1926       elem = (*elemSetIt);
1927       nodeIt = elem->nodesIterator();
1928       int index=0;
1929       while ( nodeIt->more() ) {
1930         // find GHS3D ID
1931         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1932         map< const SMDS_MeshNode*,int >::iterator it = anEnforcedNodeToGhs3dIdMap.find(node);
1933         if (it == anEnforcedNodeToGhs3dIdMap.end()) {
1934           it = anExistingEnforcedNodeToGhs3dIdMap.find(node);
1935           if (it == anEnforcedNodeToGhs3dIdMap.end())
1936             throw "Node not found";
1937         }
1938         nedge[index] = it->second;
1939         index++;
1940       }
1941       GmfSetLin(idx, GmfEdges, nedge[0], nedge[1], dummyint);
1942       anEdgeGroupByGhs3dId[usedEnforcedEdges] = theEnforcedEdges.find(elem)->second;
1943 //      GmfSetLin(idxRequired, GmfEdges, nedge[0], nedge[1], dummyint);
1944       usedEnforcedEdges++;
1945     }
1946 //    GmfCloseMesh(idxRequired);
1947   }
1948
1949
1950   if (usedEnforcedEdges) {
1951     GmfSetKwd(idx, GmfRequiredEdges, usedEnforcedEdges);
1952     for (int enfID=1;enfID<=usedEnforcedEdges;enfID++) {
1953       GmfSetLin(idx, GmfRequiredEdges, enfID);
1954     }
1955   }
1956
1957   // GmfTriangles
1958   int usedEnforcedTriangles = 0;
1959   if (anElemSet.size()+theKeptEnforcedTriangles.size()) {
1960     aFaceGroupByGhs3dId.resize( anElemSet.size()+theKeptEnforcedTriangles.size() );
1961     GmfSetKwd(idx, GmfTriangles, anElemSet.size()+theKeptEnforcedTriangles.size());
1962     int k=0;
1963     for(elemSetIt = anElemSet.begin() ; elemSetIt != anElemSet.end() ; ++elemSetIt,++k) {
1964       elem = (*elemSetIt);
1965       nodeIt = elem->nodesIterator();
1966       int index=0;
1967       for ( int j = 0; j < 3; ++j ) {
1968         // find GHS3D ID
1969         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1970         map< const SMDS_MeshNode*,int >::iterator it = aNodeToGhs3dIdMap.find(node);
1971         if (it == aNodeToGhs3dIdMap.end())
1972           throw "Node not found";
1973         ntri[index] = it->second;
1974         index++;
1975       }
1976       GmfSetLin(idx, GmfTriangles, ntri[0], ntri[1], ntri[2], dummyint);
1977       aFaceGroupByGhs3dId[k] = "";
1978     }
1979     if (theKeptEnforcedTriangles.size()) {
1980       for(elemSetIt = theKeptEnforcedTriangles.begin() ; elemSetIt != theKeptEnforcedTriangles.end() ; ++elemSetIt,++k) {
1981         elem = (*elemSetIt);
1982         nodeIt = elem->nodesIterator();
1983         int index=0;
1984         for ( int j = 0; j < 3; ++j ) {
1985           // find GHS3D ID
1986           const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1987           map< const SMDS_MeshNode*,int >::iterator it = anEnforcedNodeToGhs3dIdMap.find(node);
1988           if (it == anEnforcedNodeToGhs3dIdMap.end()) {
1989             it = anExistingEnforcedNodeToGhs3dIdMap.find(node);
1990             if (it == anEnforcedNodeToGhs3dIdMap.end())
1991               throw "Node not found";
1992           }
1993           ntri[index] = it->second;
1994           index++;
1995         }
1996         GmfSetLin(idx, GmfTriangles, ntri[0], ntri[1], ntri[2], dummyint);
1997         aFaceGroupByGhs3dId[k] = theEnforcedTriangles.find(elem)->second;
1998         usedEnforcedTriangles++;
1999       }
2000     }
2001   }
2002
2003   
2004   if (usedEnforcedTriangles) {
2005     GmfSetKwd(idx, GmfRequiredTriangles, usedEnforcedTriangles);
2006     for (int enfID=1;enfID<=usedEnforcedTriangles;enfID++)
2007       GmfSetLin(idx, GmfRequiredTriangles, anElemSet.size()+enfID);
2008   }
2009
2010   GmfCloseMesh(idx);
2011   if (idxRequired)
2012     GmfCloseMesh(idxRequired);
2013   if (idxSol)
2014     GmfCloseMesh(idxSol);
2015   
2016   return true;
2017   
2018 }
2019
2020 // static bool writeGMFFile(const char*                                    theMeshFileName,
2021 //                         const char*                                     theRequiredFileName,
2022 //                         const char*                                     theSolFileName,
2023 //                         SMESH_MesherHelper&                             theHelper,
2024 //                         const SMESH_ProxyMesh&                          theProxyMesh,
2025 //                         std::map <int,int> &                            theNodeId2NodeIndexMap,
2026 //                         std::map <int,int> &                            theSmdsToGhs3dIdMap,
2027 //                         std::map <int,const SMDS_MeshNode*> &           theGhs3dIdToNodeMap,
2028 //                         TIDSortedNodeSet &                              theEnforcedNodes,
2029 //                         TIDSortedElemSet &                              theEnforcedEdges,
2030 //                         TIDSortedElemSet &                              theEnforcedTriangles,
2031 // //                         TIDSortedElemSet &                              theEnforcedQuadrangles,
2032 //                         GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues & theEnforcedVertices)
2033 // {
2034 //   MESSAGE("writeGMFFile with geometry");
2035 //   int idx, idxRequired, idxSol;
2036 //   int nbv, nbev, nben, aGhs3dID = 0;
2037 //   const int dummyint = 0;
2038 //   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues::const_iterator vertexIt;
2039 //   std::vector<double> enfVertexSizes;
2040 //   TIDSortedNodeSet::const_iterator enfNodeIt;
2041 //   const SMDS_MeshNode* node;
2042 //   SMDS_NodeIteratorPtr nodeIt;
2043 // 
2044 //   idx = GmfOpenMesh(theMeshFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
2045 //   if (!idx)
2046 //     return false;
2047 //   
2048 //   SMESHDS_Mesh * theMeshDS = theHelper.GetMeshDS();
2049 //   
2050 //   /* ========================== NODES ========================== */
2051 //   // NB_NODES
2052 //   nbv = theMeshDS->NbNodes();
2053 //   if ( nbv == 0 )
2054 //     return false;
2055 //   nbev = theEnforcedVertices.size();
2056 //   nben = theEnforcedNodes.size();
2057 //   
2058 //   // Issue 020674: EDF 870 SMESH: Mesh generated by Netgen not usable by GHS3D
2059 //   // The problem is in nodes on degenerated edges, we need to skip nodes which are free
2060 //   // and replace not-free nodes on edges by the node on vertex
2061 //   TNodeNodeMap n2nDegen; // map a node on degenerated edge to a node on vertex
2062 //   TNodeNodeMap::iterator n2nDegenIt;
2063 //   if ( theHelper.HasDegeneratedEdges() )
2064 //   {
2065 //     set<int> checkedSM;
2066 //     for (TopExp_Explorer e(theMeshDS->ShapeToMesh(), TopAbs_EDGE ); e.More(); e.Next())
2067 //     {
2068 //       SMESH_subMesh* sm = theHelper.GetMesh()->GetSubMesh( e.Current() );
2069 //       if ( checkedSM.insert( sm->GetId() ).second && theHelper.IsDegenShape(sm->GetId() ))
2070 //       {
2071 //         if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() )
2072 //         {
2073 //           TopoDS_Shape vertex = TopoDS_Iterator( e.Current() ).Value();
2074 //           const SMDS_MeshNode* vNode = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), theMeshDS);
2075 //           {
2076 //             SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2077 //             while ( nIt->more() )
2078 //               n2nDegen.insert( make_pair( nIt->next(), vNode ));
2079 //           }
2080 //         }
2081 //       }
2082 //     }
2083 //   }
2084 //   
2085 //   const bool isQuadMesh = 
2086 //     theHelper.GetMesh()->NbEdges( ORDER_QUADRATIC ) ||
2087 //     theHelper.GetMesh()->NbFaces( ORDER_QUADRATIC ) ||
2088 //     theHelper.GetMesh()->NbVolumes( ORDER_QUADRATIC );
2089 // 
2090 //   std::vector<std::vector<double> > VerTab;
2091 //   std::set<std::vector<double> > VerMap;
2092 //   VerTab.clear();
2093 //   std::vector<double> aVerTab;
2094 //   // Loop from 1 to NB_NODES
2095 // 
2096 //   nodeIt = theMeshDS->nodesIterator();
2097 //   
2098 //   while ( nodeIt->more() )
2099 //   {
2100 //     node = nodeIt->next();
2101 //     if ( isQuadMesh && theHelper.IsMedium( node )) // Issue 0021238
2102 //       continue;
2103 //     if ( n2nDegen.count( node ) ) // Issue 0020674
2104 //       continue;
2105 // 
2106 //     std::vector<double> coords;
2107 //     coords.push_back(node->X());
2108 //     coords.push_back(node->Y());
2109 //     coords.push_back(node->Z());
2110 //     if (VerMap.find(coords) != VerMap.end()) {
2111 //       aGhs3dID = theSmdsToGhs3dIdMap[node->GetID()];
2112 //       theGhs3dIdToNodeMap[theSmdsToGhs3dIdMap[node->GetID()]] = node;
2113 //       continue;
2114 //     }
2115 //     VerTab.push_back(coords);
2116 //     VerMap.insert(coords);
2117 //     aGhs3dID++;
2118 //     theSmdsToGhs3dIdMap.insert( make_pair( node->GetID(), aGhs3dID ));
2119 //     theGhs3dIdToNodeMap.insert( make_pair( aGhs3dID, node ));
2120 //   }
2121 //   
2122 //   
2123 //   /* ENFORCED NODES ========================== */
2124 //   if (nben) {
2125 //     std::cout << "Add " << nben << " enforced nodes to input .mesh file" << std::endl;
2126 //     for(enfNodeIt = theEnforcedNodes.begin() ; enfNodeIt != theEnforcedNodes.end() ; ++enfNodeIt) {
2127 //       double x = (*enfNodeIt)->X();
2128 //       double y = (*enfNodeIt)->Y();
2129 //       double z = (*enfNodeIt)->Z();
2130 //       // Test if point is inside shape to mesh
2131 //       gp_Pnt myPoint(x,y,z);
2132 //       BRepClass3d_SolidClassifier scl(theMeshDS->ShapeToMesh());
2133 //       scl.Perform(myPoint, 1e-7);
2134 //       TopAbs_State result = scl.State();
2135 //       if ( result != TopAbs_IN )
2136 //         continue;
2137 //       std::vector<double> coords;
2138 //       coords.push_back(x);
2139 //       coords.push_back(y);
2140 //       coords.push_back(z);
2141 //       if (theEnforcedVertices.find(coords) != theEnforcedVertices.end())
2142 //         continue;
2143 //       if (VerMap.find(coords) != VerMap.end())
2144 //         continue;
2145 //       VerTab.push_back(coords);
2146 //       VerMap.insert(coords);
2147 //       aGhs3dID++;
2148 //       theNodeId2NodeIndexMap.insert( make_pair( (*enfNodeIt)->GetID(), aGhs3dID ));
2149 //     }
2150 //   }
2151 //     
2152 //   
2153 //   /* ENFORCED VERTICES ========================== */
2154 //   int solSize = 0;
2155 //   std::vector<std::vector<double> > ReqVerTab;
2156 //   ReqVerTab.clear();
2157 //   if (nbev) {
2158 //     std::cout << "Add " << nbev << " enforced vertices to input .mesh file" << std::endl;
2159 //     for(vertexIt = theEnforcedVertices.begin() ; vertexIt != theEnforcedVertices.end() ; ++vertexIt) {
2160 //       double x = vertexIt->first[0];
2161 //       double y = vertexIt->first[1];
2162 //       double z = vertexIt->first[2];
2163 //       // Test if point is inside shape to mesh
2164 //       gp_Pnt myPoint(x,y,z);
2165 //       BRepClass3d_SolidClassifier scl(theMeshDS->ShapeToMesh());
2166 //       scl.Perform(myPoint, 1e-7);
2167 //       TopAbs_State result = scl.State();
2168 //       if ( result != TopAbs_IN )
2169 //         continue;
2170 //       enfVertexSizes.push_back(vertexIt->second);
2171 //       std::vector<double> coords;
2172 //       coords.push_back(x);
2173 //       coords.push_back(y);
2174 //       coords.push_back(z);
2175 //       if (VerMap.find(coords) != VerMap.end())
2176 //         continue;
2177 //       ReqVerTab.push_back(coords);
2178 //       VerMap.insert(coords);
2179 //       solSize++;
2180 //     }
2181 //   }
2182 // 
2183 //   
2184 //   /* ========================== FACES ========================== */
2185 //   
2186 //   int nbTriangles = 0/*, nbQuadrangles = 0*/, aSmdsID;
2187 //   TopTools_IndexedMapOfShape facesMap, trianglesMap/*, quadranglesMap*/;
2188 //   TIDSortedElemSet::const_iterator elemIt;
2189 //   const SMESHDS_SubMesh* theSubMesh;
2190 //   TopoDS_Shape aShape;
2191 //   SMDS_ElemIteratorPtr itOnSubMesh, itOnSubFace;
2192 //   const SMDS_MeshElement* aFace;
2193 //   map<int,int>::const_iterator itOnMap;
2194 //   std::vector<std::vector<int> > tt, qt,et;
2195 //   tt.clear();
2196 //   qt.clear();
2197 //   et.clear();
2198 //   std::vector<int> att, aqt, aet;
2199 //   
2200 //   TopExp::MapShapes( theMeshDS->ShapeToMesh(), TopAbs_FACE, facesMap );
2201 // 
2202 //   for ( int i = 1; i <= facesMap.Extent(); ++i )
2203 //     if (( theSubMesh  = theProxyMesh.GetSubMesh( facesMap(i))))
2204 //     {
2205 //       SMDS_ElemIteratorPtr it = theSubMesh->GetElements();
2206 //       while (it->more())
2207 //       {
2208 //         const SMDS_MeshElement *elem = it->next();
2209 //         int nbCornerNodes = elem->NbCornerNodes();
2210 //         if (nbCornerNodes == 3)
2211 //         {
2212 //           trianglesMap.Add(facesMap(i));
2213 //           nbTriangles ++;
2214 //         }
2215 // //         else if (nbCornerNodes == 4)
2216 // //         {
2217 // //           quadranglesMap.Add(facesMap(i));
2218 // //           nbQuadrangles ++;
2219 // //         }
2220 //       }
2221 //     }
2222 //     
2223 //   /* TRIANGLES ========================== */
2224 //   if (nbTriangles) {
2225 //     for ( int i = 1; i <= trianglesMap.Extent(); i++ )
2226 //     {
2227 //       aShape = trianglesMap(i);
2228 //       theSubMesh = theProxyMesh.GetSubMesh(aShape);
2229 //       if ( !theSubMesh ) continue;
2230 //       itOnSubMesh = theSubMesh->GetElements();
2231 //       while ( itOnSubMesh->more() )
2232 //       {
2233 //         aFace = itOnSubMesh->next();
2234 //         itOnSubFace = aFace->nodesIterator();
2235 //         att.clear();
2236 //         for ( int j = 0; j < 3; ++j ) {
2237 //           // find GHS3D ID
2238 //           node = castToNode( itOnSubFace->next() );
2239 //           if (( n2nDegenIt = n2nDegen.find( node )) != n2nDegen.end() )
2240 //             node = n2nDegenIt->second;
2241 //           aSmdsID = node->GetID();
2242 //           itOnMap = theSmdsToGhs3dIdMap.find( aSmdsID );
2243 //           ASSERT( itOnMap != theSmdsToGhs3dIdMap.end() );
2244 //           att.push_back((*itOnMap).second);
2245 //         }
2246 //         tt.push_back(att);
2247 //       }
2248 //     }
2249 //   }
2250 // 
2251 //   if (theEnforcedTriangles.size()) {
2252 //     std::cout << "Add " << theEnforcedTriangles.size() << " enforced triangles to input .mesh file" << std::endl;
2253 //     // Iterate over the enforced triangles
2254 //     for(elemIt = theEnforcedTriangles.begin() ; elemIt != theEnforcedTriangles.end() ; ++elemIt) {
2255 //       aFace = (*elemIt);
2256 //       itOnSubFace = aFace->nodesIterator();
2257 //       bool isOK = true;
2258 //       att.clear();
2259 //       
2260 //       for ( int j = 0; j < 3; ++j ) {
2261 //         node = castToNode( itOnSubFace->next() );
2262 //         if (( n2nDegenIt = n2nDegen.find( node )) != n2nDegen.end() )
2263 //           node = n2nDegenIt->second;
2264 // //         std::cout << node;
2265 //         double x = node->X();
2266 //         double y = node->Y();
2267 //         double z = node->Z();
2268 //         // Test if point is inside shape to mesh
2269 //         gp_Pnt myPoint(x,y,z);
2270 //         BRepClass3d_SolidClassifier scl(theMeshDS->ShapeToMesh());
2271 //         scl.Perform(myPoint, 1e-7);
2272 //         TopAbs_State result = scl.State();
2273 //         if ( result != TopAbs_IN ) {
2274 //           isOK = false;
2275 //           theEnforcedTriangles.erase(elemIt);
2276 //           continue;
2277 //         }
2278 //         std::vector<double> coords;
2279 //         coords.push_back(x);
2280 //         coords.push_back(y);
2281 //         coords.push_back(z);
2282 //         if (VerMap.find(coords) != VerMap.end()) {
2283 //           att.push_back(theNodeId2NodeIndexMap[node->GetID()]);
2284 //           continue;
2285 //         }
2286 //         VerTab.push_back(coords);
2287 //         VerMap.insert(coords);
2288 //         aGhs3dID++;
2289 //         theNodeId2NodeIndexMap.insert( make_pair( node->GetID(), aGhs3dID ));
2290 //         att.push_back(aGhs3dID);
2291 //       }
2292 //       if (isOK)
2293 //         tt.push_back(att);
2294 //     }
2295 //   }
2296 // 
2297 // 
2298 //   /* ========================== EDGES ========================== */
2299 // 
2300 //   if (theEnforcedEdges.size()) {
2301 //     // Iterate over the enforced edges
2302 //     std::cout << "Add " << theEnforcedEdges.size() << " enforced edges to input .mesh file" << std::endl;
2303 //     for(elemIt = theEnforcedEdges.begin() ; elemIt != theEnforcedEdges.end() ; ++elemIt) {
2304 //       aFace = (*elemIt);
2305 //       bool isOK = true;
2306 //       itOnSubFace = aFace->nodesIterator();
2307 //       aet.clear();
2308 //       for ( int j = 0; j < 2; ++j ) {
2309 //         node = castToNode( itOnSubFace->next() );
2310 //         if (( n2nDegenIt = n2nDegen.find( node )) != n2nDegen.end() )
2311 //           node = n2nDegenIt->second;
2312 //         double x = node->X();
2313 //         double y = node->Y();
2314 //         double z = node->Z();
2315 //         // Test if point is inside shape to mesh
2316 //         gp_Pnt myPoint(x,y,z);
2317 //         BRepClass3d_SolidClassifier scl(theMeshDS->ShapeToMesh());
2318 //         scl.Perform(myPoint, 1e-7);
2319 //         TopAbs_State result = scl.State();
2320 //         if ( result != TopAbs_IN ) {
2321 //           isOK = false;
2322 //           theEnforcedEdges.erase(elemIt);
2323 //           continue;
2324 //         }
2325 //         std::vector<double> coords;
2326 //         coords.push_back(x);
2327 //         coords.push_back(y);
2328 //         coords.push_back(z);
2329 //         if (VerMap.find(coords) != VerMap.end()) {
2330 //           aet.push_back(theNodeId2NodeIndexMap[node->GetID()]);
2331 //           continue;
2332 //         }
2333 //         VerTab.push_back(coords);
2334 //         VerMap.insert(coords);
2335 //         
2336 //         aGhs3dID++;
2337 //         theNodeId2NodeIndexMap.insert( make_pair( node->GetID(), aGhs3dID ));
2338 //         aet.push_back(aGhs3dID);
2339 //       }
2340 //       if (isOK)
2341 //         et.push_back(aet);
2342 //     }
2343 //   }
2344 // 
2345 // 
2346 //   /* Write vertices number */
2347 //   MESSAGE("Number of vertices: "<<aGhs3dID);
2348 //   MESSAGE("Size of vector: "<<VerTab.size());
2349 //   GmfSetKwd(idx, GmfVertices, aGhs3dID/*+solSize*/);
2350 //   for (int i=0;i<aGhs3dID;i++)
2351 //     GmfSetLin(idx, GmfVertices, VerTab[i][0], VerTab[i][1], VerTab[i][2], dummyint);
2352 // //   for (int i=0;i<solSize;i++) {
2353 // //     std::cout << ReqVerTab[i][0] <<" "<< ReqVerTab[i][1] << " "<< ReqVerTab[i][2] << std::endl;
2354 // //     GmfSetLin(idx, GmfVertices, ReqVerTab[i][0], ReqVerTab[i][1], ReqVerTab[i][2], dummyint);
2355 // //   }
2356 // 
2357 //   if (solSize) {
2358 //     idxRequired = GmfOpenMesh(theRequiredFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
2359 //     if (!idxRequired) {
2360 //       GmfCloseMesh(idx);
2361 //       return false;
2362 //     }
2363 //     idxSol = GmfOpenMesh(theSolFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
2364 //     if (!idxSol){
2365 //       GmfCloseMesh(idx);
2366 //       if (idxRequired)
2367 //         GmfCloseMesh(idxRequired);
2368 //       return false;
2369 //     }
2370 //     
2371 //     int TypTab[] = {GmfSca};
2372 //     GmfSetKwd(idxRequired, GmfVertices, solSize);
2373 //     GmfSetKwd(idxSol, GmfSolAtVertices, solSize, 1, TypTab);
2374 //     
2375 //     for (int i=0;i<solSize;i++) {
2376 //       double solTab[] = {enfVertexSizes.at(i)};
2377 //       GmfSetLin(idxRequired, GmfVertices, ReqVerTab[i][0], ReqVerTab[i][1], ReqVerTab[i][2], dummyint);
2378 //       GmfSetLin(idxSol, GmfSolAtVertices, solTab);
2379 //     }
2380 //     GmfCloseMesh(idxRequired);
2381 //     GmfCloseMesh(idxSol);
2382 //   }
2383 //   
2384 //   /* Write triangles number */
2385 //   if (tt.size()) {
2386 //     GmfSetKwd(idx, GmfTriangles, tt.size());
2387 //     for (int i=0;i<tt.size();i++)
2388 //       GmfSetLin(idx, GmfTriangles, tt[i][0], tt[i][1], tt[i][2], dummyint);
2389 //   }  
2390 //   
2391 //   /* Write edges number */
2392 //   if (et.size()) {
2393 //     GmfSetKwd(idx, GmfEdges, et.size());
2394 //     for (int i=0;i<et.size();i++)
2395 //       GmfSetLin(idx, GmfEdges, et[i][0], et[i][1], dummyint);
2396 //   }
2397 // 
2398 //   /* QUADRANGLES ========================== */
2399 //   // TODO: add pyramids ?
2400 // //   if (nbQuadrangles) {
2401 // //     for ( int i = 1; i <= quadranglesMap.Extent(); i++ )
2402 // //     {
2403 // //       aShape = quadranglesMap(i);
2404 // //       theSubMesh = theProxyMesh.GetSubMesh(aShape);
2405 // //       if ( !theSubMesh ) continue;
2406 // //       itOnSubMesh = theSubMesh->GetElements();
2407 // //       for ( int j = 0; j < 4; ++j )
2408 // //       {
2409 // //         aFace = itOnSubMesh->next();
2410 // //         itOnSubFace = aFace->nodesIterator();
2411 // //         aqt.clear();
2412 // //         while ( itOnSubFace->more() ) {
2413 // //           // find GHS3D ID
2414 // //           aSmdsID = itOnSubFace->next()->GetID();
2415 // //           itOnMap = theSmdsToGhs3dIdMap.find( aSmdsID );
2416 // //           ASSERT( itOnMap != theSmdsToGhs3dIdMap.end() );
2417 // //           aqt.push_back((*itOnMap).second);
2418 // //         }
2419 // //         qt.push_back(aqt);
2420 // //       }
2421 // //     }
2422 // //   }
2423 // // 
2424 // //   if (theEnforcedQuadrangles.size()) {
2425 // //     // Iterate over the enforced triangles
2426 // //     for(elemIt = theEnforcedQuadrangles.begin() ; elemIt != theEnforcedQuadrangles.end() ; ++elemIt) {
2427 // //       aFace = (*elemIt);
2428 // //       bool isOK = true;
2429 // //       itOnSubFace = aFace->nodesIterator();
2430 // //       aqt.clear();
2431 // //       for ( int j = 0; j < 4; ++j ) {
2432 // //         int aNodeID = itOnSubFace->next()->GetID();
2433 // //         itOnMap = theNodeId2NodeIndexMap.find(aNodeID);
2434 // //         if (itOnMap != theNodeId2NodeIndexMap.end())
2435 // //           aqt.push_back((*itOnMap).second);
2436 // //         else {
2437 // //           isOK = false;
2438 // //           theEnforcedQuadrangles.erase(elemIt);
2439 // //           break;
2440 // //         }
2441 // //       }
2442 // //       if (isOK)
2443 // //         qt.push_back(aqt);
2444 // //     }
2445 // //   }
2446 // //  
2447 //   
2448 // //   /* Write quadrilaterals number */
2449 // //   if (qt.size()) {
2450 // //     GmfSetKwd(idx, GmfQuadrilaterals, qt.size());
2451 // //     for (int i=0;i<qt.size();i++)
2452 // //       GmfSetLin(idx, GmfQuadrilaterals, qt[i][0], qt[i][1], qt[i][2], qt[i][3], dummyint);
2453 // //   }
2454 // 
2455 //   GmfCloseMesh(idx);
2456 //   return true;
2457 // }
2458
2459
2460 //=======================================================================
2461 //function : writeFaces
2462 //purpose  : 
2463 //=======================================================================
2464
2465 static bool writeFaces (ofstream &              theFile,
2466                         const SMESH_ProxyMesh&  theMesh,
2467                         const TopoDS_Shape&     theShape,
2468                         const map <int,int> &   theSmdsToGhs3dIdMap,
2469                         const map <int,int> &   theEnforcedNodeIdToGhs3dIdMap,
2470                         GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedEdges,
2471                         GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedTriangles)
2472 {
2473   // record structure:
2474   //
2475   // NB_ELEMS DUMMY_INT
2476   // Loop from 1 to NB_ELEMS
2477   // NB_NODES NODE_NB_1 NODE_NB_2 ... (NB_NODES + 1) times: DUMMY_INT
2478
2479   TopoDS_Shape aShape;
2480   const SMESHDS_SubMesh* theSubMesh;
2481   const SMDS_MeshElement* aFace;
2482   const char* space    = "  ";
2483   const int   dummyint = 0;
2484   map<int,int>::const_iterator itOnMap;
2485   SMDS_ElemIteratorPtr itOnSubMesh, itOnSubFace;
2486   int nbNodes, aSmdsID;
2487
2488   TIDSortedElemSet::const_iterator elemIt;
2489   int nbEnforcedEdges       = theEnforcedEdges.size();
2490   int nbEnforcedTriangles   = theEnforcedTriangles.size();
2491
2492   // count triangles bound to geometry
2493   int nbTriangles = 0;
2494
2495   TopTools_IndexedMapOfShape facesMap, trianglesMap;
2496   TopExp::MapShapes( theShape, TopAbs_FACE, facesMap );
2497   
2498   int nbFaces = facesMap.Extent();
2499
2500   for ( int i = 1; i <= nbFaces; ++i )
2501     if (( theSubMesh  = theMesh.GetSubMesh( facesMap(i))))
2502       nbTriangles += theSubMesh->NbElements();
2503   std::string tmpStr;
2504   (nbFaces == 0 || nbFaces == 1) ? tmpStr = " shape " : tmpStr = " shapes " ;
2505   std::cout << "    " << nbFaces << tmpStr << "of 2D dimension";
2506   int nbEnforcedElements = nbEnforcedEdges+nbEnforcedTriangles;
2507   if (nbEnforcedElements > 0) {
2508     (nbEnforcedElements == 1) ? tmpStr = "shape:" : tmpStr = "shapes:";
2509     std::cout << " and" << std::endl;
2510     std::cout << "    " << nbEnforcedElements 
2511                         << " enforced " << tmpStr << std::endl;
2512   }
2513   else
2514     std::cout << std::endl;
2515   if (nbEnforcedEdges) {
2516     (nbEnforcedEdges == 1) ? tmpStr = "edge" : tmpStr = "edges";
2517     std::cout << "      " << nbEnforcedEdges << " enforced " << tmpStr << std::endl;
2518   }
2519   if (nbEnforcedTriangles) {
2520     (nbEnforcedTriangles == 1) ? tmpStr = "triangle" : tmpStr = "triangles";
2521     std::cout << "      " << nbEnforcedTriangles << " enforced " << tmpStr << std::endl;
2522   }
2523   std::cout << std::endl;
2524
2525 //   theFile << space << nbTriangles << space << dummyint << std::endl;
2526   std::ostringstream globalStream, localStream, aStream;
2527
2528   for ( int i = 1; i <= facesMap.Extent(); i++ )
2529   {
2530     aShape = facesMap(i);
2531     theSubMesh = theMesh.GetSubMesh(aShape);
2532     if ( !theSubMesh ) continue;
2533     itOnSubMesh = theSubMesh->GetElements();
2534     while ( itOnSubMesh->more() )
2535     {
2536       aFace = itOnSubMesh->next();
2537       nbNodes = aFace->NbCornerNodes();
2538
2539       localStream << nbNodes << space;
2540
2541       itOnSubFace = aFace->nodesIterator();
2542       for ( int j = 0; j < 3; ++j ) {
2543         // find GHS3D ID
2544         aSmdsID = itOnSubFace->next()->GetID();
2545         itOnMap = theSmdsToGhs3dIdMap.find( aSmdsID );
2546         // if ( itOnMap == theSmdsToGhs3dIdMap.end() ) {
2547         //   cout << "not found node: " << aSmdsID << endl;
2548         //   return false;
2549         // }
2550         ASSERT( itOnMap != theSmdsToGhs3dIdMap.end() );
2551
2552         localStream << (*itOnMap).second << space ;
2553       }
2554
2555       // (NB_NODES + 1) times: DUMMY_INT
2556       for ( int j=0; j<=nbNodes; j++)
2557         localStream << dummyint << space ;
2558
2559       localStream << std::endl;
2560     }
2561   }
2562   
2563   globalStream << localStream.str();
2564   localStream.str("");
2565
2566   //
2567   //        FACES : END
2568   //
2569
2570 //   //
2571 //   //        ENFORCED EDGES : BEGIN
2572 //   //
2573 //   
2574 //   // Iterate over the enforced edges
2575 //   int usedEnforcedEdges = 0;
2576 //   bool isOK;
2577 //   for(elemIt = theEnforcedEdges.begin() ; elemIt != theEnforcedEdges.end() ; ++elemIt) {
2578 //     aFace = (*elemIt);
2579 //     isOK = true;
2580 //     itOnSubFace = aFace->nodesIterator();
2581 //     aStream.str("");
2582 //     aStream << "2" << space ;
2583 //     for ( int j = 0; j < 2; ++j ) {
2584 //       aSmdsID = itOnSubFace->next()->GetID();
2585 //       itOnMap = theEnforcedNodeIdToGhs3dIdMap.find(aSmdsID);
2586 //       if (itOnMap != theEnforcedNodeIdToGhs3dIdMap.end())
2587 //         aStream << (*itOnMap).second << space;
2588 //       else {
2589 //         isOK = false;
2590 //         break;
2591 //       }
2592 //     }
2593 //     if (isOK) {
2594 //       for ( int j=0; j<=2; j++)
2595 //         aStream << dummyint << space ;
2596 // //       aStream << dummyint << space << dummyint;
2597 //       localStream << aStream.str() << std::endl;
2598 //       usedEnforcedEdges++;
2599 //     }
2600 //   }
2601 //   
2602 //   if (usedEnforcedEdges) {
2603 //     globalStream << localStream.str();
2604 //     localStream.str("");
2605 //   }
2606 // 
2607 //   //
2608 //   //        ENFORCED EDGES : END
2609 //   //
2610 //   //
2611 // 
2612 //   //
2613 //   //        ENFORCED TRIANGLES : BEGIN
2614 //   //
2615 //     // Iterate over the enforced triangles
2616 //   int usedEnforcedTriangles = 0;
2617 //   for(elemIt = theEnforcedTriangles.begin() ; elemIt != theEnforcedTriangles.end() ; ++elemIt) {
2618 //     aFace = (*elemIt);
2619 //     nbNodes = aFace->NbCornerNodes();
2620 //     isOK = true;
2621 //     itOnSubFace = aFace->nodesIterator();
2622 //     aStream.str("");
2623 //     aStream << nbNodes << space ;
2624 //     for ( int j = 0; j < 3; ++j ) {
2625 //       aSmdsID = itOnSubFace->next()->GetID();
2626 //       itOnMap = theEnforcedNodeIdToGhs3dIdMap.find(aSmdsID);
2627 //       if (itOnMap != theEnforcedNodeIdToGhs3dIdMap.end())
2628 //         aStream << (*itOnMap).second << space;
2629 //       else {
2630 //         isOK = false;
2631 //         break;
2632 //       }
2633 //     }
2634 //     if (isOK) {
2635 //       for ( int j=0; j<=3; j++)
2636 //         aStream << dummyint << space ;
2637 //       localStream << aStream.str() << std::endl;
2638 //       usedEnforcedTriangles++;
2639 //     }
2640 //   }
2641 //   
2642 //   if (usedEnforcedTriangles) {
2643 //     globalStream << localStream.str();
2644 //     localStream.str("");
2645 //   }
2646 // 
2647 //   //
2648 //   //        ENFORCED TRIANGLES : END
2649 //   //
2650   
2651   theFile
2652   << nbTriangles/*+usedEnforcedTriangles+usedEnforcedEdges*/
2653   << " 0" << std::endl
2654   << globalStream.str();
2655
2656   return true;
2657 }
2658
2659 //=======================================================================
2660 //function : writePoints
2661 //purpose  : 
2662 //=======================================================================
2663
2664 static bool writePoints (ofstream &                       theFile,
2665                          SMESH_MesherHelper&              theHelper,
2666                          map <int,int> &                  theSmdsToGhs3dIdMap,
2667                          map <int,int> &                  theEnforcedNodeIdToGhs3dIdMap,
2668                          map <int,const SMDS_MeshNode*> & theGhs3dIdToNodeMap,
2669                          GHS3DPlugin_Hypothesis::TID2SizeMap & theNodeIDToSizeMap,
2670                          GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues & theEnforcedVertices,
2671                          GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap & theEnforcedNodes,
2672                          GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedEdges,
2673                          GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedTriangles)
2674 {
2675   // record structure:
2676   //
2677   // NB_NODES
2678   // Loop from 1 to NB_NODES
2679   //   X Y Z DUMMY_INT
2680
2681   SMESHDS_Mesh * theMeshDS = theHelper.GetMeshDS();
2682   int nbNodes = theMeshDS->NbNodes();
2683   if ( nbNodes == 0 )
2684     return false;
2685   
2686   int nbEnforcedVertices = theEnforcedVertices.size();
2687   int nbEnforcedNodes    = theEnforcedNodes.size();
2688   
2689   const TopoDS_Shape shapeToMesh = theMeshDS->ShapeToMesh();
2690   
2691   int aGhs3dID = 1;
2692   SMDS_NodeIteratorPtr nodeIt = theMeshDS->nodesIterator();
2693   const SMDS_MeshNode* node;
2694
2695   // Issue 020674: EDF 870 SMESH: Mesh generated by Netgen not usable by GHS3D
2696   // The problem is in nodes on degenerated edges, we need to skip nodes which are free
2697   // and replace not-free nodes on degenerated edges by the node on vertex
2698   TNodeNodeMap n2nDegen; // map a node on degenerated edge to a node on vertex
2699   TNodeNodeMap::iterator n2nDegenIt;
2700   if ( theHelper.HasDegeneratedEdges() )
2701   {
2702     set<int> checkedSM;
2703     for (TopExp_Explorer e(theMeshDS->ShapeToMesh(), TopAbs_EDGE ); e.More(); e.Next())
2704     {
2705       SMESH_subMesh* sm = theHelper.GetMesh()->GetSubMesh( e.Current() );
2706       if ( checkedSM.insert( sm->GetId() ).second && theHelper.IsDegenShape(sm->GetId() ))
2707       {
2708         if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() )
2709         {
2710           TopoDS_Shape vertex = TopoDS_Iterator( e.Current() ).Value();
2711           const SMDS_MeshNode* vNode = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), theMeshDS);
2712           {
2713             SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2714             while ( nIt->more() )
2715               n2nDegen.insert( make_pair( nIt->next(), vNode ));
2716           }
2717         }
2718       }
2719     }
2720     nbNodes -= n2nDegen.size();
2721   }
2722
2723   const bool isQuadMesh = 
2724     theHelper.GetMesh()->NbEdges( ORDER_QUADRATIC ) ||
2725     theHelper.GetMesh()->NbFaces( ORDER_QUADRATIC ) ||
2726     theHelper.GetMesh()->NbVolumes( ORDER_QUADRATIC );
2727   if ( isQuadMesh )
2728   {
2729     // descrease nbNodes by nb of medium nodes
2730     while ( nodeIt->more() )
2731     {
2732       node = nodeIt->next();
2733       if ( !theHelper.IsDegenShape( node->getshapeId() ))
2734         nbNodes -= int( theHelper.IsMedium( node ));
2735     }
2736     nodeIt = theMeshDS->nodesIterator();
2737   }
2738
2739   const char* space    = "  ";
2740   const int   dummyint = 0;
2741
2742   std::string tmpStr;
2743   (nbNodes == 0 || nbNodes == 1) ? tmpStr = " node" : tmpStr = " nodes";
2744   // NB_NODES
2745   std::cout << std::endl;
2746   std::cout << "The initial 2D mesh contains :" << std::endl;
2747   std::cout << "    " << nbNodes << tmpStr << std::endl;
2748   if (nbEnforcedVertices > 0) {
2749     (nbEnforcedVertices == 1) ? tmpStr = "vertex" : tmpStr = "vertices";
2750     std::cout << "    " << nbEnforcedVertices << " enforced " << tmpStr << std::endl;
2751   }
2752   if (nbEnforcedNodes > 0) {
2753     (nbEnforcedNodes == 1) ? tmpStr = "node" : tmpStr = "nodes";
2754     std::cout << "    " << nbEnforcedNodes << " enforced " << tmpStr << std::endl;
2755   }
2756   std::cout << std::endl;
2757   std::cout << "Start writing in 'points' file ..." << std::endl;
2758
2759   theFile << nbNodes << std::endl;
2760
2761   // Loop from 1 to NB_NODES
2762
2763   while ( nodeIt->more() )
2764   {
2765     node = nodeIt->next();
2766     if ( isQuadMesh && theHelper.IsMedium( node )) // Issue 0021238
2767       continue;
2768     if ( n2nDegen.count( node ) ) // Issue 0020674
2769       continue;
2770
2771     theSmdsToGhs3dIdMap.insert( make_pair( node->GetID(), aGhs3dID ));
2772     theGhs3dIdToNodeMap.insert( make_pair( aGhs3dID, node ));
2773     aGhs3dID++;
2774
2775     // X Y Z DUMMY_INT
2776     theFile
2777     << node->X() << space 
2778     << node->Y() << space 
2779     << node->Z() << space 
2780     << dummyint;
2781
2782     theFile << std::endl;
2783
2784   }
2785   
2786   // Iterate over the enforced nodes
2787   std::map<int,double> enfVertexIndexSizeMap;
2788   if (nbEnforcedNodes) {
2789     GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap::const_iterator nodeIt = theEnforcedNodes.begin();
2790     for( ; nodeIt != theEnforcedNodes.end() ; ++nodeIt) {
2791       double x = nodeIt->first->X();
2792       double y = nodeIt->first->Y();
2793       double z = nodeIt->first->Z();
2794       // Test if point is inside shape to mesh
2795       gp_Pnt myPoint(x,y,z);
2796       BRepClass3d_SolidClassifier scl(shapeToMesh);
2797       scl.Perform(myPoint, 1e-7);
2798       TopAbs_State result = scl.State();
2799       if ( result != TopAbs_IN )
2800         continue;
2801       std::vector<double> coords;
2802       coords.push_back(x);
2803       coords.push_back(y);
2804       coords.push_back(z);
2805       if (theEnforcedVertices.find(coords) != theEnforcedVertices.end())
2806         continue;
2807         
2808 //      double size = theNodeIDToSizeMap.find(nodeIt->first->GetID())->second;
2809   //       theGhs3dIdToNodeMap.insert( make_pair( nbNodes + i, (*nodeIt) ));
2810   //       MESSAGE("Adding enforced node (" << x << "," << y <<"," << z << ")");
2811       // X Y Z PHY_SIZE DUMMY_INT
2812       theFile
2813       << x << space 
2814       << y << space 
2815       << z << space
2816       << -1 << space
2817       << dummyint << space;
2818       theFile << std::endl;
2819       theEnforcedNodeIdToGhs3dIdMap.insert( make_pair( nodeIt->first->GetID(), aGhs3dID ));
2820       enfVertexIndexSizeMap[aGhs3dID] = -1;
2821       aGhs3dID++;
2822   //     else
2823   //         MESSAGE("Enforced vertex (" << x << "," << y <<"," << z << ") is not inside the geometry: it was not added ");
2824     }
2825   }
2826   
2827   if (nbEnforcedVertices) {
2828     // Iterate over the enforced vertices
2829     GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues::const_iterator vertexIt = theEnforcedVertices.begin();
2830     for( ; vertexIt != theEnforcedVertices.end() ; ++vertexIt) {
2831       double x = vertexIt->first[0];
2832       double y = vertexIt->first[1];
2833       double z = vertexIt->first[2];
2834       // Test if point is inside shape to mesh
2835       gp_Pnt myPoint(x,y,z);
2836       BRepClass3d_SolidClassifier scl(shapeToMesh);
2837       scl.Perform(myPoint, 1e-7);
2838       TopAbs_State result = scl.State();
2839       if ( result != TopAbs_IN )
2840         continue;
2841       MESSAGE("Adding enforced vertex (" << x << "," << y <<"," << z << ") = " << vertexIt->second);
2842       // X Y Z PHY_SIZE DUMMY_INT
2843       theFile
2844       << x << space 
2845       << y << space 
2846       << z << space
2847       << vertexIt->second << space 
2848       << dummyint << space;
2849       theFile << std::endl;
2850       enfVertexIndexSizeMap[aGhs3dID] = vertexIt->second;
2851       aGhs3dID++;
2852     }
2853   }
2854   
2855   
2856   std::cout << std::endl;
2857   std::cout << "End writing in 'points' file." << std::endl;
2858
2859   return true;
2860 }
2861
2862 //=======================================================================
2863 //function : readResultFile
2864 //purpose  : readResultFile with geometry
2865 //=======================================================================
2866
2867 static bool readResultFile(const int                       fileOpen,
2868 #ifdef WNT
2869                            const char*                     fileName,
2870 #endif
2871                            GHS3DPlugin_GHS3D*              theAlgo,
2872                            SMESH_MesherHelper&             theHelper,
2873                            TopoDS_Shape                    tabShape[],
2874                            double**                        tabBox,
2875                            const int                       nbShape,
2876                            map <int,const SMDS_MeshNode*>& theGhs3dIdToNodeMap,
2877                            std::map <int,int> &            theNodeId2NodeIndexMap,
2878                            bool                            toMeshHoles,
2879                            int                             nbEnforcedVertices,
2880                            int                             nbEnforcedNodes,
2881                            GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedEdges,
2882                            GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedTriangles)
2883 {
2884   MESSAGE("GHS3DPlugin_GHS3D::readResultFile()");
2885   Kernel_Utils::Localizer loc;
2886   struct stat status;
2887   size_t      length;
2888   
2889   std::string tmpStr;
2890
2891   char *ptr, *mapPtr;
2892   char *tetraPtr;
2893   char *shapePtr;
2894
2895   SMESHDS_Mesh* theMeshDS = theHelper.GetMeshDS();
2896
2897   int nbElems, nbNodes, nbInputNodes;
2898   int nbTriangle;
2899   int ID, shapeID, ghs3dShapeID;
2900   int IdShapeRef = 1;
2901   int compoundID =
2902     nbShape ? theMeshDS->ShapeToIndex( tabShape[0] ) : theMeshDS->ShapeToIndex( theMeshDS->ShapeToMesh() );
2903
2904   int *tab, *tabID, *nodeID, *nodeAssigne;
2905   double *coord;
2906   const SMDS_MeshNode **node;
2907
2908   tab    = new int[3];
2909   nodeID = new int[4];
2910   coord  = new double[3];
2911   node   = new const SMDS_MeshNode*[4];
2912
2913   TopoDS_Shape aSolid;
2914   SMDS_MeshNode * aNewNode;
2915   map <int,const SMDS_MeshNode*>::iterator itOnNode;
2916   SMDS_MeshElement* aTet;
2917 #ifdef _DEBUG_
2918   set<int> shapeIDs;
2919 #endif
2920
2921   // Read the file state
2922   fstat(fileOpen, &status);
2923   length   = status.st_size;
2924
2925   // Mapping the result file into memory
2926 #ifdef WNT
2927   HANDLE fd = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ,
2928                          NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
2929   HANDLE hMapObject = CreateFileMapping(fd, NULL, PAGE_READONLY,
2930                                         0, (DWORD)length, NULL);
2931   ptr = ( char* ) MapViewOfFile(hMapObject, FILE_MAP_READ, 0, 0, 0 );
2932 #else
2933   ptr = (char *) mmap(0,length,PROT_READ,MAP_PRIVATE,fileOpen,0);
2934 #endif
2935   mapPtr = ptr;
2936
2937   ptr      = readMapIntLine(ptr, tab);
2938   tetraPtr = ptr;
2939
2940   nbElems      = tab[0];
2941   nbNodes      = tab[1];
2942   nbInputNodes = tab[2];
2943
2944   nodeAssigne = new int[ nbNodes+1 ];
2945
2946   if (nbShape > 0)
2947     aSolid = tabShape[0];
2948
2949   // Reading the nodeId
2950   for (int i=0; i < 4*nbElems; i++)
2951     strtol(ptr, &ptr, 10);
2952
2953   MESSAGE("nbInputNodes: "<<nbInputNodes);
2954   MESSAGE("nbEnforcedVertices: "<<nbEnforcedVertices);
2955   MESSAGE("nbEnforcedNodes: "<<nbEnforcedNodes);
2956   // Reading the nodeCoor and update the nodeMap
2957   for (int iNode=1; iNode <= nbNodes; iNode++) {
2958     if(theAlgo->computeCanceled())
2959       return false;
2960     for (int iCoor=0; iCoor < 3; iCoor++)
2961       coord[ iCoor ] = strtod(ptr, &ptr);
2962     nodeAssigne[ iNode ] = 1;
2963     if ( iNode > (nbInputNodes-(nbEnforcedVertices+nbEnforcedNodes)) ) {
2964       // Creating SMESH nodes
2965       // - for enforced vertices
2966       // - for vertices of forced edges
2967       // - for ghs3d nodes
2968       nodeAssigne[ iNode ] = 0;
2969       aNewNode = theMeshDS->AddNode( coord[0],coord[1],coord[2] );
2970       theGhs3dIdToNodeMap.insert(theGhs3dIdToNodeMap.end(), make_pair( iNode, aNewNode ));
2971     }
2972   }
2973
2974   // Reading the number of triangles which corresponds to the number of sub-domains
2975   nbTriangle = strtol(ptr, &ptr, 10);
2976
2977   tabID = new int[nbTriangle];
2978   for (int i=0; i < nbTriangle; i++) {
2979     if(theAlgo->computeCanceled())
2980       return false;
2981     tabID[i] = 0;
2982     // find the solid corresponding to GHS3D sub-domain following
2983     // the technique proposed in GHS3D manual in chapter
2984     // "B.4 Subdomain (sub-region) assignment"
2985     int nodeId1 = strtol(ptr, &ptr, 10);
2986     int nodeId2 = strtol(ptr, &ptr, 10);
2987     int nodeId3 = strtol(ptr, &ptr, 10);
2988     if ( nbTriangle > 1 ) {
2989       const SMDS_MeshNode* n1 = theGhs3dIdToNodeMap[ nodeId1 ];
2990       const SMDS_MeshNode* n2 = theGhs3dIdToNodeMap[ nodeId2 ];
2991       const SMDS_MeshNode* n3 = theGhs3dIdToNodeMap[ nodeId3 ];
2992       if (!n1 || !n2 || !n3) {
2993         tabID[i] = HOLE_ID;
2994         continue;
2995       }
2996       try {
2997         OCC_CATCH_SIGNALS;
2998 //         tabID[i] = findShapeID( theHelper, n1, n2, n3, toMeshHoles );
2999         tabID[i] = findShapeID( *theHelper.GetMesh(), n1, n2, n3, toMeshHoles );
3000         // -- 0020330: Pb with ghs3d as a submesh
3001         // check that found shape is to be meshed
3002         if ( tabID[i] > 0 ) {
3003           const TopoDS_Shape& foundShape = theMeshDS->IndexToShape( tabID[i] );
3004           bool isToBeMeshed = false;
3005           for ( int iS = 0; !isToBeMeshed && iS < nbShape; ++iS )
3006             isToBeMeshed = foundShape.IsSame( tabShape[ iS ]);
3007           if ( !isToBeMeshed )
3008             tabID[i] = HOLE_ID;
3009         }
3010         // END -- 0020330: Pb with ghs3d as a submesh
3011 #ifdef _DEBUG_
3012         std::cout << i+1 << " subdomain: findShapeID() returns " << tabID[i] << std::endl;
3013 #endif
3014       }
3015       catch ( Standard_Failure & ex)
3016       {
3017 #ifdef _DEBUG_
3018         std::cout << i+1 << " subdomain: Exception caugt: " << ex.GetMessageString() << std::endl;
3019 #endif
3020       }
3021       catch (...) {
3022 #ifdef _DEBUG_
3023         std::cout << i+1 << " subdomain: unknown exception caught " << std::endl;
3024 #endif
3025       }
3026     }
3027   }
3028
3029   shapePtr = ptr;
3030
3031   if ( nbTriangle <= nbShape ) // no holes
3032     toMeshHoles = true; // not avoid creating tetras in holes
3033
3034   // Associating the tetrahedrons to the shapes
3035   shapeID = compoundID;
3036   for (int iElem = 0; iElem < nbElems; iElem++) {
3037     if(theAlgo->computeCanceled())
3038       return false;
3039     for (int iNode = 0; iNode < 4; iNode++) {
3040       ID = strtol(tetraPtr, &tetraPtr, 10);
3041       itOnNode = theGhs3dIdToNodeMap.find(ID);
3042       node[ iNode ] = itOnNode->second;
3043       nodeID[ iNode ] = ID;
3044     }
3045     // We always run GHS3D with "to mesh holes"==TRUE but we must not create
3046     // tetras within holes depending on hypo option,
3047     // so we first check if aTet is inside a hole and then create it 
3048     //aTet = theMeshDS->AddVolume( node[1], node[0], node[2], node[3] );
3049     if ( nbTriangle > 1 ) {
3050       shapeID = HOLE_ID; // negative shapeID means not to create tetras if !toMeshHoles
3051       ghs3dShapeID = strtol(shapePtr, &shapePtr, 10) - IdShapeRef;
3052       if ( tabID[ ghs3dShapeID ] == 0 ) {
3053         TopAbs_State state;
3054         aSolid = findShape(node, aSolid, tabShape, tabBox, nbShape, &state);
3055         if ( toMeshHoles || state == TopAbs_IN )
3056           shapeID = theMeshDS->ShapeToIndex( aSolid );
3057         tabID[ ghs3dShapeID ] = shapeID;
3058       }
3059       else
3060         shapeID = tabID[ ghs3dShapeID ];
3061     }
3062     else if ( nbShape > 1 ) {
3063       // Case where nbTriangle == 1 while nbShape == 2 encountered
3064       // with compound of 2 boxes and "To mesh holes"==False,
3065       // so there are no subdomains specified for each tetrahedron.
3066       // Try to guess a solid by a node already bound to shape
3067       shapeID = 0;
3068       for ( int i=0; i<4 && shapeID==0; i++ ) {
3069         if ( nodeAssigne[ nodeID[i] ] == 1 &&
3070              node[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE &&
3071              node[i]->getshapeId() > 1 )
3072         {
3073           shapeID = node[i]->getshapeId();
3074         }
3075       }
3076       if ( shapeID==0 ) {
3077         aSolid = findShape(node, aSolid, tabShape, tabBox, nbShape);
3078         shapeID = theMeshDS->ShapeToIndex( aSolid );
3079       }
3080     }
3081     // set new nodes and tetrahedron onto the shape
3082     for ( int i=0; i<4; i++ ) {
3083       if ( nodeAssigne[ nodeID[i] ] == 0 ) {
3084         if ( shapeID != HOLE_ID )
3085           theMeshDS->SetNodeInVolume( node[i], shapeID );
3086         nodeAssigne[ nodeID[i] ] = shapeID;
3087       }
3088     }
3089     if ( toMeshHoles || shapeID != HOLE_ID ) {
3090       aTet = theHelper.AddVolume( node[1], node[0], node[2], node[3],
3091                                   /*id=*/0, /*force3d=*/false);
3092       theMeshDS->SetMeshElementOnShape( aTet, shapeID );
3093     }
3094 #ifdef _DEBUG_
3095     shapeIDs.insert( shapeID );
3096 #endif
3097   }
3098   
3099   // Add enforced elements
3100   GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap::const_iterator elemIt;
3101   const SMDS_MeshElement* anElem;
3102   SMDS_ElemIteratorPtr itOnEnfElem;
3103   map<int,int>::const_iterator itOnMap;
3104   shapeID = compoundID;
3105   // Enforced edges
3106   if (theEnforcedEdges.size()) {
3107     (theEnforcedEdges.size() <= 1) ? tmpStr = " enforced edge" : " enforced edges";
3108     std::cout << "Add " << theEnforcedEdges.size() << tmpStr << std::endl;
3109     std::vector< const SMDS_MeshNode* > node( 2 );
3110     // Iterate over the enforced edges
3111     for(elemIt = theEnforcedEdges.begin() ; elemIt != theEnforcedEdges.end() ; ++elemIt) {
3112       anElem = elemIt->first;
3113       bool addElem = true;
3114       itOnEnfElem = anElem->nodesIterator();
3115       for ( int j = 0; j < 2; ++j ) {
3116         int aNodeID = itOnEnfElem->next()->GetID();
3117         itOnMap = theNodeId2NodeIndexMap.find(aNodeID);
3118         if (itOnMap != theNodeId2NodeIndexMap.end()) {
3119           itOnNode = theGhs3dIdToNodeMap.find((*itOnMap).second);
3120           if (itOnNode != theGhs3dIdToNodeMap.end()) {
3121             node.push_back((*itOnNode).second);
3122 //             shapeID =(*itOnNode).second->getshapeId();
3123           }
3124           else
3125             addElem = false;
3126         }
3127         else
3128           addElem = false;
3129       }
3130       if (addElem) {
3131         aTet = theHelper.AddEdge( node[0], node[1], 0,  false);
3132         theMeshDS->SetMeshElementOnShape( aTet, shapeID );
3133       }
3134     }
3135   }
3136   // Enforced faces
3137   if (theEnforcedTriangles.size()) {
3138     (theEnforcedTriangles.size() <= 1) ? tmpStr = " enforced triangle" : " enforced triangles";
3139     std::cout << "Add " << theEnforcedTriangles.size() << " enforced triangles" << std::endl;
3140     std::vector< const SMDS_MeshNode* > node( 3 );
3141     // Iterate over the enforced triangles
3142     for(elemIt = theEnforcedTriangles.begin() ; elemIt != theEnforcedTriangles.end() ; ++elemIt) {
3143       anElem = elemIt->first;
3144       bool addElem = true;
3145       itOnEnfElem = anElem->nodesIterator();
3146       for ( int j = 0; j < 3; ++j ) {
3147         int aNodeID = itOnEnfElem->next()->GetID();
3148         itOnMap = theNodeId2NodeIndexMap.find(aNodeID);
3149         if (itOnMap != theNodeId2NodeIndexMap.end()) {
3150           itOnNode = theGhs3dIdToNodeMap.find((*itOnMap).second);
3151           if (itOnNode != theGhs3dIdToNodeMap.end()) {
3152             node.push_back((*itOnNode).second);
3153 //             shapeID =(*itOnNode).second->getshapeId();
3154           }
3155           else
3156             addElem = false;
3157         }
3158         else
3159           addElem = false;
3160       }
3161       if (addElem) {
3162         aTet = theHelper.AddFace( node[0], node[1], node[2], 0,  false);
3163         theMeshDS->SetMeshElementOnShape( aTet, shapeID );
3164       }
3165     }
3166   }
3167
3168   // Remove nodes of tetras inside holes if !toMeshHoles
3169   if ( !toMeshHoles ) {
3170     itOnNode = theGhs3dIdToNodeMap.find( nbInputNodes );
3171     for ( ; itOnNode != theGhs3dIdToNodeMap.end(); ++itOnNode) {
3172       ID = itOnNode->first;
3173       if ( nodeAssigne[ ID ] == HOLE_ID )
3174         theMeshDS->RemoveFreeNode( itOnNode->second, 0 );
3175     }
3176   }
3177
3178   
3179   if ( nbElems ) {
3180     (nbElems <= 1) ? tmpStr = " tetrahedra" : " tetrahedrons";
3181     cout << nbElems << tmpStr << " have been associated to " << nbShape;
3182     (nbShape <= 1) ? tmpStr = " shape" : " shapes";
3183     cout << tmpStr << endl;
3184   }
3185 #ifdef WNT
3186   UnmapViewOfFile(mapPtr);
3187   CloseHandle(hMapObject);
3188   CloseHandle(fd);
3189 #else
3190   munmap(mapPtr, length);
3191 #endif
3192   close(fileOpen);
3193
3194   delete [] tab;
3195   delete [] tabID;
3196   delete [] nodeID;
3197   delete [] coord;
3198   delete [] node;
3199   delete [] nodeAssigne;
3200
3201 #ifdef _DEBUG_
3202   shapeIDs.erase(-1);
3203   if ( shapeIDs.size() != nbShape ) {
3204     (shapeIDs.size() <= 1) ? tmpStr = " solid" : " solids";
3205     std::cout << "Only " << shapeIDs.size() << tmpStr << " of " << nbShape << " found" << std::endl;
3206     for (int i=0; i<nbShape; i++) {
3207       shapeID = theMeshDS->ShapeToIndex( tabShape[i] );
3208       if ( shapeIDs.find( shapeID ) == shapeIDs.end() )
3209         std::cout << "  Solid #" << shapeID << " not found" << std::endl;
3210     }
3211   }
3212 #endif
3213
3214   return true;
3215 }
3216
3217
3218 //=============================================================================
3219 /*!
3220  *Here we are going to use the GHS3D mesher with geometry
3221  */
3222 //=============================================================================
3223
3224 bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
3225                                 const TopoDS_Shape& theShape)
3226 {
3227   bool Ok(false);
3228   //SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
3229
3230   // we count the number of shapes
3231   // _nbShape = countShape( meshDS, TopAbs_SOLID ); -- 0020330: Pb with ghs3d as a submesh
3232   _nbShape = 0;
3233   TopExp_Explorer expBox ( theShape, TopAbs_SOLID );
3234   for ( ; expBox.More(); expBox.Next() )
3235     _nbShape++;
3236
3237   // create bounding box for every shape inside the compound
3238
3239   int iShape = 0;
3240   TopoDS_Shape* tabShape;
3241   double**      tabBox;
3242   tabShape = new TopoDS_Shape[_nbShape];
3243   tabBox   = new double*[_nbShape];
3244   for (int i=0; i<_nbShape; i++)
3245     tabBox[i] = new double[6];
3246   Standard_Real Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
3247
3248   for (expBox.ReInit(); expBox.More(); expBox.Next()) {
3249     tabShape[iShape] = expBox.Current();
3250     Bnd_Box BoundingBox;
3251     BRepBndLib::Add(expBox.Current(), BoundingBox);
3252     BoundingBox.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
3253     tabBox[iShape][0] = Xmin; tabBox[iShape][1] = Xmax;
3254     tabBox[iShape][2] = Ymin; tabBox[iShape][3] = Ymax;
3255     tabBox[iShape][4] = Zmin; tabBox[iShape][5] = Zmax;
3256     iShape++;
3257   }
3258
3259   // a unique working file name
3260   // to avoid access to the same files by eg different users
3261   _genericName = GHS3DPlugin_Hypothesis::GetFileName(_hyp);
3262   TCollection_AsciiString aGenericName((char*) _genericName.c_str() );
3263
3264   TCollection_AsciiString aResultFileName;
3265   TCollection_AsciiString aLogFileName    = aGenericName + ".log";    // log
3266   // The output .mesh file does not contain yet the subdomain-info (Ghs3D 4.2)
3267 //   TCollection_AsciiString aGMFFileName, aRequiredVerticesFileName, aSolFileName;
3268 //   TCollection_AsciiString aGenericNameRequired = aGenericName + "_required";
3269 // #ifdef _DEBUG_
3270 //   aGMFFileName    = aGenericName + ".mesh"; // GMF mesh file
3271 //   aResultFileName = aGenericName + "Vol.mesh"; // GMF mesh file
3272 //   aRequiredVerticesFileName    = aGenericNameRequired + ".mesh"; // GMF required vertices mesh file
3273 //   aSolFileName    = aGenericName + "_required.sol"; // GMF solution file
3274 // #else
3275 //   aGMFFileName    = aGenericName + ".meshb"; // GMF mesh file
3276 //   aResultFileName = aGenericName + "Vol.meshb"; // GMF mesh file
3277 //   aRequiredVerticesFileName    = aGenericNameRequired + ".meshb"; // GMF required vertices mesh file
3278 //   aSolFileName    = aGenericName + "_required.solb"; // GMF solution file
3279 // #endif
3280
3281   TCollection_AsciiString aFacesFileName, aPointsFileName, aBadResFileName, aBbResFileName;
3282
3283   aFacesFileName  = aGenericName + ".faces";  // in faces
3284   aPointsFileName = aGenericName + ".points"; // in points
3285   aResultFileName = aGenericName + ".noboite";// out points and volumes
3286   aBadResFileName = aGenericName + ".boite";  // out bad result
3287   aBbResFileName  = aGenericName + ".bb";     // out vertex stepsize
3288   
3289   // -----------------
3290   // make input files
3291   // -----------------
3292
3293   ofstream aFacesFile  ( aFacesFileName.ToCString()  , ios::out);
3294   ofstream aPointsFile ( aPointsFileName.ToCString() , ios::out);
3295
3296   Ok =
3297     aFacesFile.rdbuf()->is_open() && aPointsFile.rdbuf()->is_open();
3298   if (!Ok) {
3299     INFOS( "Can't write into " << aFacesFileName);
3300     return error(SMESH_Comment("Can't write into ") << aFacesFileName);
3301   }
3302
3303   std::map <int,int> aNodeId2NodeIndexMap, aSmdsToGhs3dIdMap, anEnforcedNodeIdToGhs3dIdMap;
3304   std::map <int,const SMDS_MeshNode*> aGhs3dIdToNodeMap;
3305   std::map <int, int> nodeID2nodeIndexMap;
3306   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues coordsSizeMap = GHS3DPlugin_Hypothesis::GetEnforcedVerticesCoordsSize(_hyp);
3307   GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap enforcedNodes = GHS3DPlugin_Hypothesis::GetEnforcedNodes(_hyp);
3308   GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap enforcedEdges = GHS3DPlugin_Hypothesis::GetEnforcedEdges(_hyp);
3309   GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap enforcedTriangles = GHS3DPlugin_Hypothesis::GetEnforcedTriangles(_hyp);
3310 //   TIDSortedElemSet enforcedQuadrangles = GHS3DPlugin_Hypothesis::GetEnforcedQuadrangles(_hyp);
3311   GHS3DPlugin_Hypothesis::TID2SizeMap nodeIDToSizeMap = GHS3DPlugin_Hypothesis::GetNodeIDToSizeMap(_hyp);
3312
3313   int nbEnforcedVertices = coordsSizeMap.size();
3314   int nbEnforcedNodes = enforcedNodes.size();
3315   
3316   std::string tmpStr;
3317   (nbEnforcedNodes <= 1) ? tmpStr = "node" : "nodes";
3318   std::cout << nbEnforcedNodes << " enforced " << tmpStr << " from hypo" << std::endl;
3319   (nbEnforcedVertices <= 1) ? tmpStr = "vertex" : "vertices";
3320   std::cout << nbEnforcedVertices << " enforced " << tmpStr << " from hypo" << std::endl;
3321   
3322   SMESH_MesherHelper helper( theMesh );
3323   helper.SetSubShape( theShape );
3324
3325   {
3326     SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
3327
3328     // make prisms on quadrangles
3329     if ( theMesh.NbQuadrangles() > 0 )
3330     {
3331       vector<SMESH_ProxyMesh::Ptr> components;
3332       for (expBox.ReInit(); expBox.More(); expBox.Next())
3333       {
3334         if ( _viscousLayersHyp )
3335         {
3336           proxyMesh = _viscousLayersHyp->Compute( theMesh, expBox.Current() );
3337           if ( !proxyMesh )
3338             return false;
3339         }
3340         StdMeshers_QuadToTriaAdaptor* q2t = new StdMeshers_QuadToTriaAdaptor;
3341         q2t->Compute( theMesh, expBox.Current(), proxyMesh.get() );
3342         components.push_back( SMESH_ProxyMesh::Ptr( q2t ));
3343       }
3344       proxyMesh.reset( new SMESH_ProxyMesh( components ));
3345     }
3346     // build viscous layers
3347     else if ( _viscousLayersHyp )
3348     {
3349       proxyMesh = _viscousLayersHyp->Compute( theMesh, theShape );
3350       if ( !proxyMesh )
3351         return false;
3352     }
3353
3354     Ok = (writePoints( aPointsFile, helper, 
3355                        aSmdsToGhs3dIdMap, anEnforcedNodeIdToGhs3dIdMap, aGhs3dIdToNodeMap, 
3356                        nodeIDToSizeMap,
3357                        coordsSizeMap, enforcedNodes, enforcedEdges, enforcedTriangles)
3358           &&
3359           writeFaces ( aFacesFile, *proxyMesh, theShape, 
3360                        aSmdsToGhs3dIdMap, anEnforcedNodeIdToGhs3dIdMap,
3361                        enforcedEdges, enforcedTriangles ));
3362 //     Ok = writeGMFFile(aGMFFileName.ToCString(), aRequiredVerticesFileName.ToCString(), aSolFileName.ToCString(),
3363 //                       helper, *proxyMesh,
3364 //                       aNodeId2NodeIndexMap, aSmdsToGhs3dIdMap, aGhs3dIdToNodeMap,
3365 //                       enforcedNodes, enforcedEdges, enforcedTriangles, /*enforcedQuadrangles,*/
3366 //                       coordsSizeMap);
3367   }
3368
3369   // Write aSmdsToGhs3dIdMap to temp file
3370   TCollection_AsciiString aSmdsToGhs3dIdMapFileName;
3371   aSmdsToGhs3dIdMapFileName = aGenericName + ".ids";  // ids relation
3372   ofstream aIdsFile  ( aSmdsToGhs3dIdMapFileName.ToCString()  , ios::out);
3373   Ok = aIdsFile.rdbuf()->is_open();
3374   if (!Ok) {
3375     INFOS( "Can't write into " << aSmdsToGhs3dIdMapFileName);
3376     return error(SMESH_Comment("Can't write into ") << aSmdsToGhs3dIdMapFileName);
3377   }
3378   INFOS( "Writing ids relation into " << aSmdsToGhs3dIdMapFileName);
3379   aIdsFile << "Smds Ghs3d" << std::endl;
3380   map <int,int>::const_iterator myit;
3381   for (myit=aSmdsToGhs3dIdMap.begin() ; myit != aSmdsToGhs3dIdMap.end() ; ++myit) {
3382     aIdsFile << myit->first << " " << myit->second << std::endl;
3383   }
3384
3385   aIdsFile.close();
3386   aFacesFile.close();
3387   aPointsFile.close();
3388   
3389   if ( ! Ok ) {
3390     if ( !_keepFiles ) {
3391 //       removeFile( aGMFFileName );
3392 //       removeFile( aRequiredVerticesFileName );
3393 //       removeFile( aSolFileName );
3394       removeFile( aFacesFileName );
3395       removeFile( aPointsFileName );
3396       removeFile( aSmdsToGhs3dIdMapFileName );
3397     }
3398     return error(COMPERR_BAD_INPUT_MESH);
3399   }
3400   removeFile( aResultFileName ); // needed for boundary recovery module usage
3401
3402   // -----------------
3403   // run ghs3d mesher
3404   // -----------------
3405
3406   TCollection_AsciiString cmd( (char*)GHS3DPlugin_Hypothesis::CommandToRun( _hyp ).c_str() );
3407   cmd += TCollection_AsciiString(" -f ") + aGenericName;  // file to read
3408   cmd += TCollection_AsciiString(" 1>" ) + aLogFileName;  // dump into file
3409   // The output .mesh file does not contain yet the subdomain-info (Ghs3D 4.2)
3410 //   cmd += TCollection_AsciiString(" --in ") + aGenericName;
3411 //   cmd += TCollection_AsciiString(" --required_vertices ") + aGenericNameRequired;
3412 //    cmd += TCollection_AsciiString(" --out ") + aResultGMFFileName;
3413 //   cmd += TCollection_AsciiString(" 1>" ) + aLogFileName;  // dump into file
3414
3415   std::cout << std::endl;
3416   std::cout << "Ghs3d execution..." << std::endl;
3417   std::cout << cmd << std::endl;
3418
3419   _compute_canceled = false;
3420
3421   system( cmd.ToCString() ); // run
3422
3423   std::cout << std::endl;
3424   std::cout << "End of Ghs3d execution !" << std::endl;
3425
3426   // --------------
3427   // read a result
3428   // --------------
3429
3430   // Mapping the result file
3431
3432   int fileOpen;
3433   fileOpen = open( aResultFileName.ToCString(), O_RDONLY);
3434   if ( fileOpen < 0 ) {
3435     std::cout << std::endl;
3436     std::cout << "Can't open the " << aResultFileName.ToCString() << " GHS3D output file" << std::endl;
3437     std::cout << "Log: " << aLogFileName << std::endl;
3438     Ok = false;
3439   }
3440   else {
3441     bool toMeshHoles =
3442       _hyp ? _hyp->GetToMeshHoles(true) : GHS3DPlugin_Hypothesis::DefaultMeshHoles();
3443
3444     helper.IsQuadraticSubMesh( theShape );
3445     helper.SetElementsOnShape( false );
3446
3447     Ok = readResultFile( fileOpen,
3448 #ifdef WNT
3449                          aResultFileName.ToCString(),
3450 #endif
3451                          this,
3452                          /*theMesh, */helper, tabShape, tabBox, _nbShape, 
3453                          aGhs3dIdToNodeMap, aNodeId2NodeIndexMap,
3454                          toMeshHoles, 
3455                          nbEnforcedVertices, nbEnforcedNodes, 
3456                          enforcedEdges, enforcedTriangles );
3457                          
3458 //       Ok = readGMFFile(
3459 // #ifndef GMF_HAS_SUBDOMAIN_INFO
3460 //                        fileOpen,
3461 // #endif
3462 //                        aGenericName.ToCString(), theMesh,
3463 //                        _nbShape, tabShape, tabBox, 
3464 //                        aGhs3dIdToNodeMap, toMeshHoles,
3465 //                        nbEnforcedVertices, nbEnforcedNodes);
3466   }
3467
3468
3469
3470
3471   // ---------------------
3472   // remove working files
3473   // ---------------------
3474
3475   if ( Ok )
3476   {
3477     if ( !_keepFiles )
3478       removeFile( aLogFileName );
3479
3480     if ( _hyp && _hyp->GetToMakeGroupsOfDomains() )
3481       error( COMPERR_WARNING, "'toMakeGroupsOfDomains' is ignored since the mesh is on shape" );
3482   }
3483   else if ( OSD_File( aLogFileName ).Size() > 0 )
3484   {
3485     // get problem description from the log file
3486     _Ghs2smdsConvertor conv( aGhs3dIdToNodeMap );
3487     storeErrorDescription( aLogFileName, conv );
3488   }
3489   else
3490   {
3491     // the log file is empty
3492     removeFile( aLogFileName );
3493     INFOS( "GHS3D Error, command '" << cmd.ToCString() << "' failed" );
3494     error(COMPERR_ALGO_FAILED, "ghs3d: command not found" );
3495   }
3496
3497   if ( !_keepFiles ) {
3498     if (! Ok)
3499       if(_compute_canceled)
3500         removeFile( aLogFileName );
3501     removeFile( aFacesFileName );
3502     removeFile( aPointsFileName );
3503     removeFile( aResultFileName );
3504     removeFile( aBadResFileName );
3505     removeFile( aBbResFileName );
3506     removeFile( aSmdsToGhs3dIdMapFileName );
3507   }
3508   std::cout << "<" << aResultFileName.ToCString() << "> GHS3D output file ";
3509   if ( !Ok )
3510     std::cout << "not ";
3511   std::cout << "treated !" << std::endl;
3512   std::cout << std::endl;
3513
3514   _nbShape = 0;    // re-initializing _nbShape for the next Compute() method call
3515   delete [] tabShape;
3516   delete [] tabBox;
3517
3518   return Ok;
3519 }
3520
3521 //=============================================================================
3522 /*!
3523  *Here we are going to use the GHS3D mesher w/o geometry
3524  */
3525 //=============================================================================
3526 bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
3527                                 SMESH_MesherHelper* theHelper)
3528 {
3529   MESSAGE("GHS3DPlugin_GHS3D::Compute()");
3530
3531   //SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
3532   TopoDS_Shape theShape = theHelper->GetSubShape();
3533
3534   // a unique working file name
3535   // to avoid access to the same files by eg different users
3536   _genericName = GHS3DPlugin_Hypothesis::GetFileName(_hyp);
3537   TCollection_AsciiString aGenericName((char*) _genericName.c_str() );
3538   TCollection_AsciiString aGenericNameRequired = aGenericName + "_required";
3539
3540   TCollection_AsciiString aLogFileName    = aGenericName + ".log";    // log
3541   TCollection_AsciiString aResultFileName;
3542   bool Ok;
3543
3544   TCollection_AsciiString aGMFFileName, aRequiredVerticesFileName, aSolFileName;
3545 //#ifdef _DEBUG_
3546   aGMFFileName              = aGenericName + ".mesh"; // GMF mesh file
3547   aResultFileName           = aGenericName + "Vol.mesh"; // GMF mesh file
3548   aRequiredVerticesFileName = aGenericNameRequired + ".mesh"; // GMF required vertices mesh file
3549   aSolFileName              = aGenericNameRequired + ".sol"; // GMF solution file
3550 //#else
3551 //  aGMFFileName    = aGenericName + ".meshb"; // GMF mesh file
3552 //  aResultFileName = aGenericName + "Vol.meshb"; // GMF mesh file
3553 //  aRequiredVerticesFileName    = aGenericNameRequired + ".meshb"; // GMF required vertices mesh file
3554 //  aSolFileName    = aGenericNameRequired + ".solb"; // GMF solution file
3555 //#endif
3556
3557   std::map <int, int> nodeID2nodeIndexMap;
3558   std::map<std::vector<double>, std::string> enfVerticesWithGroup;
3559   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues coordsSizeMap;
3560   TopoDS_Shape GeomShape;
3561 //   TopAbs_ShapeEnum GeomType;
3562   std::vector<double> coords;
3563   gp_Pnt aPnt;
3564   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertex* enfVertex;
3565
3566   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexList enfVertices = GHS3DPlugin_Hypothesis::GetEnforcedVertices(_hyp);
3567   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexList::const_iterator enfVerIt = enfVertices.begin();
3568
3569   for ( ; enfVerIt != enfVertices.end() ; ++enfVerIt)
3570   {
3571     enfVertex = (*enfVerIt);
3572 //     if (enfVertex->geomEntry.empty() && enfVertex->coords.size()) {
3573     if (enfVertex->coords.size()) {
3574       coordsSizeMap.insert(make_pair(enfVertex->coords,enfVertex->size));
3575       enfVerticesWithGroup.insert(make_pair(enfVertex->coords,enfVertex->groupName));
3576 //       MESSAGE("enfVerticesWithGroup.insert(make_pair(("<<enfVertex->coords[0]<<","<<enfVertex->coords[1]<<","<<enfVertex->coords[2]<<"),\""<<enfVertex->groupName<<"\"))");
3577     }
3578     else {
3579 //     if (!enfVertex->geomEntry.empty()) {
3580       GeomShape = entryToShape(enfVertex->geomEntry);
3581 //       GeomType = GeomShape.ShapeType();
3582
3583 //       if (!enfVertex->isCompound) {
3584 // //       if (GeomType == TopAbs_VERTEX) {
3585 //         coords.clear();
3586 //         aPnt = BRep_Tool::Pnt(TopoDS::Vertex(GeomShape));
3587 //         coords.push_back(aPnt.X());
3588 //         coords.push_back(aPnt.Y());
3589 //         coords.push_back(aPnt.Z());
3590 //         if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
3591 //           coordsSizeMap.insert(make_pair(coords,enfVertex->size));
3592 //           enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
3593 //         }
3594 //       }
3595 //
3596 //       // Group Management
3597 //       else {
3598 //       if (GeomType == TopAbs_COMPOUND){
3599         for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
3600           coords.clear();
3601           if (it.Value().ShapeType() == TopAbs_VERTEX){
3602             aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
3603             coords.push_back(aPnt.X());
3604             coords.push_back(aPnt.Y());
3605             coords.push_back(aPnt.Z());
3606             if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
3607               coordsSizeMap.insert(make_pair(coords,enfVertex->size));
3608               enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
3609 //               MESSAGE("enfVerticesWithGroup.insert(make_pair(("<<coords[0]<<","<<coords[1]<<","<<coords[2]<<"),\""<<enfVertex->groupName<<"\"))");
3610             }
3611           }
3612         }
3613 //       }
3614     }
3615   }
3616
3617 //   const SMDS_MeshNode* enfNode;
3618   GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap enforcedNodes = GHS3DPlugin_Hypothesis::GetEnforcedNodes(_hyp);
3619 //   GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap::const_iterator enfNodeIt = enforcedNodes.begin();
3620 //   for ( ; enfNodeIt != enforcedNodes.end() ; ++enfNodeIt)
3621 //   {
3622 //     enfNode = enfNodeIt->first;
3623 //     coords.clear();
3624 //     coords.push_back(enfNode->X());
3625 //     coords.push_back(enfNode->Y());
3626 //     coords.push_back(enfNode->Z());
3627 //     if (enfVerticesWithGro
3628 //       enfVerticesWithGroup.insert(make_pair(coords,enfNodeIt->second));
3629 //   }
3630
3631
3632   GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap enforcedEdges = GHS3DPlugin_Hypothesis::GetEnforcedEdges(_hyp);
3633   GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap enforcedTriangles = GHS3DPlugin_Hypothesis::GetEnforcedTriangles(_hyp);
3634 //   TIDSortedElemSet enforcedQuadrangles = GHS3DPlugin_Hypothesis::GetEnforcedQuadrangles(_hyp);
3635   GHS3DPlugin_Hypothesis::TID2SizeMap nodeIDToSizeMap = GHS3DPlugin_Hypothesis::GetNodeIDToSizeMap(_hyp);
3636
3637   std::string tmpStr;
3638
3639   int nbEnforcedVertices = coordsSizeMap.size();
3640   int nbEnforcedNodes = enforcedNodes.size();
3641   (nbEnforcedNodes <= 1) ? tmpStr = "node" : tmpStr = "nodes";
3642   std::cout << nbEnforcedNodes << " enforced " << tmpStr << " from hypo" << std::endl;
3643   (nbEnforcedVertices <= 1) ? tmpStr = "vertex" : tmpStr = "vertices";
3644   std::cout << nbEnforcedVertices << " enforced " << tmpStr << " from hypo" << std::endl;
3645
3646   std::vector <const SMDS_MeshNode*> aNodeByGhs3dId, anEnforcedNodeByGhs3dId;
3647   std::map<const SMDS_MeshNode*,int> aNodeToGhs3dIdMap;
3648   std::vector<std::string> aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId;
3649   {
3650     SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
3651     if ( theMesh.NbQuadrangles() > 0 )
3652     {
3653       StdMeshers_QuadToTriaAdaptor* aQuad2Trias = new StdMeshers_QuadToTriaAdaptor;
3654       aQuad2Trias->Compute( theMesh );
3655       proxyMesh.reset( aQuad2Trias );
3656     }
3657
3658     Ok = writeGMFFile(aGMFFileName.ToCString(), aRequiredVerticesFileName.ToCString(), aSolFileName.ToCString(),
3659                       *proxyMesh, &theMesh,
3660                       aNodeByGhs3dId, aNodeToGhs3dIdMap,
3661                       aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
3662                       enforcedNodes, enforcedEdges, enforcedTriangles,
3663                       enfVerticesWithGroup, coordsSizeMap);
3664   }
3665
3666   // -----------------
3667   // run ghs3d mesher
3668   // -----------------
3669
3670   TCollection_AsciiString cmd = TCollection_AsciiString((char*)GHS3DPlugin_Hypothesis::CommandToRun( _hyp, false ).c_str());
3671
3672   cmd += TCollection_AsciiString(" --in ") + aGenericName;
3673   if ( nbEnforcedVertices + nbEnforcedNodes)
3674     cmd += TCollection_AsciiString(" --required_vertices ") + aGenericNameRequired;
3675   cmd += TCollection_AsciiString(" --out ") + aResultFileName;
3676   cmd += TCollection_AsciiString(" 1>" ) + aLogFileName;  // dump into file
3677
3678   std::cout << std::endl;
3679   std::cout << "Ghs3d execution..." << std::endl;
3680   std::cout << cmd << std::endl;
3681
3682   _compute_canceled = false;
3683
3684   system( cmd.ToCString() ); // run
3685
3686   std::cout << std::endl;
3687   std::cout << "End of Ghs3d execution !" << std::endl;
3688
3689   // --------------
3690   // read a result
3691   // --------------
3692   GHS3DPlugin_Hypothesis::TSetStrings groupsToRemove = GHS3DPlugin_Hypothesis::GetGroupsToRemove(_hyp);
3693   const bool toMakeGroupsOfDomains = GHS3DPlugin_Hypothesis::GetToMakeGroupsOfDomains( _hyp );
3694
3695   Ok = readGMFFile(aResultFileName.ToCString(),
3696                    this,
3697                    theHelper, theShape, aNodeByGhs3dId, aNodeToGhs3dIdMap,
3698                    aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
3699                    groupsToRemove, toMakeGroupsOfDomains);
3700
3701   updateMeshGroups(theHelper->GetMesh(), groupsToRemove);
3702   removeEmptyGroupsOfDomains( theHelper->GetMesh() );
3703
3704   if ( Ok ) {
3705     GHS3DPlugin_Hypothesis* that = (GHS3DPlugin_Hypothesis*)this->_hyp;
3706     if (that)
3707       that->ClearGroupsToRemove();
3708   }
3709   // ---------------------
3710   // remove working files
3711   // ---------------------
3712
3713   if ( Ok )
3714   {
3715     if ( !_keepFiles )
3716       removeFile( aLogFileName );
3717
3718     if ( !toMakeGroupsOfDomains && _hyp && _hyp->GetToMakeGroupsOfDomains() )
3719       error( COMPERR_WARNING, "'toMakeGroupsOfDomains' is ignored since 'toMeshHoles' is OFF." );
3720   }
3721   else if ( OSD_File( aLogFileName ).Size() > 0 )
3722   {
3723     // get problem description from the log file
3724     _Ghs2smdsConvertor conv( aNodeByGhs3dId );
3725     storeErrorDescription( aLogFileName, conv );
3726   }
3727   else {
3728     // the log file is empty
3729     removeFile( aLogFileName );
3730     INFOS( "GHS3D Error, command '" << cmd.ToCString() << "' failed" );
3731     error(COMPERR_ALGO_FAILED, "ghs3d: command not found" );
3732   }
3733
3734   if ( !_keepFiles )
3735   {
3736     if (! Ok)
3737       if(_compute_canceled)
3738         removeFile( aLogFileName );
3739     removeFile( aGMFFileName );
3740     removeFile( aResultFileName );
3741     removeFile( aRequiredVerticesFileName );
3742     removeFile( aSolFileName );
3743   }
3744   return Ok;
3745 }
3746
3747 void GHS3DPlugin_GHS3D::CancelCompute()
3748 {
3749   _compute_canceled = true;
3750 #ifdef WNT
3751 #else
3752   std::string cmd = "ps xo pid,args | grep " + _genericName;
3753   cmd += " | grep -e \"^ *[0-9]\\+ \\+" + GHS3DPlugin_Hypothesis::GetExeName() + "\"";
3754   cmd += " | awk '{print $1}' | xargs kill -9 > /dev/null 2>&1";
3755   system( cmd.c_str() );
3756 #endif
3757 }
3758
3759 //================================================================================
3760 /*!
3761  * \brief Provide human readable text by error code reported by ghs3d
3762  */
3763 //================================================================================
3764
3765 static string translateError(const int errNum)
3766 {
3767   switch ( errNum ) {
3768   case 0:
3769     return "The surface mesh includes a face of type other than edge, "
3770       "triangle or quadrilateral. This face type is not supported.";
3771   case 1:
3772     return "Not enough memory for the face table.";
3773   case 2:
3774     return "Not enough memory.";
3775   case 3:
3776     return "Not enough memory.";
3777   case 4:
3778     return "Face is ignored.";
3779   case 5:
3780     return "End of file. Some data are missing in the file.";
3781   case 6:
3782     return "Read error on the file. There are wrong data in the file.";
3783   case 7:
3784     return "the metric file is inadequate (dimension other than 3).";
3785   case 8:
3786     return "the metric file is inadequate (values not per vertices).";
3787   case 9:
3788     return "the metric file contains more than one field.";
3789   case 10:
3790     return "the number of values in the \".bb\" (metric file) is incompatible with the expected"
3791       "value of number of mesh vertices in the \".noboite\" file.";
3792   case 12:
3793     return "Too many sub-domains.";
3794   case 13:
3795     return "the number of vertices is negative or null.";
3796   case 14:
3797     return "the number of faces is negative or null.";
3798   case 15:
3799     return "A face has a null vertex.";
3800   case 22:
3801     return "incompatible data.";
3802   case 131:
3803     return "the number of vertices is negative or null.";
3804   case 132:
3805     return "the number of vertices is negative or null (in the \".mesh\" file).";
3806   case 133:
3807     return "the number of faces is negative or null.";
3808   case 1000:
3809     return "A face appears more than once in the input surface mesh.";
3810   case 1001:
3811     return "An edge appears more than once in the input surface mesh.";
3812   case 1002:
3813     return "A face has a vertex negative or null.";
3814   case 1003:
3815     return "NOT ENOUGH MEMORY.";
3816   case 2000:
3817     return "Not enough available memory.";
3818   case 2002:
3819     return "Some initial points cannot be inserted. The surface mesh is probably very bad "
3820       "in terms of quality or the input list of points is wrong.";
3821   case 2003:
3822     return "Some vertices are too close to one another or coincident.";
3823   case 2004:
3824     return "Some vertices are too close to one another or coincident.";
3825   case 2012:
3826     return "A vertex cannot be inserted.";
3827   case 2014:
3828     return "There are at least two points considered as coincident.";
3829   case 2103:
3830     return "Some vertices are too close to one another or coincident.";
3831   case 3000:
3832     return "The surface mesh regeneration step has failed.";
3833   case 3009:
3834     return "Constrained edge cannot be enforced.";
3835   case 3019:
3836     return "Constrained face cannot be enforced.";
3837   case 3029:
3838     return "Missing faces.";
3839   case 3100:
3840     return "No guess to start the definition of the connected component(s).";
3841   case 3101:
3842     return "The surface mesh includes at least one hole. The domain is not well defined.";
3843   case 3102:
3844     return "Impossible to define a component.";
3845   case 3103:
3846     return "The surface edge intersects another surface edge.";
3847   case 3104:
3848     return "The surface edge intersects the surface face.";
3849   case 3105:
3850     return "One boundary point lies within a surface face.";
3851   case 3106:
3852     return "One surface edge intersects a surface face.";
3853   case 3107:
3854     return "One boundary point lies within a surface edge.";
3855   case 3108:
3856     return "Insufficient memory ressources detected due to a bad quality surface mesh leading "
3857       "to too many swaps.";
3858   case 3109:
3859     return "Edge is unique (i.e., bounds a hole in the surface).";
3860   case 3122:
3861     return "Presumably, the surface mesh is not compatible with the domain being processed.";
3862   case 3123:
3863     return "Too many components, too many sub-domain.";
3864   case 3209:
3865     return "The surface mesh includes at least one hole. "
3866       "Therefore there is no domain properly defined.";
3867   case 3300:
3868     return "Statistics.";
3869   case 3400:
3870     return "Statistics.";
3871   case 3500:
3872     return "Warning, it is dramatically tedious to enforce the boundary items.";
3873   case 4000:
3874     return "Not enough memory at this time, nevertheless, the program continues. "
3875       "The expected mesh will be correct but not really as large as required.";
3876   case 4002:
3877     return "see above error code, resulting quality may be poor.";
3878   case 4003:
3879     return "Not enough memory at this time, nevertheless, the program continues (warning).";
3880   case 8000:
3881     return "Unknown face type.";
3882   case 8005:
3883   case 8006:
3884     return "End of file. Some data are missing in the file.";
3885   case 9000:
3886     return "A too small volume element is detected.";
3887   case 9001:
3888     return "There exists at least a null or negative volume element.";
3889   case 9002:
3890     return "There exist null or negative volume elements.";
3891   case 9003:
3892     return "A too small volume element is detected. A face is considered being degenerated.";
3893   case 9100:
3894     return "Some element is suspected to be very bad shaped or wrong.";
3895   case 9102:
3896     return "A too bad quality face is detected. This face is considered degenerated.";
3897   case 9112:
3898     return "A too bad quality face is detected. This face is degenerated.";
3899   case 9122:
3900     return "Presumably, the surface mesh is not compatible with the domain being processed.";
3901   case 9999:
3902     return "Abnormal error occured, contact hotline.";
3903   case 23600:
3904     return "Not enough memory for the face table.";
3905   case 23601:
3906     return "The algorithm cannot run further. "
3907       "The surface mesh is probably very bad in terms of quality.";
3908   case 23602:
3909     return "Bad vertex number.";
3910   }
3911   return "";
3912 }
3913
3914 //================================================================================
3915 /*!
3916  * \brief Retrieve from a string given number of integers
3917  */
3918 //================================================================================
3919
3920 static char* getIds( char* ptr, int nbIds, vector<int>& ids )
3921 {
3922   ids.clear();
3923   ids.reserve( nbIds );
3924   while ( nbIds )
3925   {
3926     while ( !isdigit( *ptr )) ++ptr;
3927     if ( ptr[-1] == '-' ) --ptr;
3928     ids.push_back( strtol( ptr, &ptr, 10 ));
3929     --nbIds;
3930   }
3931   return ptr;
3932 }
3933
3934 //================================================================================
3935 /*!
3936  * \brief Retrieve problem description form a log file
3937  *  \retval bool - always false
3938  */
3939 //================================================================================
3940
3941 bool GHS3DPlugin_GHS3D::storeErrorDescription(const TCollection_AsciiString& logFile,
3942                                               const _Ghs2smdsConvertor &     toSmdsConvertor )
3943 {
3944   if(_compute_canceled)
3945     return error(SMESH_Comment("interruption initiated by user"));
3946   // open file
3947 #ifdef WNT
3948   int file = ::_open (logFile.ToCString(), _O_RDONLY|_O_BINARY);
3949 #else
3950   int file = ::open (logFile.ToCString(), O_RDONLY);
3951 #endif
3952   if ( file < 0 )
3953     return error( SMESH_Comment("See ") << logFile << " for problem description");
3954
3955   // get file size
3956 //   struct stat status;
3957 //   fstat(file, &status);
3958 //   size_t length = status.st_size;
3959   off_t length = lseek( file, 0, SEEK_END);
3960   lseek( file, 0, SEEK_SET);
3961
3962   // read file
3963   vector< char > buf( length );
3964   int nBytesRead = ::read (file, & buf[0], length);
3965   ::close (file);
3966   char* ptr = & buf[0];
3967   char* bufEnd = ptr + nBytesRead;
3968
3969   SMESH_Comment errDescription;
3970
3971   enum { NODE = 1, EDGE, TRIA, VOL, ID = 1 };
3972
3973   // look for errors "ERR #"
3974
3975   set<string> foundErrorStr; // to avoid reporting same error several times
3976   set<int>    elemErrorNums; // not to report different types of errors with bad elements
3977   while ( ++ptr < bufEnd )
3978   {
3979     if ( strncmp( ptr, "ERR ", 4 ) != 0 )
3980       continue;
3981
3982     list<const SMDS_MeshElement*> badElems;
3983     vector<int> nodeIds;
3984
3985     ptr += 4;
3986     char* errBeg = ptr;
3987     int   errNum = strtol(ptr, &ptr, 10);
3988     switch ( errNum ) { // we treat errors enumerated in [SALOME platform 0019316] issue
3989     case 0015:
3990       // The face number (numfac) with vertices (f 1, f 2, f 3) has a null vertex.
3991       ptr = getIds(ptr, NODE, nodeIds);
3992       ptr = getIds(ptr, TRIA, nodeIds);
3993       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3994       break;
3995     case 1000: // ERR  1000 :  1 3 2
3996       // Face (f 1, f 2, f 3) appears more than once in the input surface mesh.
3997       ptr = getIds(ptr, TRIA, nodeIds);
3998       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3999       break;
4000     case 1001:
4001       // Edge (e1, e2) appears more than once in the input surface mesh
4002       ptr = getIds(ptr, EDGE, nodeIds);
4003       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4004       break;
4005     case 1002:
4006       // Face (f 1, f 2, f 3) has a vertex negative or null
4007       ptr = getIds(ptr, TRIA, nodeIds);
4008       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4009       break;
4010     case 2004:
4011       // Vertex v1 and vertex v2 are too close to one another or coincident (warning).
4012       ptr = getIds(ptr, NODE, nodeIds);
4013       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4014       ptr = getIds(ptr, NODE, nodeIds);
4015       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4016       break;
4017     case 2012:
4018       // Vertex v1 cannot be inserted (warning).
4019       ptr = getIds(ptr, NODE, nodeIds);
4020       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4021       break;
4022     case 2014:
4023       // There are at least two points whose distance is dist, i.e., considered as coincident
4024     case 2103: // ERR  2103 :  16 WITH  3
4025       // Vertex v1 and vertex v2 are too close to one another or coincident (warning).
4026       ptr = getIds(ptr, NODE, nodeIds);
4027       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4028       ptr = getIds(ptr, NODE, nodeIds);
4029       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4030       break;
4031     case 3009:
4032       // Constrained edge (e1, e2) cannot be enforced (warning).
4033       ptr = getIds(ptr, EDGE, nodeIds);
4034       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4035       break;
4036     case 3019:
4037       // Constrained face (f 1, f 2, f 3) cannot be enforced
4038       ptr = getIds(ptr, TRIA, nodeIds);
4039       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4040       break;
4041     case 3103: // ERR  3103 :  1 2 WITH  7 3
4042       // The surface edge (e1, e2) intersects another surface edge (e3, e4)
4043       ptr = getIds(ptr, EDGE, nodeIds);
4044       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4045       ptr = getIds(ptr, EDGE, nodeIds);
4046       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4047       break;
4048     case 3104: // ERR  3104 :  9 10 WITH  1 2 3
4049       // The surface edge (e1, e2) intersects the surface face (f 1, f 2, f 3)
4050       ptr = getIds(ptr, EDGE, nodeIds);
4051       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4052       ptr = getIds(ptr, TRIA, nodeIds);
4053       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4054       break;
4055     case 3105: // ERR  3105 :  8 IN  2 3 5
4056       // One boundary point (say p1) lies within a surface face (f 1, f 2, f 3)
4057       ptr = getIds(ptr, NODE, nodeIds);
4058       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4059       ptr = getIds(ptr, TRIA, nodeIds);
4060       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4061       break;
4062     case 3106:
4063       // One surface edge (say e1, e2) intersects a surface face (f 1, f 2, f 3)
4064       ptr = getIds(ptr, EDGE, nodeIds);
4065       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4066       ptr = getIds(ptr, TRIA, nodeIds);
4067       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4068       break;
4069     case 3107: // ERR  3107 :  2 IN  4 1
4070       // One boundary point (say p1) lies within a surface edge (e1, e2) (stop).
4071       ptr = getIds(ptr, NODE, nodeIds);
4072       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4073       ptr = getIds(ptr, EDGE, nodeIds);
4074       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4075       break;
4076     case 3109: // ERR  3109 :  EDGE  5 6 UNIQUE
4077       // Edge (e1, e2) is unique (i.e., bounds a hole in the surface)
4078       ptr = getIds(ptr, EDGE, nodeIds);
4079       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4080       break;
4081     case 9000: // ERR  9000
4082       //  ELEMENT  261 WITH VERTICES :  7 396 -8 242
4083       //  VOLUME   : -1.11325045E+11 W.R.T. EPSILON   0.
4084       // A too small volume element is detected. Are reported the index of the element,
4085       // its four vertex indices, its volume and the tolerance threshold value
4086       ptr = getIds(ptr, ID, nodeIds);
4087       ptr = getIds(ptr, VOL, nodeIds);
4088       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4089       // even if all nodes found, volume it most probably invisible,
4090       // add its faces to demenstrate it anyhow
4091       {
4092         vector<int> faceNodes( nodeIds.begin(), --nodeIds.end() ); // 012
4093         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
4094         faceNodes[2] = nodeIds[3]; // 013
4095         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
4096         faceNodes[1] = nodeIds[2]; // 023
4097         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
4098         faceNodes[0] = nodeIds[1]; // 123
4099         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
4100       }
4101       break;
4102     case 9001: // ERR  9001
4103       //  %% NUMBER OF NEGATIVE VOLUME TETS  :  1
4104       //  %% THE LARGEST NEGATIVE TET        :   1.75376581E+11
4105       //  %%  NUMBER OF NULL VOLUME TETS     :  0
4106       // There exists at least a null or negative volume element
4107       break;
4108     case 9002:
4109       // There exist n null or negative volume elements
4110       break;
4111     case 9003:
4112       // A too small volume element is detected
4113       break;
4114     case 9102:
4115       // A too bad quality face is detected. This face is considered degenerated,
4116       // its index, its three vertex indices together with its quality value are reported
4117       break; // same as next
4118     case 9112: // ERR  9112
4119       //  FACE   2 WITH VERTICES :  4 2 5
4120       //  SMALL INRADIUS :   0.
4121       // A too bad quality face is detected. This face is degenerated,
4122       // its index, its three vertex indices together with its inradius are reported
4123       ptr = getIds(ptr, ID, nodeIds);
4124       ptr = getIds(ptr, TRIA, nodeIds);
4125       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
4126       // add triangle edges as it most probably has zero area and hence invisible
4127       {
4128         vector<int> edgeNodes(2);
4129         edgeNodes[0] = nodeIds[0]; edgeNodes[1] = nodeIds[1]; // 0-1
4130         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
4131         edgeNodes[1] = nodeIds[2]; // 0-2
4132         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
4133         edgeNodes[0] = nodeIds[1]; // 1-2
4134         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
4135       }
4136       break;
4137     }
4138
4139     bool isNewError = foundErrorStr.insert( string( errBeg, ptr )).second;
4140     if ( !isNewError )
4141       continue; // not to report same error several times
4142
4143 //     const SMDS_MeshElement* nullElem = 0;
4144 //     bool allElemsOk = ( find( badElems.begin(), badElems.end(), nullElem) == badElems.end());
4145
4146 //     if ( allElemsOk && !badElems.empty() && !elemErrorNums.empty() ) {
4147 //       bool oneMoreErrorType = elemErrorNums.insert( errNum ).second;
4148 //       if ( oneMoreErrorType )
4149 //         continue; // not to report different types of errors with bad elements
4150 //     }
4151
4152     // store bad elements
4153     //if ( allElemsOk ) {
4154       list<const SMDS_MeshElement*>::iterator elem = badElems.begin();
4155       for ( ; elem != badElems.end(); ++elem )
4156         addBadInputElement( *elem );
4157       //}
4158
4159     // make error text
4160     string text = translateError( errNum );
4161     if ( errDescription.find( text ) == text.npos ) {
4162       if ( !errDescription.empty() )
4163         errDescription << "\n";
4164       errDescription << text;
4165     }
4166
4167   } // end while
4168
4169   if ( errDescription.empty() ) { // no errors found
4170     char msgLic1[] = "connection to server failed";
4171     char msgLic2[] = " Dlim ";
4172     if ( search( &buf[0], bufEnd, msgLic1, msgLic1 + strlen(msgLic1)) != bufEnd ||
4173          search( &buf[0], bufEnd, msgLic2, msgLic2 + strlen(msgLic2)) != bufEnd )
4174       errDescription << "Licence problems.";
4175     else
4176     {
4177       char msg2[] = "SEGMENTATION FAULT";
4178       if ( search( &buf[0], bufEnd, msg2, msg2 + strlen(msg2)) != bufEnd )
4179         errDescription << "ghs3d: SEGMENTATION FAULT. ";
4180     }
4181   }
4182
4183   if ( errDescription.empty() )
4184     errDescription << "See " << logFile << " for problem description";
4185   else
4186     errDescription << "\nSee " << logFile << " for more information";
4187
4188   return error( errDescription );
4189 }
4190
4191 //================================================================================
4192 /*!
4193  * \brief Creates _Ghs2smdsConvertor
4194  */
4195 //================================================================================
4196
4197 _Ghs2smdsConvertor::_Ghs2smdsConvertor( const map <int,const SMDS_MeshNode*> & ghs2NodeMap)
4198   :_ghs2NodeMap( & ghs2NodeMap ), _nodeByGhsId( 0 )
4199 {
4200 }
4201
4202 //================================================================================
4203 /*!
4204  * \brief Creates _Ghs2smdsConvertor
4205  */
4206 //================================================================================
4207
4208 _Ghs2smdsConvertor::_Ghs2smdsConvertor( const vector <const SMDS_MeshNode*> &  nodeByGhsId)
4209   : _ghs2NodeMap( 0 ), _nodeByGhsId( &nodeByGhsId )
4210 {
4211 }
4212
4213 //================================================================================
4214 /*!
4215  * \brief Return SMDS element by ids of GHS3D nodes
4216  */
4217 //================================================================================
4218
4219 const SMDS_MeshElement* _Ghs2smdsConvertor::getElement(const vector<int>& ghsNodes) const
4220 {
4221   size_t nbNodes = ghsNodes.size();
4222   vector<const SMDS_MeshNode*> nodes( nbNodes, 0 );
4223   for ( size_t i = 0; i < nbNodes; ++i ) {
4224     int ghsNode = ghsNodes[ i ];
4225     if ( _ghs2NodeMap ) {
4226       map <int,const SMDS_MeshNode*>::const_iterator in = _ghs2NodeMap->find( ghsNode);
4227       if ( in == _ghs2NodeMap->end() )
4228         return 0;
4229       nodes[ i ] = in->second;
4230     }
4231     else {
4232       if ( ghsNode < 1 || ghsNode > _nodeByGhsId->size() )
4233         return 0;
4234       nodes[ i ] = (*_nodeByGhsId)[ ghsNode-1 ];
4235     }
4236   }
4237   if ( nbNodes == 1 )
4238     return nodes[0];
4239
4240   if ( nbNodes == 2 ) {
4241     const SMDS_MeshElement* edge= SMDS_Mesh::FindEdge( nodes[0], nodes[1] );
4242     if ( !edge )
4243       edge = new SMDS_LinearEdge( nodes[0], nodes[1] );
4244     return edge;
4245   }
4246   if ( nbNodes == 3 ) {
4247     const SMDS_MeshElement* face = SMDS_Mesh::FindFace( nodes );
4248     if ( !face )
4249       face = new SMDS_FaceOfNodes( nodes[0], nodes[1], nodes[2] );
4250     return face;
4251   }
4252   if ( nbNodes == 4 )
4253     return new SMDS_VolumeOfNodes( nodes[0], nodes[1], nodes[2], nodes[3] );
4254
4255   return 0;
4256 }
4257
4258
4259 //=============================================================================
4260 /*!
4261  *
4262  */
4263 //=============================================================================
4264 bool GHS3DPlugin_GHS3D::Evaluate(SMESH_Mesh& aMesh,
4265                                  const TopoDS_Shape& aShape,
4266                                  MapShapeNbElems& aResMap)
4267 {
4268   int nbtri = 0, nbqua = 0;
4269   double fullArea = 0.0;
4270   for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
4271     TopoDS_Face F = TopoDS::Face( exp.Current() );
4272     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
4273     MapShapeNbElemsItr anIt = aResMap.find(sm);
4274     if( anIt==aResMap.end() ) {
4275       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
4276       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
4277                                             "Submesh can not be evaluated",this));
4278       return false;
4279     }
4280     std::vector<int> aVec = (*anIt).second;
4281     nbtri += Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
4282     nbqua += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
4283     GProp_GProps G;
4284     BRepGProp::SurfaceProperties(F,G);
4285     double anArea = G.Mass();
4286     fullArea += anArea;
4287   }
4288
4289   // collect info from edges
4290   int nb0d_e = 0, nb1d_e = 0;
4291   bool IsQuadratic = false;
4292   bool IsFirst = true;
4293   TopTools_MapOfShape tmpMap;
4294   for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
4295     TopoDS_Edge E = TopoDS::Edge(exp.Current());
4296     if( tmpMap.Contains(E) )
4297       continue;
4298     tmpMap.Add(E);
4299     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
4300     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
4301     std::vector<int> aVec = (*anIt).second;
4302     nb0d_e += aVec[SMDSEntity_Node];
4303     nb1d_e += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
4304     if(IsFirst) {
4305       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
4306       IsFirst = false;
4307     }
4308   }
4309   tmpMap.Clear();
4310
4311   double ELen = sqrt(2.* ( fullArea/(nbtri+nbqua*2) ) / sqrt(3.0) );
4312
4313   GProp_GProps G;
4314   BRepGProp::VolumeProperties(aShape,G);
4315   double aVolume = G.Mass();
4316   double tetrVol = 0.1179*ELen*ELen*ELen;
4317   double CoeffQuality = 0.9;
4318   int nbVols = int(aVolume/tetrVol/CoeffQuality);
4319   int nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
4320   int nb1d_in = (int) ( nbVols*6 - nb1d_e - nb1d_f ) / 5;
4321   std::vector<int> aVec(SMDSEntity_Last);
4322   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
4323   if( IsQuadratic ) {
4324     aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
4325     aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
4326     aVec[SMDSEntity_Quad_Pyramid] = nbqua;
4327   }
4328   else {
4329     aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
4330     aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
4331     aVec[SMDSEntity_Pyramid] = nbqua;
4332   }
4333   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
4334   aResMap.insert(std::make_pair(sm,aVec));
4335
4336   return true;
4337 }
4338
4339 bool GHS3DPlugin_GHS3D::importGMFMesh(const char* theGMFFileName, SMESH_Mesh& theMesh)
4340 {
4341   SMESH_MesherHelper* helper  = new SMESH_MesherHelper(theMesh );
4342 //   TopoDS_Shape theShape = theMesh.GetShapeToMesh();
4343   std::vector <const SMDS_MeshNode*> dummyNodeVector;
4344   std::map<const SMDS_MeshNode*,int> dummyNodeMap;
4345   std::map<std::vector<double>, std::string> dummyEnfVertGroup;
4346   std::vector<std::string> dummyElemGroup;
4347   std::set<std::string> dummyGroupsToRemove;
4348
4349   bool ok = readGMFFile(theGMFFileName,
4350                         this,
4351                         helper, theMesh.GetShapeToMesh(), dummyNodeVector, dummyNodeMap, dummyElemGroup, dummyElemGroup, dummyElemGroup, dummyGroupsToRemove);
4352   theMesh.GetMeshDS()->Modified();
4353   return ok;
4354 }
4355
4356 namespace
4357 {
4358   //================================================================================
4359   /*!
4360    * \brief Sub-mesh event listener setting enforced elements as soon as an enforced
4361    *        mesh is loaded
4362    */
4363   struct _EnforcedMeshRestorer : public SMESH_subMeshEventListener
4364   {
4365     _EnforcedMeshRestorer():
4366       SMESH_subMeshEventListener( /*isDeletable = */true, Name() )
4367     {}
4368
4369     //================================================================================
4370     /*!
4371      * \brief Returns an ID of listener
4372      */
4373     static const char* Name() { return "GHS3DPlugin_GHS3D::_EnforcedMeshRestorer"; }
4374
4375     //================================================================================
4376     /*!
4377      * \brief Treat events of the subMesh
4378      */
4379     void ProcessEvent(const int                       event,
4380                       const int                       eventType,
4381                       SMESH_subMesh*                  subMesh,
4382                       SMESH_subMeshEventListenerData* data,
4383                       const SMESH_Hypothesis*         hyp)
4384     {
4385       if ( SMESH_subMesh::SUBMESH_LOADED == event &&
4386            SMESH_subMesh::COMPUTE_EVENT  == eventType &&
4387            data &&
4388            !data->mySubMeshes.empty() )
4389       {
4390         // An enforced mesh (subMesh->_father) has been loaded from hdf file
4391         if ( GHS3DPlugin_Hypothesis* hyp = GetGHSHypothesis( data->mySubMeshes.front() ))
4392           hyp->RestoreEnfElemsByMeshes();
4393       }
4394     }
4395     //================================================================================
4396     /*!
4397      * \brief Returns GHS3DPlugin_Hypothesis used to compute a subMesh
4398      */
4399     static GHS3DPlugin_Hypothesis* GetGHSHypothesis( SMESH_subMesh* subMesh )
4400     {
4401       SMESH_HypoFilter ghsHypFilter( SMESH_HypoFilter::HasName( "GHS3D_Parameters" ));
4402       return (GHS3DPlugin_Hypothesis* )
4403         subMesh->GetFather()->GetHypothesis( subMesh->GetSubShape(),
4404                                              ghsHypFilter,
4405                                              /*visitAncestors=*/true);
4406     }
4407   };
4408
4409   //================================================================================
4410   /*!
4411    * \brief Sub-mesh event listener removing empty groups created due to "To make
4412    *        groups of domains".
4413    */
4414   struct _GroupsOfDomainsRemover : public SMESH_subMeshEventListener
4415   {
4416     _GroupsOfDomainsRemover():
4417       SMESH_subMeshEventListener( /*isDeletable = */true,
4418                                   "GHS3DPlugin_GHS3D::_GroupsOfDomainsRemover" ) {}
4419     /*!
4420      * \brief Treat events of the subMesh
4421      */
4422     void ProcessEvent(const int                       event,
4423                       const int                       eventType,
4424                       SMESH_subMesh*                  subMesh,
4425                       SMESH_subMeshEventListenerData* data,
4426                       const SMESH_Hypothesis*         hyp)
4427     {
4428       if (SMESH_subMesh::ALGO_EVENT == eventType &&
4429           !subMesh->GetAlgo() )
4430       {
4431         removeEmptyGroupsOfDomains( subMesh->GetFather(), /*notEmptyAsWell=*/true );
4432       }
4433     }
4434   };
4435 }
4436
4437 //================================================================================
4438 /*!
4439  * \brief Set an event listener to set enforced elements as soon as an enforced
4440  *        mesh is loaded
4441  */
4442 //================================================================================
4443
4444 void GHS3DPlugin_GHS3D::SubmeshRestored(SMESH_subMesh* subMesh)
4445 {
4446   if ( GHS3DPlugin_Hypothesis* hyp = _EnforcedMeshRestorer::GetGHSHypothesis( subMesh ))
4447   {
4448     GHS3DPlugin_Hypothesis::TGHS3DEnforcedMeshList enfMeshes = hyp->_GetEnforcedMeshes();
4449     GHS3DPlugin_Hypothesis::TGHS3DEnforcedMeshList::iterator it = enfMeshes.begin();
4450     for(;it != enfMeshes.end();++it) {
4451       GHS3DPlugin_Hypothesis::TGHS3DEnforcedMesh* enfMesh = *it;
4452       if ( SMESH_Mesh* mesh = GetMeshByPersistentID( enfMesh->persistID ))
4453       {
4454         SMESH_subMesh* smToListen = mesh->GetSubMesh( mesh->GetShapeToMesh() );
4455         // a listener set to smToListen will care of hypothesis stored in SMESH_EventListenerData
4456         subMesh->SetEventListener( new _EnforcedMeshRestorer(),
4457                                    SMESH_subMeshEventListenerData::MakeData( subMesh ),
4458                                    smToListen);
4459       }
4460     }
4461   }
4462 }
4463
4464 //================================================================================
4465 /*!
4466  * \brief Sets an event listener removing empty groups created due to "To make
4467  *        groups of domains".
4468  * \param subMesh - submesh where algo is set
4469  *
4470  * This method is called when a submesh gets HYP_OK algo_state.
4471  * After being set, event listener is notified on each event of a submesh.
4472  */
4473 //================================================================================
4474
4475 void GHS3DPlugin_GHS3D::SetEventListener(SMESH_subMesh* subMesh)
4476 {
4477   subMesh->SetEventListener( new _GroupsOfDomainsRemover(), 0, subMesh );
4478 }