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