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