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