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