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