Salome HOME
Patch for MacOS (from SALOME forum)
[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
45 #include <BRepAdaptor_Surface.hxx>
46 #include <BRepBndLib.hxx>
47 #include <BRepBuilderAPI_MakeVertex.hxx>
48 #include <BRepClass3d.hxx>
49 #include <BRepClass3d_SolidClassifier.hxx>
50 #include <BRepExtrema_DistShapeShape.hxx>
51 #include <BRepGProp.hxx>
52 #include <BRepTools.hxx>
53 #include <BRep_Tool.hxx>
54 #include <Bnd_Box.hxx>
55 #include <GProp_GProps.hxx>
56 #include <GeomAPI_ProjectPointOnSurf.hxx>
57 #include <Precision.hxx>
58 #include <Standard_ErrorHandler.hxx>
59 #include <Standard_Failure.hxx>
60 #include <Standard_ProgramError.hxx>
61 #include <TopExp.hxx>
62 #include <TopExp_Explorer.hxx>
63 #include <TopTools_IndexedMapOfShape.hxx>
64 #include <TopTools_ListIteratorOfListOfShape.hxx>
65 #include <TopTools_MapOfShape.hxx>
66 #include <TopoDS.hxx>
67 #include <TopoDS_Shell.hxx>
68 #include <TopoDS_Solid.hxx>
69
70 #include <Basics_Utils.hxx>
71 #include <utilities.h>
72
73 #include <algorithm>
74
75 #define castToNode(n) static_cast<const SMDS_MeshNode *>( n );
76
77 #ifndef GMFVERSION
78 #define GMFVERSION GmfDouble
79 #endif
80 #define GMFDIMENSION 3
81
82 #define HOLE_ID -1
83
84 typedef const std::list<const SMDS_MeshFace*> TTriaList;
85
86 static const char theDomainGroupNamePrefix[] = "Domain_";
87
88 static void removeFile( const std::string& fileName )
89 {
90   try {
91     SMESH_File( fileName ).remove();
92   }
93   catch ( ... ) {
94     MESSAGE("Can't remove file: " << fileName << " ; file does not exist or permission denied");
95   }
96 }
97
98 //=============================================================================
99 /*!
100  *  
101  */
102 //=============================================================================
103
104 HYBRIDPlugin_HYBRID::HYBRIDPlugin_HYBRID(int hypId, int studyId, SMESH_Gen* gen)
105   : SMESH_3D_Algo(hypId, studyId, gen)
106 {
107   _name = Name();
108   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
109   _onlyUnaryInput = true; // Compute() will be called on each solid
110   _iShape=0;
111   _nbShape=0;
112   _compatibleHypothesis.push_back( HYBRIDPlugin_Hypothesis::GetHypType());
113   _requireShape = false; // can work without shape_studyId
114
115   smeshGen_i = SMESH_Gen_i::GetSMESHGen();
116   CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
117   SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
118
119   myStudy = NULL;
120   myStudy = aStudyMgr->GetStudyByID(_studyId);
121   
122   _computeCanceled = false;
123 }
124
125 //=============================================================================
126 /*!
127  *  
128  */
129 //=============================================================================
130
131 HYBRIDPlugin_HYBRID::~HYBRIDPlugin_HYBRID()
132 {
133 }
134
135 //=============================================================================
136 /*!
137  *  
138  */
139 //=============================================================================
140
141 bool HYBRIDPlugin_HYBRID::CheckHypothesis ( SMESH_Mesh&         aMesh,
142                                           const TopoDS_Shape& aShape,
143                                           Hypothesis_Status&  aStatus )
144 {
145   aStatus = SMESH_Hypothesis::HYP_OK;
146
147   _hyp = 0;
148   _keepFiles = false;
149   _removeLogOnSuccess = true;
150   _logInStandardOutput = false;
151
152   const std::list <const SMESHDS_Hypothesis * >& hyps =
153     GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
154   std::list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
155   for ( ; h != hyps.end(); ++h )
156   {
157     if ( !_hyp )
158       _hyp = dynamic_cast< const HYBRIDPlugin_Hypothesis*> ( *h );
159   }
160   if ( _hyp )
161   {
162     _keepFiles = _hyp->GetKeepFiles();
163     _removeLogOnSuccess = _hyp->GetRemoveLogOnSuccess();
164     _logInStandardOutput = _hyp->GetStandardOutputLog();
165   }
166
167   return true;
168 }
169
170
171 //=======================================================================
172 //function : entryToShape
173 //purpose  : 
174 //=======================================================================
175
176 TopoDS_Shape HYBRIDPlugin_HYBRID::entryToShape(std::string entry)
177 {
178   if ( myStudy->_is_nil() )
179     throw SALOME_Exception("MG-HYBRID plugin can't work w/o publishing in the study");
180   GEOM::GEOM_Object_var aGeomObj;
181   TopoDS_Shape S = TopoDS_Shape();
182   SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
183   if (!aSObj->_is_nil() ) {
184     CORBA::Object_var obj = aSObj->GetObject();
185     aGeomObj = GEOM::GEOM_Object::_narrow(obj);
186     aSObj->UnRegister();
187   }
188   if ( !aGeomObj->_is_nil() )
189     S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
190   return S;
191 }
192
193 //=======================================================================
194 //function : addElemInMeshGroup
195 //purpose  : Update or create groups in mesh
196 //=======================================================================
197
198 static void addElemInMeshGroup(SMESH_Mesh*             theMesh,
199                                const SMDS_MeshElement* anElem,
200                                std::string&            groupName,
201                                std::set<std::string>&  groupsToRemove)
202 {
203   if ( !anElem ) return; // issue 0021776
204
205   bool groupDone = false;
206   SMESH_Mesh::GroupIteratorPtr grIt = theMesh->GetGroups();
207   while (grIt->more()) {
208     SMESH_Group * group = grIt->next();
209     if ( !group ) continue;
210     SMESHDS_GroupBase* groupDS = group->GetGroupDS();
211     if ( !groupDS ) continue;
212     if ( groupDS->GetType()==anElem->GetType() &&groupName.compare(group->GetName())==0) {
213       SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
214       aGroupDS->SMDSGroup().Add(anElem);
215       groupDone = true;
216       break;
217     }
218   }
219   
220   if (!groupDone)
221   {
222     int groupId;
223     SMESH_Group* aGroup = theMesh->AddGroup(anElem->GetType(), groupName.c_str(), groupId);
224     aGroup->SetName( groupName.c_str() );
225     SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
226     aGroupDS->SMDSGroup().Add(anElem);
227     groupDone = true;
228   }
229   if (!groupDone)
230     throw SALOME_Exception(LOCALIZED("A given element was not added to a group"));
231 }
232
233
234 //=======================================================================
235 //function : updateMeshGroups
236 //purpose  : Update or create groups in mesh
237 //=======================================================================
238
239 static void updateMeshGroups(SMESH_Mesh* theMesh, std::set<std::string> groupsToRemove)
240 {
241   SMESH_Mesh::GroupIteratorPtr grIt = theMesh->GetGroups();
242   while (grIt->more()) {
243     SMESH_Group * group = grIt->next();
244     if ( !group ) continue;
245     SMESHDS_GroupBase* groupDS = group->GetGroupDS();
246     if ( !groupDS ) continue;
247     std::string currentGroupName = (std::string)group->GetName();
248     if (groupDS->IsEmpty() && groupsToRemove.find(currentGroupName) != groupsToRemove.end()) {
249       // Previous group created by enforced elements
250       theMesh->RemoveGroup(groupDS->GetID());
251     }
252   }
253 }
254
255 //=======================================================================
256 //function : removeEmptyGroupsOfDomains
257 //purpose  : remove empty groups named "Domain_nb" created due to
258 //           "To make groups of domains" option.
259 //=======================================================================
260
261 static void removeEmptyGroupsOfDomains(SMESH_Mesh* mesh,
262                                        bool        notEmptyAsWell = false)
263 {
264   const char* refName = theDomainGroupNamePrefix;
265   const size_t refLen = strlen( theDomainGroupNamePrefix );
266
267   std::list<int> groupIDs = mesh->GetGroupIds();
268   std::list<int>::const_iterator id = groupIDs.begin();
269   for ( ; id != groupIDs.end(); ++id )
270   {
271     SMESH_Group* group = mesh->GetGroup( *id );
272     if ( !group || ( !group->GetGroupDS()->IsEmpty() && !notEmptyAsWell ))
273       continue;
274     const char* name = group->GetName();
275     char* end;
276     // check the name
277     if ( strncmp( name, refName, refLen ) == 0 && // starts from refName;
278          isdigit( *( name + refLen )) &&          // refName is followed by a digit;
279          strtol( name + refLen, &end, 10) >= 0 && // there are only digits ...
280          *end == '\0')                            // ... till a string end.
281     {
282       mesh->RemoveGroup( *id );
283     }
284   }
285 }
286
287 //================================================================================
288 /*!
289  * \brief Create the groups corresponding to domains
290  */
291 //================================================================================
292
293 static void makeDomainGroups( std::vector< std::vector< const SMDS_MeshElement* > >& elemsOfDomain,
294                               SMESH_MesherHelper*                                    theHelper)
295 {
296   for ( size_t iDomain = 0; iDomain < elemsOfDomain.size(); ++iDomain )
297   {
298     std::vector< const SMDS_MeshElement* > & elems = elemsOfDomain[ iDomain ];
299     if ( elems.empty() ) continue;
300
301     // find existing groups
302     std::vector< SMESH_Group* > groupOfType( SMDSAbs_NbElementTypes, (SMESH_Group*)NULL );
303     const std::string domainName = ( SMESH_Comment( theDomainGroupNamePrefix ) << iDomain );
304     SMESH_Mesh::GroupIteratorPtr groupIt = theHelper->GetMesh()->GetGroups();
305     while ( groupIt->more() )
306     {
307       SMESH_Group* group = groupIt->next();
308       if ( domainName == group->GetName() &&
309            dynamic_cast< SMESHDS_Group* >( group->GetGroupDS()) )
310         groupOfType[ group->GetGroupDS()->GetType() ] = group;
311     }
312     // create and fill the groups
313     size_t iElem = 0;
314     int groupID;
315     do
316     {
317       SMESH_Group* group = groupOfType[ elems[ iElem ]->GetType() ];
318       if ( !group )
319         group = theHelper->GetMesh()->AddGroup( elems[ iElem ]->GetType(),
320                                                 domainName.c_str(), groupID );
321       SMDS_MeshGroup& groupDS =
322         static_cast< SMESHDS_Group* >( group->GetGroupDS() )->SMDSGroup();
323
324       while ( iElem < elems.size() && groupDS.Add( elems[iElem] ))
325         ++iElem;
326
327     } while ( iElem < elems.size() );
328   }
329 }
330
331 //=======================================================================
332 //function : readGMFFile
333 //purpose  : read GMF file w/o geometry associated to mesh
334 //=======================================================================
335
336 static bool readGMFFile(MG_HYBRID_API*                          MGOutput,
337                         const char*                             theFile,
338                         HYBRIDPlugin_HYBRID*                    theAlgo,
339                         SMESH_MesherHelper*                     theHelper,
340                         std::vector <const SMDS_MeshNode*> &    theNodeByHybridId,
341                         std::vector <const SMDS_MeshElement*> & theFaceByHybridId,
342                         std::map<const SMDS_MeshNode*,int> &    theNodeToHybridIdMap,
343                         std::vector<std::string> &              aNodeGroupByHybridId,
344                         std::vector<std::string> &              anEdgeGroupByHybridId,
345                         std::vector<std::string> &              aFaceGroupByHybridId,
346                         std::set<std::string> &                 groupsToRemove,
347                         bool                                    toMakeGroupsOfDomains=false,
348                         bool                                    toMeshHoles=true)
349 {
350   std::string tmpStr;
351   SMESHDS_Mesh* theMeshDS = theHelper->GetMeshDS();
352   const bool hasGeom = ( theHelper->GetMesh()->HasShapeToMesh() );
353
354   int nbInitialNodes = theNodeByHybridId.size();
355   int nbMeshNodes = theMeshDS->NbNodes();
356   
357   const bool isQuadMesh = 
358     theHelper->GetMesh()->NbEdges( ORDER_QUADRATIC ) ||
359     theHelper->GetMesh()->NbFaces( ORDER_QUADRATIC ) ||
360     theHelper->GetMesh()->NbVolumes( ORDER_QUADRATIC );
361     
362 #ifdef _DEBUG_
363   std::cout << "theNodeByHybridId.size(): " << nbInitialNodes << std::endl;
364   std::cout << "theHelper->GetMesh()->NbNodes(): " << nbMeshNodes << std::endl;
365   std::cout << "isQuadMesh: " << isQuadMesh << std::endl;
366 #endif
367   
368   // ---------------------------------
369   // Read generated elements and nodes
370   // ---------------------------------
371
372   int nbElem = 0, nbRef = 0;
373   int aGMFNodeID = 0;
374   std::vector< const SMDS_MeshNode* > GMFNode;
375 #ifdef _DEBUG_
376   std::map<int, std::set<int> > subdomainId2tetraId;
377 #endif
378   std::map <GmfKwdCod,int> tabRef;
379   const bool force3d = !hasGeom;
380   const int  noID    = 0;
381
382   tabRef[GmfVertices]       = 3; // for new nodes and enforced nodes
383   tabRef[GmfCorners]        = 1;
384   tabRef[GmfEdges]          = 2; // for enforced edges
385   tabRef[GmfRidges]         = 1;
386   tabRef[GmfTriangles]      = 3; // for enforced faces
387   tabRef[GmfQuadrilaterals] = 4;
388   tabRef[GmfTetrahedra]     = 4; // for new tetras
389   tabRef[GmfPyramids]       = 5; // for new pyramids
390   tabRef[GmfPrisms]         = 6; // for new prisms
391   tabRef[GmfHexahedra]      = 8;
392
393   int ver, dim;
394   int InpMsh = MGOutput->GmfOpenMesh(theFile, GmfRead, &ver, &dim);
395   if (!InpMsh)
396     return false;
397
398   // Hybrid is not multi-domain => We can't (and don't need to) read ids of domains in ouput file like in GHS3DPlugin
399   // We just need to get the id of the one and only solid
400   int solidID = 1;
401   if ( hasGeom )
402   {
403     if ( theHelper->GetSubShape().ShapeType() == TopAbs_SOLID )
404       solidID = theHelper->GetSubShapeID();
405     else
406       solidID = theMeshDS->ShapeToIndex
407         ( TopExp_Explorer( theHelper->GetSubShape(), TopAbs_SOLID ).Current() );
408   }
409
410   // Issue 0020682. Avoid creating nodes and tetras at place where
411   // volumic elements already exist
412   SMESH_ElementSearcher* elemSearcher = 0;
413   std::vector< const SMDS_MeshElement* > foundVolumes;
414   if ( !hasGeom && theHelper->GetMesh()->NbVolumes() > 0 )
415     elemSearcher = SMESH_MeshAlgos::GetElementSearcher( *theMeshDS );
416   SMESHUtils::Deleter< SMESH_ElementSearcher > elemSearcherDeleter( elemSearcher );
417
418   // IMP 0022172: [CEA 790] create the groups corresponding to domains
419   std::vector< std::vector< const SMDS_MeshElement* > > elemsOfDomain;
420
421   int nbVertices = MGOutput->GmfStatKwd(InpMsh, GmfVertices) - nbInitialNodes;
422   if ( nbVertices < 0 )
423     return false;
424   GMFNode.resize( nbVertices + 1 );
425
426   std::map <GmfKwdCod,int>::const_iterator it = tabRef.begin();
427   for ( ; it != tabRef.end() ; ++it)
428   {
429     if(theAlgo->computeCanceled()) {
430       MGOutput->GmfCloseMesh(InpMsh);
431       return false;
432     }
433     int dummy;
434     GmfKwdCod token = it->first;
435     nbRef           = it->second;
436
437     nbElem = MGOutput->GmfStatKwd(InpMsh, token);
438     if (nbElem > 0) {
439       MGOutput->GmfGotoKwd(InpMsh, token);
440       std::cout << "Read " << nbElem;
441     }
442     else
443       continue;
444
445     std::vector<int> id (nbElem*tabRef[token]); // node ids
446     std::vector<int> domainID( nbElem ); // domain
447
448     if (token == GmfVertices) {
449       (nbElem <= 1) ? tmpStr = " vertex" : tmpStr = " vertices";
450       
451       int aGMFID;
452       float VerTab_f[3];
453       double x, y, z;
454       const SMDS_MeshNode * aGMFNode;
455
456       for ( int iElem = 0; iElem < nbElem; iElem++ ) {
457         if(theAlgo->computeCanceled()) {
458           MGOutput->GmfCloseMesh(InpMsh);
459           return false;
460         }
461         if (ver == GmfFloat) {
462           MGOutput->GmfGetLin(InpMsh, token, &VerTab_f[0], &VerTab_f[1], &VerTab_f[2], &dummy);
463           x = VerTab_f[0];
464           y = VerTab_f[1];
465           z = VerTab_f[2];
466         }
467         else {
468           MGOutput->GmfGetLin(InpMsh, token, &x, &y, &z, &dummy);
469         }
470         if (iElem >= nbInitialNodes) {
471           if ( elemSearcher &&
472                 elemSearcher->FindElementsByPoint( gp_Pnt(x,y,z), SMDSAbs_Volume, foundVolumes))
473             aGMFNode = 0;
474           else
475             aGMFNode = theHelper->AddNode(x, y, z);
476           
477           aGMFID = iElem -nbInitialNodes +1;
478           GMFNode[ aGMFID ] = aGMFNode;
479           if (aGMFID-1 < (int)aNodeGroupByHybridId.size() && !aNodeGroupByHybridId.at(aGMFID-1).empty())
480             addElemInMeshGroup(theHelper->GetMesh(), aGMFNode, aNodeGroupByHybridId.at(aGMFID-1), groupsToRemove);
481         }
482       }
483     }
484     else if (token == GmfCorners && nbElem > 0) {
485       (nbElem <= 1) ? tmpStr = " corner" : tmpStr = " corners";
486       for ( int iElem = 0; iElem < nbElem; iElem++ )
487         MGOutput->GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]]);
488     }
489     else if (token == GmfRidges && nbElem > 0) {
490       (nbElem <= 1) ? tmpStr = " ridge" : tmpStr = " ridges";
491       for ( int iElem = 0; iElem < nbElem; iElem++ )
492         MGOutput->GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]]);
493     }
494     else if (token == GmfEdges && nbElem > 0) {
495       (nbElem <= 1) ? tmpStr = " edge" : tmpStr = " edges";
496       for ( int iElem = 0; iElem < nbElem; iElem++ )
497         MGOutput->GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &domainID[iElem]);
498     }
499     else if (token == GmfTriangles && nbElem > 0) {
500       (nbElem <= 1) ? tmpStr = " triangle" : tmpStr = " triangles";
501       for ( int iElem = 0; iElem < nbElem; iElem++ )
502         MGOutput->GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &domainID[iElem]);
503     }
504     else if (token == GmfQuadrilaterals && nbElem > 0) {
505       (nbElem <= 1) ? tmpStr = " Quadrilateral" : tmpStr = " Quadrilaterals";
506       for ( int iElem = 0; iElem < nbElem; iElem++ )
507         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]);
508     }
509     else if (token == GmfTetrahedra && nbElem > 0) {
510       (nbElem <= 1) ? tmpStr = " Tetrahedron" : tmpStr = " Tetrahedra";
511       for ( int iElem = 0; iElem < nbElem; iElem++ ) {
512         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]);
513 #ifdef _DEBUG_
514         subdomainId2tetraId[dummy].insert(iElem+1);
515 #endif
516       }
517     }
518     else if (token == GmfPyramids && nbElem > 0) {
519       (nbElem <= 1) ? tmpStr = " Pyramid" : tmpStr = " Pyramids";
520       for ( int iElem = 0; iElem < nbElem; iElem++ )
521         MGOutput->GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3],
522                   &id[iElem*tabRef[token]+4], &domainID[iElem]);
523     }
524     else if (token == GmfPrisms && nbElem > 0) {
525       (nbElem <= 1) ? tmpStr = " Prism" : tmpStr = " Prisms";
526       for ( int iElem = 0; iElem < nbElem; iElem++ )
527         MGOutput->GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3],
528                   &id[iElem*tabRef[token]+4], &id[iElem*tabRef[token]+5], &domainID[iElem]);
529     }
530     else if (token == GmfHexahedra && nbElem > 0) {
531       (nbElem <= 1) ? tmpStr = " Hexahedron" : tmpStr = " Hexahedra";
532       for ( int iElem = 0; iElem < nbElem; iElem++ )
533         MGOutput->GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3],
534                   &id[iElem*tabRef[token]+4], &id[iElem*tabRef[token]+5], &id[iElem*tabRef[token]+6], &id[iElem*tabRef[token]+7], &domainID[iElem]);
535     }
536     std::cout << tmpStr << std::endl;
537     //std::cout << std::endl;
538
539     switch (token) {
540     case GmfCorners:
541     case GmfRidges:
542     case GmfEdges:
543     case GmfTriangles:
544     case GmfQuadrilaterals:
545     case GmfTetrahedra:
546     case GmfPyramids:
547     case GmfPrisms:
548     case GmfHexahedra:
549     {
550       std::vector< const SMDS_MeshNode* > node( nbRef );
551       std::vector< int >          nodeID( nbRef );
552       std::vector< SMDS_MeshNode* > enfNode( nbRef );
553       const SMDS_MeshElement* aCreatedElem;
554
555       for ( int iElem = 0; iElem < nbElem; iElem++ )
556       {
557         if(theAlgo->computeCanceled()) {
558           MGOutput->GmfCloseMesh(InpMsh);
559           return false;
560         }
561         // Check if elem is already in input mesh. If yes => skip
562         bool fullyCreatedElement = false; // if at least one of the nodes was created
563         for ( int iRef = 0; iRef < nbRef; iRef++ )
564         {
565           aGMFNodeID = id[iElem*tabRef[token]+iRef]; // read nbRef aGMFNodeID
566           if (aGMFNodeID <= nbInitialNodes) // input nodes
567           {
568             aGMFNodeID--;
569             node[ iRef ] = theNodeByHybridId[aGMFNodeID];
570           }
571           else
572           {
573             fullyCreatedElement = true;
574             aGMFNodeID -= nbInitialNodes;
575             nodeID[ iRef ] = aGMFNodeID ;
576             node  [ iRef ] = GMFNode[ aGMFNodeID ];
577           }
578         }
579         aCreatedElem = 0;
580         switch (token)
581         {
582         case GmfEdges:
583           if (fullyCreatedElement) {
584             aCreatedElem = theHelper->AddEdge( node[0], node[1], noID, force3d );
585             if (anEdgeGroupByHybridId.size() && !anEdgeGroupByHybridId[iElem].empty())
586               addElemInMeshGroup(theHelper->GetMesh(), aCreatedElem, anEdgeGroupByHybridId[iElem], groupsToRemove);
587           }
588           break;
589         case GmfTriangles:
590           if (fullyCreatedElement) {
591             aCreatedElem = theHelper->AddFace( node[0], node[1], node[2], noID, force3d );
592             if (aFaceGroupByHybridId.size() && !aFaceGroupByHybridId[iElem].empty())
593               addElemInMeshGroup(theHelper->GetMesh(), aCreatedElem, aFaceGroupByHybridId[iElem], groupsToRemove);
594           }
595           break;
596         case GmfQuadrilaterals:
597           if (fullyCreatedElement) {
598             aCreatedElem = theHelper->AddFace( node[0], node[1], node[2], node[3], noID, force3d );
599           }
600           break;
601         case GmfTetrahedra:
602           if ( hasGeom )
603           {
604             if ( solidID != HOLE_ID )
605             {
606               aCreatedElem = theHelper->AddVolume( node[1], node[0], node[2], node[3],
607                                                    noID, force3d );
608               theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
609               for ( int iN = 0; iN < 4; ++iN )
610                 if ( node[iN]->getshapeId() < 1 )
611                   theMeshDS->SetNodeInVolume( node[iN], solidID );
612             }
613           }
614           else
615           {
616             if ( elemSearcher ) {
617               // Issue 0020682. Avoid creating nodes and tetras at place where
618               // volumic elements already exist
619               if ( !node[1] || !node[0] || !node[2] || !node[3] )
620                 continue;
621               if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
622                                                       SMESH_TNodeXYZ(node[1]) +
623                                                       SMESH_TNodeXYZ(node[2]) +
624                                                       SMESH_TNodeXYZ(node[3]) ) / 4.,
625                                                      SMDSAbs_Volume, foundVolumes ))
626                 break;
627             }
628             aCreatedElem = theHelper->AddVolume( node[1], node[0], node[2], node[3],
629                                                  noID, force3d );
630           }
631           break;
632         case GmfPyramids:
633           if ( hasGeom )
634           {
635             if ( solidID != HOLE_ID )
636             {
637               aCreatedElem = theHelper->AddVolume( node[3], node[2], node[1],
638                                                    node[0], node[4],
639                                                    noID, force3d );
640               theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
641               for ( int iN = 0; iN < 5; ++iN )
642                 if ( node[iN]->getshapeId() < 1 )
643                   theMeshDS->SetNodeInVolume( node[iN], solidID );
644             }
645           }
646           else
647           {
648             if ( elemSearcher ) {
649               // Issue 0020682. Avoid creating nodes and tetras at place where
650               // volumic elements already exist
651               if ( !node[1] || !node[0] || !node[2] || !node[3] || !node[4] || !node[5] )
652                 continue;
653               if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
654                                                       SMESH_TNodeXYZ(node[1]) +
655                                                       SMESH_TNodeXYZ(node[2]) +
656                                                       SMESH_TNodeXYZ(node[3]) +
657                                                       SMESH_TNodeXYZ(node[4])) / 5.,
658                                                      SMDSAbs_Volume, foundVolumes ))
659                 break;
660             }
661             aCreatedElem = theHelper->AddVolume( node[3], node[2], node[1],
662                                                    node[0], node[4],
663                                                    noID, force3d );
664           }
665           break;
666         case GmfPrisms:
667           if ( hasGeom )
668           {
669             if ( solidID != HOLE_ID )
670             {
671               aCreatedElem = theHelper->AddVolume( node[0], node[2], node[1],
672                                                    node[3], node[5], node[4],
673                                                    noID, force3d );
674               theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
675               for ( int iN = 0; iN < 6; ++iN )
676                 if ( node[iN]->getshapeId() < 1 )
677                   theMeshDS->SetNodeInVolume( node[iN], solidID );
678             }
679           }
680           else
681           {
682             if ( elemSearcher ) {
683               // Issue 0020682. Avoid creating nodes and tetras at place where
684               // volumic elements already exist
685               if ( !node[1] || !node[0] || !node[2] || !node[3] || !node[4] || !node[5] )
686                 continue;
687               if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
688                                                       SMESH_TNodeXYZ(node[1]) +
689                                                       SMESH_TNodeXYZ(node[2]) +
690                                                       SMESH_TNodeXYZ(node[3]) +
691                                                       SMESH_TNodeXYZ(node[4]) +
692                                                       SMESH_TNodeXYZ(node[5])) / 6.,
693                                                      SMDSAbs_Volume, foundVolumes ))
694                 break;
695             }
696             aCreatedElem = theHelper->AddVolume( node[0], node[2], node[1],
697                                                  node[3], node[5], node[4],
698                                                  noID, force3d );
699           }
700           break;
701         case GmfHexahedra:
702           if ( hasGeom )
703           {
704             if ( solidID != HOLE_ID )
705             {
706               aCreatedElem = theHelper->AddVolume( node[0], node[3], node[2], node[1],
707                                                    node[4], node[7], node[6], node[5],
708                                                    noID, force3d );
709               theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
710               for ( int iN = 0; iN < 8; ++iN )
711                 if ( node[iN]->getshapeId() < 1 )
712                   theMeshDS->SetNodeInVolume( node[iN], solidID );
713             }
714           }
715           else
716           {
717             if ( elemSearcher ) {
718               // Issue 0020682. Avoid creating nodes and tetras at place where
719               // volumic elements already exist
720               if ( !node[1] || !node[0] || !node[2] || !node[3] || !node[4] || !node[5] || !node[6] || !node[7])
721                 continue;
722               if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
723                                                       SMESH_TNodeXYZ(node[1]) +
724                                                       SMESH_TNodeXYZ(node[2]) +
725                                                       SMESH_TNodeXYZ(node[3]) +
726                                                       SMESH_TNodeXYZ(node[4]) +
727                                                       SMESH_TNodeXYZ(node[5]) +
728                                                       SMESH_TNodeXYZ(node[6]) +
729                                                       SMESH_TNodeXYZ(node[7])) / 8.,
730                                                      SMDSAbs_Volume, foundVolumes ))
731                 break;
732             }
733             aCreatedElem = theHelper->AddVolume( node[0], node[3], node[2], node[1],
734                                                  node[4], node[7], node[6], node[5],
735                                                  noID, force3d );
736           }
737           break;
738         default: continue;
739         } // switch (token)
740
741         if ( aCreatedElem && toMakeGroupsOfDomains )
742         {
743           if ( domainID[iElem] >= (int) elemsOfDomain.size() )
744             elemsOfDomain.resize( domainID[iElem] + 1 );
745           elemsOfDomain[ domainID[iElem] ].push_back( aCreatedElem );
746         }
747       } // loop on elements of one type
748       break;
749     } // case ...
750
751     default:;
752     } // switch (token)
753   } // loop on tabRef
754
755   // remove nodes in holes
756   if ( hasGeom )
757   {
758     for ( int i = 1; i <= nbVertices; ++i )
759       if ( GMFNode[i]->NbInverseElements() == 0 )
760         theMeshDS->RemoveFreeNode( GMFNode[i], /*sm=*/0, /*fromGroups=*/false );
761   }
762
763   MGOutput->GmfCloseMesh(InpMsh);
764
765   // 0022172: [CEA 790] create the groups corresponding to domains
766   if ( toMakeGroupsOfDomains )
767     makeDomainGroups( elemsOfDomain, theHelper );
768
769 #ifdef _DEBUG_
770   std::map<int, std::set<int> >::const_iterator subdomainIt = subdomainId2tetraId.begin();
771   std::string aSubdomainFileName = theFile;
772   aSubdomainFileName = aSubdomainFileName + ".subdomain";
773   ofstream aSubdomainFile  ( aSubdomainFileName  , ios::out);
774
775   aSubdomainFile << "Nb subdomains " << subdomainId2tetraId.size() << std::endl;
776   for(;subdomainIt != subdomainId2tetraId.end() ; ++subdomainIt) {
777     int subdomainId = subdomainIt->first;
778     std::set<int> tetraIds = subdomainIt->second;
779     std::set<int>::const_iterator tetraIdsIt = tetraIds.begin();
780     aSubdomainFile << subdomainId << std::endl;
781     for(;tetraIdsIt != tetraIds.end() ; ++tetraIdsIt) {
782       aSubdomainFile << (*tetraIdsIt) << " ";
783     }
784     aSubdomainFile << std::endl;
785   }
786   aSubdomainFile.close();
787 #endif  
788   
789   return true;
790 }
791
792
793 static bool writeGMFFile(MG_HYBRID_API*                                  MGInput,
794                          const char*                                     theMeshFileName,
795                          const char*                                     theRequiredFileName,
796                          const char*                                     theSolFileName,
797                          const SMESH_ProxyMesh&                          theProxyMesh,
798                          SMESH_MesherHelper&                             theHelper,
799                          std::vector <const SMDS_MeshNode*> &            theNodeByHybridId,
800                          std::vector <const SMDS_MeshElement*> &         theFaceByHybridId,
801                          std::map<const SMDS_MeshNode*,int> &            aNodeToHybridIdMap,
802                          std::vector<std::string> &                      aNodeGroupByHybridId,
803                          std::vector<std::string> &                      anEdgeGroupByHybridId,
804                          std::vector<std::string> &                      aFaceGroupByHybridId,
805                          HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap & theEnforcedNodes,
806                          HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedEdges,
807                          HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedTriangles,
808                          std::map<std::vector<double>, std::string> &    enfVerticesWithGroup,
809                          HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues & theEnforcedVertices)
810 {
811   std::string tmpStr;
812   int idx, idxRequired = 0, idxSol = 0;
813   //tabg each dummyint
814   //const int dummyint = 0;
815   const int dummyint1 = 1;
816   const int dummyint2 = 2;
817   const int dummyint3 = 3;
818   const int dummyint4 = 4;
819   const int enforcedTag = HYBRIDPlugin_Hypothesis::EnforcedTag();
820   //const int dummyint6 = 6; //are interesting for layers
821   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues::const_iterator vertexIt;
822   std::vector<double> enfVertexSizes;
823   const SMDS_MeshElement* elem;
824   TIDSortedElemSet anElemSetTri, anElemSetQuad, theKeptEnforcedEdges, theKeptEnforcedTriangles;
825   SMDS_ElemIteratorPtr nodeIt;
826   std::vector <const SMDS_MeshNode*> theEnforcedNodeByHybridId;
827   std::map<const SMDS_MeshNode*,int> anEnforcedNodeToHybridIdMap, anExistingEnforcedNodeToHybridIdMap;
828   std::vector< const SMDS_MeshElement* > foundElems;
829   std::map<const SMDS_MeshNode*,TopAbs_State> aNodeToTopAbs_StateMap;
830   int nbFoundElems;
831   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap::iterator elemIt;
832   TIDSortedElemSet::iterator elemSetIt;
833   bool isOK;
834   SMESH_Mesh* theMesh = theHelper.GetMesh();
835   const bool hasGeom = theMesh->HasShapeToMesh();
836   SMESHUtils::Deleter< SMESH_ElementSearcher > pntCls
837     ( SMESH_MeshAlgos::GetElementSearcher(*theMesh->GetMeshDS()));
838   
839   int nbEnforcedVertices = theEnforcedVertices.size();
840   
841   // count faces
842   int nbFaces = theProxyMesh.NbFaces();
843   int nbNodes;
844   theFaceByHybridId.reserve( nbFaces );
845   
846   // groups management
847   int usedEnforcedNodes = 0;
848   std::string gn = "";
849
850   if ( nbFaces == 0 )
851     return false;
852   
853   idx = MGInput->GmfOpenMesh(theMeshFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
854   if (!idx)
855     return false;
856   
857   // ========================== FACES ==========================
858   // TRIANGLES ==========================
859   SMDS_ElemIteratorPtr eIt =
860     hasGeom ? theProxyMesh.GetFaces( theHelper.GetSubShape()) : theProxyMesh.GetFaces();
861   while ( eIt->more() )
862   {
863     elem = eIt->next();
864     nodeIt = elem->nodesIterator();
865     nbNodes = elem->NbCornerNodes();
866     if (nbNodes == 3)
867       anElemSetTri.insert(elem);
868     else if (nbNodes == 4)
869       anElemSetQuad.insert(elem);
870     else
871     {
872       std::cout << "Unexpected number of nodes: " << nbNodes << std::endl;
873       throw ("Unexpected number of nodes" );
874     }
875     while ( nodeIt->more() && nbNodes--)
876     {
877       // find HYBRID ID
878       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
879       int newId = aNodeToHybridIdMap.size() + 1; // hybrid ids count from 1
880       aNodeToHybridIdMap.insert( std::make_pair( node, newId ));
881     }
882   }
883   
884   //EDGES ==========================
885   
886   // Iterate over the enforced edges
887   for(elemIt = theEnforcedEdges.begin() ; elemIt != theEnforcedEdges.end() ; ++elemIt) {
888     elem = elemIt->first;
889     isOK = true;
890     nodeIt = elem->nodesIterator();
891     nbNodes = 2;
892     while ( nodeIt->more() && nbNodes-- ) {
893       // find HYBRID ID
894       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
895       // Test if point is inside shape to mesh
896       gp_Pnt myPoint(node->X(),node->Y(),node->Z());
897       TopAbs_State result = pntCls->GetPointState( myPoint );
898       if ( result == TopAbs_OUT ) {
899         isOK = false;
900         break;
901       }
902       aNodeToTopAbs_StateMap.insert( std::make_pair( node, result ));
903     }
904     if (isOK) {
905       nodeIt = elem->nodesIterator();
906       nbNodes = 2;
907       int newId = -1;
908       while ( nodeIt->more() && nbNodes-- ) {
909         // find HYBRID ID
910         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
911         gp_Pnt myPoint(node->X(),node->Y(),node->Z());
912         nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
913 #ifdef _DEBUG_
914         std::cout << "Node at "<<node->X()<<", "<<node->Y()<<", "<<node->Z()<<std::endl;
915         std::cout << "Nb nodes found : "<<nbFoundElems<<std::endl;
916 #endif
917         if (nbFoundElems ==0) {
918           if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
919             newId = aNodeToHybridIdMap.size() + anEnforcedNodeToHybridIdMap.size() + 1; // hybrid ids count from 1
920             anEnforcedNodeToHybridIdMap.insert( std::make_pair( node, newId ));
921           }
922         }
923         else if (nbFoundElems ==1) {
924           const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
925           newId = (*aNodeToHybridIdMap.find(existingNode)).second;
926           anExistingEnforcedNodeToHybridIdMap.insert( std::make_pair( node, newId ));
927         }
928         else
929           isOK = false;
930 #ifdef _DEBUG_
931         std::cout << "HYBRID node ID: "<<newId<<std::endl;
932 #endif
933       }
934       if (isOK)
935         theKeptEnforcedEdges.insert(elem);
936     }
937   }
938   
939   //ENFORCED TRIANGLES ==========================
940   
941   // Iterate over the enforced triangles
942   for(elemIt = theEnforcedTriangles.begin() ; elemIt != theEnforcedTriangles.end() ; ++elemIt) {
943     elem = elemIt->first;
944     isOK = true;
945     nodeIt = elem->nodesIterator();
946     nbNodes = 3;
947     while ( nodeIt->more() && nbNodes--) {
948       // find HYBRID ID
949       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
950       // Test if point is inside shape to mesh
951       gp_Pnt myPoint(node->X(),node->Y(),node->Z());
952       TopAbs_State result = pntCls->GetPointState( myPoint );
953       if ( result == TopAbs_OUT ) {
954         isOK = false;
955         break;
956       }
957       aNodeToTopAbs_StateMap.insert( std::make_pair( node, result ));
958     }
959     if (isOK) {
960       nodeIt = elem->nodesIterator();
961       nbNodes = 3;
962       int newId = -1;
963       while ( nodeIt->more() && nbNodes--) {
964         // find HYBRID ID
965         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
966         gp_Pnt myPoint(node->X(),node->Y(),node->Z());
967         nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
968 #ifdef _DEBUG_
969         std::cout << "Nb nodes found : "<<nbFoundElems<<std::endl;
970 #endif
971         if (nbFoundElems ==0) {
972           if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
973             newId = aNodeToHybridIdMap.size() + anEnforcedNodeToHybridIdMap.size() + 1; // hybrid ids count from 1
974             anEnforcedNodeToHybridIdMap.insert( std::make_pair( node, newId ));
975           }
976         }
977         else if (nbFoundElems ==1) {
978           const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
979           newId = (*aNodeToHybridIdMap.find(existingNode)).second;
980           anExistingEnforcedNodeToHybridIdMap.insert( std::make_pair( node, newId ));
981         }
982         else
983           isOK = false;
984 #ifdef _DEBUG_
985         std::cout << "HYBRID node ID: "<<newId<<std::endl;
986 #endif
987       }
988       if (isOK)
989         theKeptEnforcedTriangles.insert(elem);
990     }
991   }
992   
993   // put nodes to theNodeByHybridId vector
994 #ifdef _DEBUG_
995   std::cout << "aNodeToHybridIdMap.size(): "<<aNodeToHybridIdMap.size()<<std::endl;
996 #endif
997   theNodeByHybridId.resize( aNodeToHybridIdMap.size() );
998   std::map<const SMDS_MeshNode*,int>::const_iterator n2id = aNodeToHybridIdMap.begin();
999   for ( ; n2id != aNodeToHybridIdMap.end(); ++ n2id)
1000   {
1001 //     std::cout << "n2id->first: "<<n2id->first<<std::endl;
1002     theNodeByHybridId[ n2id->second - 1 ] = n2id->first; // hybrid ids count from 1
1003   }
1004
1005   // put nodes to anEnforcedNodeToHybridIdMap vector
1006 #ifdef _DEBUG_
1007   std::cout << "anEnforcedNodeToHybridIdMap.size(): "<<anEnforcedNodeToHybridIdMap.size()<<std::endl;
1008 #endif
1009   theEnforcedNodeByHybridId.resize( anEnforcedNodeToHybridIdMap.size());
1010   n2id = anEnforcedNodeToHybridIdMap.begin();
1011   for ( ; n2id != anEnforcedNodeToHybridIdMap.end(); ++ n2id)
1012   {
1013     if (n2id->second > (int)aNodeToHybridIdMap.size()) {
1014       theEnforcedNodeByHybridId[ n2id->second - aNodeToHybridIdMap.size() - 1 ] = n2id->first; // hybrid ids count from 1
1015     }
1016   }
1017   
1018   
1019   //========================== NODES ==========================
1020   std::vector<const SMDS_MeshNode*> theOrderedNodes, theRequiredNodes;
1021   std::set< std::vector<double> > nodesCoords;
1022   std::vector<const SMDS_MeshNode*>::const_iterator hybridNodeIt = theNodeByHybridId.begin();
1023   std::vector<const SMDS_MeshNode*>::const_iterator after  = theNodeByHybridId.end();
1024   
1025   (theNodeByHybridId.size() <= 1) ? tmpStr = " node" : " nodes";
1026   std::cout << theNodeByHybridId.size() << tmpStr << " from mesh ..." << std::endl;
1027   for ( ; hybridNodeIt != after; ++hybridNodeIt )
1028   {
1029     const SMDS_MeshNode* node = *hybridNodeIt;
1030     std::vector<double> coords;
1031     coords.push_back(node->X());
1032     coords.push_back(node->Y());
1033     coords.push_back(node->Z());
1034     nodesCoords.insert(coords);
1035     theOrderedNodes.push_back(node);
1036   }
1037   
1038   // Iterate over the enforced nodes given by enforced elements
1039   hybridNodeIt = theEnforcedNodeByHybridId.begin();
1040   after  = theEnforcedNodeByHybridId.end();
1041   (theEnforcedNodeByHybridId.size() <= 1) ? tmpStr = " node" : " nodes";
1042   std::cout << theEnforcedNodeByHybridId.size() << tmpStr << " from enforced elements ..." << std::endl;
1043   for ( ; hybridNodeIt != after; ++hybridNodeIt )
1044   {
1045     const SMDS_MeshNode* node = *hybridNodeIt;
1046     std::vector<double> coords;
1047     coords.push_back(node->X());
1048     coords.push_back(node->Y());
1049     coords.push_back(node->Z());
1050 #ifdef _DEBUG_
1051     std::cout << "Node at " << node->X()<<", " <<node->Y()<<", " <<node->Z();
1052 #endif
1053     
1054     if (nodesCoords.find(coords) != nodesCoords.end()) {
1055       // node already exists in original mesh
1056 #ifdef _DEBUG_
1057       std::cout << " found" << std::endl;
1058 #endif
1059       continue;
1060     }
1061     
1062     if (theEnforcedVertices.find(coords) != theEnforcedVertices.end()) {
1063       // node already exists in enforced vertices
1064 #ifdef _DEBUG_
1065       std::cout << " found" << std::endl;
1066 #endif
1067       continue;
1068     }
1069     
1070 #ifdef _DEBUG_
1071     std::cout << " not found" << std::endl;
1072 #endif
1073     
1074     nodesCoords.insert(coords);
1075     theOrderedNodes.push_back(node);
1076 //     theRequiredNodes.push_back(node);
1077   }
1078   
1079   
1080   // Iterate over the enforced nodes
1081   HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap::const_iterator enfNodeIt;
1082   (theEnforcedNodes.size() <= 1) ? tmpStr = " node" : " nodes";
1083   std::cout << theEnforcedNodes.size() << tmpStr << " from enforced nodes ..." << std::endl;
1084   for(enfNodeIt = theEnforcedNodes.begin() ; enfNodeIt != theEnforcedNodes.end() ; ++enfNodeIt)
1085   {
1086     const SMDS_MeshNode* node = enfNodeIt->first;
1087     std::vector<double> coords;
1088     coords.push_back(node->X());
1089     coords.push_back(node->Y());
1090     coords.push_back(node->Z());
1091 #ifdef _DEBUG_
1092     std::cout << "Node at " << node->X()<<", " <<node->Y()<<", " <<node->Z();
1093 #endif
1094     
1095     // Test if point is inside shape to mesh
1096     gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1097     TopAbs_State result = pntCls->GetPointState( myPoint );
1098     if ( result == TopAbs_OUT ) {
1099 #ifdef _DEBUG_
1100       std::cout << " out of volume" << std::endl;
1101 #endif
1102       continue;
1103     }
1104     
1105     if (nodesCoords.find(coords) != nodesCoords.end()) {
1106 #ifdef _DEBUG_
1107       std::cout << " found in nodesCoords" << std::endl;
1108 #endif
1109 //       theRequiredNodes.push_back(node);
1110       continue;
1111     }
1112
1113     if (theEnforcedVertices.find(coords) != theEnforcedVertices.end()) {
1114 #ifdef _DEBUG_
1115       std::cout << " found in theEnforcedVertices" << std::endl;
1116 #endif
1117       continue;
1118     }
1119     
1120 #ifdef _DEBUG_
1121     std::cout << " not found" << std::endl;
1122 #endif
1123     nodesCoords.insert(coords);
1124 //     theOrderedNodes.push_back(node);
1125     theRequiredNodes.push_back(node);
1126   }
1127   int requiredNodes = theRequiredNodes.size();
1128   
1129   int solSize = 0;
1130   std::vector<std::vector<double> > ReqVerTab;
1131   if (nbEnforcedVertices) {
1132     (nbEnforcedVertices <= 1) ? tmpStr = " node" : " nodes";
1133     std::cout << nbEnforcedVertices << tmpStr << " from enforced vertices ..." << std::endl;
1134     // Iterate over the enforced vertices
1135     for(vertexIt = theEnforcedVertices.begin() ; vertexIt != theEnforcedVertices.end() ; ++vertexIt) {
1136       double x = vertexIt->first[0];
1137       double y = vertexIt->first[1];
1138       double z = vertexIt->first[2];
1139       // Test if point is inside shape to mesh
1140       gp_Pnt myPoint(x,y,z);
1141       TopAbs_State result = pntCls->GetPointState( myPoint );
1142       if ( result == TopAbs_OUT )
1143         continue;
1144       std::vector<double> coords;
1145       coords.push_back(x);
1146       coords.push_back(y);
1147       coords.push_back(z);
1148       ReqVerTab.push_back(coords);
1149       enfVertexSizes.push_back(vertexIt->second);
1150       solSize++;
1151     }
1152   }
1153   
1154   
1155   // GmfVertices
1156   std::cout << "Begin writing required nodes in GmfVertices" << std::endl;
1157   std::cout << "Nb vertices: " << theOrderedNodes.size() << std::endl;
1158   MGInput->GmfSetKwd(idx, GmfVertices, theOrderedNodes.size());
1159   for (hybridNodeIt = theOrderedNodes.begin();hybridNodeIt != theOrderedNodes.end();++hybridNodeIt) {
1160     MGInput->GmfSetLin(idx, GmfVertices, (*hybridNodeIt)->X(), (*hybridNodeIt)->Y(), (*hybridNodeIt)->Z(), dummyint1);
1161   }
1162
1163   std::cout << "End writing required nodes in GmfVertices" << std::endl;
1164
1165   if (requiredNodes + solSize) {
1166     std::cout << "Begin writing in req and sol file" << std::endl;
1167     aNodeGroupByHybridId.resize( requiredNodes + solSize );
1168     idxRequired = MGInput->GmfOpenMesh(theRequiredFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1169     if (!idxRequired) {
1170       MGInput->GmfCloseMesh(idx);
1171       return false;
1172     }
1173     idxSol = MGInput->GmfOpenMesh(theSolFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1174     if (!idxSol) {
1175       MGInput->GmfCloseMesh(idx);
1176       if (idxRequired)
1177         MGInput->GmfCloseMesh(idxRequired);
1178       return false;
1179     }
1180     int TypTab[] = {GmfSca};
1181     double ValTab[] = {0.0};
1182     MGInput->GmfSetKwd(idxRequired, GmfVertices, requiredNodes + solSize);
1183     MGInput->GmfSetKwd(idxSol, GmfSolAtVertices, requiredNodes + solSize, 1, TypTab);
1184     for (hybridNodeIt = theRequiredNodes.begin();hybridNodeIt != theRequiredNodes.end();++hybridNodeIt) {
1185       MGInput->GmfSetLin(idxRequired, GmfVertices, (*hybridNodeIt)->X(), (*hybridNodeIt)->Y(), (*hybridNodeIt)->Z(), dummyint2);
1186       MGInput->GmfSetLin(idxSol, GmfSolAtVertices, ValTab);
1187       if (theEnforcedNodes.find((*hybridNodeIt)) != theEnforcedNodes.end())
1188         gn = theEnforcedNodes.find((*hybridNodeIt))->second;
1189       aNodeGroupByHybridId[usedEnforcedNodes] = gn;
1190       usedEnforcedNodes++;
1191     }
1192
1193     for (int i=0;i<solSize;i++) {
1194       std::cout << ReqVerTab[i][0] <<" "<< ReqVerTab[i][1] << " "<< ReqVerTab[i][2] << std::endl;
1195 #ifdef _DEBUG_
1196       std::cout << "enfVertexSizes.at("<<i<<"): " << enfVertexSizes.at(i) << std::endl;
1197 #endif
1198       double solTab[] = {enfVertexSizes.at(i)};
1199       MGInput->GmfSetLin(idxRequired, GmfVertices, ReqVerTab[i][0], ReqVerTab[i][1], ReqVerTab[i][2], dummyint3);
1200       MGInput->GmfSetLin(idxSol, GmfSolAtVertices, solTab);
1201       aNodeGroupByHybridId[usedEnforcedNodes] = enfVerticesWithGroup.find(ReqVerTab[i])->second;
1202 #ifdef _DEBUG_
1203       std::cout << "aNodeGroupByHybridId["<<usedEnforcedNodes<<"] = \""<<aNodeGroupByHybridId[usedEnforcedNodes]<<"\""<<std::endl;
1204 #endif
1205       usedEnforcedNodes++;
1206     }
1207     std::cout << "End writing in req and sol file" << std::endl;
1208   }
1209
1210   int nedge[2], ntri[3], nquad[4];
1211     
1212   // GmfEdges
1213   int usedEnforcedEdges = 0;
1214   if (theKeptEnforcedEdges.size()) {
1215     anEdgeGroupByHybridId.resize( theKeptEnforcedEdges.size() );
1216     MGInput->GmfSetKwd(idx, GmfEdges, theKeptEnforcedEdges.size());
1217     for(elemSetIt = theKeptEnforcedEdges.begin() ; elemSetIt != theKeptEnforcedEdges.end() ; ++elemSetIt) {
1218       elem = (*elemSetIt);
1219       nodeIt = elem->nodesIterator();
1220       int index=0;
1221       while ( nodeIt->more() ) {
1222         // find HYBRID ID
1223         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1224         std::map< const SMDS_MeshNode*,int >::iterator it = anEnforcedNodeToHybridIdMap.find(node);
1225         if (it == anEnforcedNodeToHybridIdMap.end()) {
1226           it = anExistingEnforcedNodeToHybridIdMap.find(node);
1227           if (it == anEnforcedNodeToHybridIdMap.end())
1228             throw "Node not found";
1229         }
1230         nedge[index] = it->second;
1231         index++;
1232       }
1233       MGInput->GmfSetLin(idx, GmfEdges, nedge[0], nedge[1], dummyint4);
1234       anEdgeGroupByHybridId[usedEnforcedEdges] = theEnforcedEdges.find(elem)->second;
1235       usedEnforcedEdges++;
1236     }
1237   }
1238
1239
1240   if (usedEnforcedEdges) {
1241     MGInput->GmfSetKwd(idx, GmfRequiredEdges, usedEnforcedEdges);
1242     for (int enfID=1;enfID<=usedEnforcedEdges;enfID++) {
1243       MGInput->GmfSetLin(idx, GmfRequiredEdges, enfID);
1244     }
1245   }
1246
1247   // GmfTriangles
1248   int usedEnforcedTriangles = 0;
1249   if (anElemSetTri.size()+theKeptEnforcedTriangles.size())
1250   {
1251     aFaceGroupByHybridId.resize( anElemSetTri.size()+theKeptEnforcedTriangles.size() );
1252     MGInput->GmfSetKwd(idx, GmfTriangles, anElemSetTri.size()+theKeptEnforcedTriangles.size());
1253     int k=0;
1254     for(elemSetIt = anElemSetTri.begin() ; elemSetIt != anElemSetTri.end() ; ++elemSetIt,++k)
1255     {
1256       elem = (*elemSetIt);
1257       theFaceByHybridId.push_back( elem );
1258       nodeIt = elem->nodesIterator();
1259       int index=0;
1260       for ( int j = 0; j < 3; ++j )
1261       {
1262         // find HYBRID ID
1263         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1264         std::map< const SMDS_MeshNode*,int >::iterator it = aNodeToHybridIdMap.find(node);
1265         if (it == aNodeToHybridIdMap.end())
1266           throw "Node not found";
1267         ntri[index] = it->second;
1268         index++;
1269       }
1270       MGInput->GmfSetLin(idx, GmfTriangles, ntri[0], ntri[1], ntri[2], /*tag=*/elem->getshapeId() );
1271       aFaceGroupByHybridId[k] = "";
1272     }
1273     
1274     if ( !theHelper.GetMesh()->HasShapeToMesh() ) SMESHUtils::FreeVector( theFaceByHybridId ); 
1275     std::cout << "Enforced triangles size " << theKeptEnforcedTriangles.size() << std::endl;
1276     if (theKeptEnforcedTriangles.size())
1277     {
1278       for(elemSetIt = theKeptEnforcedTriangles.begin() ; elemSetIt != theKeptEnforcedTriangles.end() ; ++elemSetIt,++k)
1279       {
1280         elem = (*elemSetIt);
1281         nodeIt = elem->nodesIterator();
1282         int index=0;
1283         for ( int j = 0; j < 3; ++j )
1284         {
1285           // find HYBRID ID
1286           const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1287           std::map< const SMDS_MeshNode*,int >::iterator it = anEnforcedNodeToHybridIdMap.find(node);
1288           if (it == anEnforcedNodeToHybridIdMap.end())
1289           {
1290             it = anExistingEnforcedNodeToHybridIdMap.find(node);
1291             if (it == anEnforcedNodeToHybridIdMap.end())
1292               throw "Node not found";
1293           }
1294           ntri[index] = it->second;
1295           index++;
1296         }
1297         MGInput->GmfSetLin(idx, GmfTriangles, ntri[0], ntri[1], ntri[2], enforcedTag);
1298         aFaceGroupByHybridId[k] = theEnforcedTriangles.find(elem)->second;
1299         usedEnforcedTriangles++;
1300       }
1301     }
1302   }
1303
1304   
1305   if (usedEnforcedTriangles)
1306   {
1307     MGInput->GmfSetKwd(idx, GmfRequiredTriangles, usedEnforcedTriangles);
1308     for (int enfID=1;enfID<=usedEnforcedTriangles;enfID++)
1309       MGInput->GmfSetLin(idx, GmfRequiredTriangles, anElemSetTri.size()+enfID);
1310   }
1311   
1312   if (anElemSetQuad.size())
1313   {
1314     MGInput->GmfSetKwd(idx, GmfQuadrilaterals, anElemSetQuad.size());
1315     int k=0;
1316     for(elemSetIt = anElemSetQuad.begin() ; elemSetIt != anElemSetQuad.end() ; ++elemSetIt,++k)
1317     {
1318       elem = (*elemSetIt);
1319       theFaceByHybridId.push_back( elem );
1320       nodeIt = elem->nodesIterator();
1321       int index=0;
1322       for ( int j = 0; j < 4; ++j )
1323       {
1324         // find HYBRID ID
1325         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1326         std::map< const SMDS_MeshNode*,int >::iterator it = aNodeToHybridIdMap.find(node);
1327         if (it == aNodeToHybridIdMap.end())
1328           throw "Node not found";
1329         nquad[index] = it->second;
1330         index++;
1331       }
1332       MGInput->GmfSetLin(idx, GmfQuadrilaterals, nquad[0], nquad[1], nquad[2], nquad[3],
1333                          /*tag=*/elem->getshapeId() );
1334       // _CEA_cbo what is it for???
1335       //aFaceGroupByHybridId[k] = "";
1336     }
1337   }
1338
1339   MGInput->GmfCloseMesh(idx);
1340   if (idxRequired)
1341     MGInput->GmfCloseMesh(idxRequired);
1342   if (idxSol)
1343     MGInput->GmfCloseMesh(idxSol);
1344   
1345   return true;
1346   
1347 }
1348
1349 //=============================================================================
1350 /*!
1351  *Here we are going to use the HYBRID mesher with geometry
1352  */
1353 //=============================================================================
1354
1355 bool HYBRIDPlugin_HYBRID::Compute(SMESH_Mesh&         theMesh,
1356                                   const TopoDS_Shape& theShape)
1357 {
1358   bool Ok = false;
1359
1360   // a unique working file name
1361   // to avoid access to the same files by eg different users
1362   _genericName = HYBRIDPlugin_Hypothesis::GetFileName(_hyp);
1363   std::string aGenericName         = _genericName;
1364   std::string aGenericNameRequired = aGenericName + "_required";
1365
1366   std::string aLogFileName    = aGenericName + ".log";    // log
1367   std::string aResultFileName;
1368
1369   std::string aGMFFileName, aRequiredVerticesFileName, aSolFileName, aResSolFileName;
1370   aGMFFileName              = aGenericName + ".mesh"; // GMF mesh file
1371   aResultFileName           = aGenericName + "Vol.mesh"; // GMF mesh file
1372   aResSolFileName           = aGenericName + "Vol.sol"; // GMF mesh file
1373   aRequiredVerticesFileName = aGenericNameRequired + ".mesh"; // GMF required vertices mesh file
1374   aSolFileName              = aGenericNameRequired + ".sol"; // GMF solution file
1375   
1376   std::map <int,int> aNodeId2NodeIndexMap, aSmdsToHybridIdMap, anEnforcedNodeIdToHybridIdMap;
1377   std::map <int, int> nodeID2nodeIndexMap;
1378   std::map<std::vector<double>, std::string> enfVerticesWithGroup;
1379   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues coordsSizeMap = HYBRIDPlugin_Hypothesis::GetEnforcedVerticesCoordsSize(_hyp);
1380   HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap enforcedNodes = HYBRIDPlugin_Hypothesis::GetEnforcedNodes(_hyp);
1381   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap enforcedEdges = HYBRIDPlugin_Hypothesis::GetEnforcedEdges(_hyp);
1382   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap enforcedTriangles = HYBRIDPlugin_Hypothesis::GetEnforcedTriangles(_hyp);
1383   HYBRIDPlugin_Hypothesis::TID2SizeMap nodeIDToSizeMap = HYBRIDPlugin_Hypothesis::GetNodeIDToSizeMap(_hyp);
1384
1385   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexList enfVertices = HYBRIDPlugin_Hypothesis::GetEnforcedVertices(_hyp);
1386   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexList::const_iterator enfVerIt = enfVertices.begin();
1387   std::vector<double> coords;
1388
1389   for ( ; enfVerIt != enfVertices.end() ; ++enfVerIt)
1390   {
1391     HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertex* enfVertex = (*enfVerIt);
1392     if (enfVertex->coords.size()) {
1393       coordsSizeMap.insert(std::make_pair(enfVertex->coords,enfVertex->size));
1394       enfVerticesWithGroup.insert(std::make_pair(enfVertex->coords,enfVertex->groupName));
1395     }
1396     else {
1397       TopoDS_Shape GeomShape = entryToShape(enfVertex->geomEntry);
1398       for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1399         coords.clear();
1400         if (it.Value().ShapeType() == TopAbs_VERTEX){
1401           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
1402           coords.push_back(aPnt.X());
1403           coords.push_back(aPnt.Y());
1404           coords.push_back(aPnt.Z());
1405           if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
1406             coordsSizeMap.insert(std::make_pair(coords,enfVertex->size));
1407             enfVerticesWithGroup.insert(std::make_pair(coords,enfVertex->groupName));
1408           }
1409         }
1410       }
1411     }
1412   }
1413   int nbEnforcedVertices = coordsSizeMap.size();
1414   int nbEnforcedNodes = enforcedNodes.size();
1415
1416   std::string tmpStr;
1417   (nbEnforcedNodes <= 1) ? tmpStr = "node" : "nodes";
1418   std::cout << nbEnforcedNodes << " enforced " << tmpStr << " from hypo" << std::endl;
1419   (nbEnforcedVertices <= 1) ? tmpStr = "vertex" : "vertices";
1420   std::cout << nbEnforcedVertices << " enforced " << tmpStr << " from hypo" << std::endl;
1421
1422   SMESH_MesherHelper helper( theMesh );
1423   helper.SetSubShape( theShape );
1424
1425   std::vector <const SMDS_MeshNode*> aNodeByHybridId, anEnforcedNodeByHybridId;
1426   std::vector <const SMDS_MeshElement*> aFaceByHybridId;
1427   std::map<const SMDS_MeshNode*,int> aNodeToHybridIdMap;
1428   std::vector<std::string> aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId;
1429
1430   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
1431
1432   MG_HYBRID_API mgHybrid( _computeCanceled, _progress );
1433
1434   Ok = writeGMFFile(&mgHybrid,
1435                     aGMFFileName.c_str(),
1436                     aRequiredVerticesFileName.c_str(),
1437                     aSolFileName.c_str(),
1438                     *proxyMesh, helper,
1439                     aNodeByHybridId, aFaceByHybridId, aNodeToHybridIdMap,
1440                     aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId,
1441                     enforcedNodes, enforcedEdges, enforcedTriangles, /*enforcedQuadrangles,*/
1442                     enfVerticesWithGroup, coordsSizeMap);
1443
1444   // Write aSmdsToHybridIdMap to temp file
1445   std::string aSmdsToHybridIdMapFileName;
1446   aSmdsToHybridIdMapFileName = aGenericName + ".ids";  // ids relation
1447   ofstream aIdsFile  ( aSmdsToHybridIdMapFileName  , ios::out);
1448   Ok = aIdsFile.rdbuf()->is_open();
1449   if (!Ok) {
1450     INFOS( "Can't write into " << aSmdsToHybridIdMapFileName);
1451     return error(SMESH_Comment("Can't write into ") << aSmdsToHybridIdMapFileName);
1452   }
1453   INFOS( "Writing ids relation into " << aSmdsToHybridIdMapFileName);
1454   aIdsFile << "Smds Hybrid" << std::endl;
1455   std::map <int,int>::const_iterator myit;
1456   for (myit=aSmdsToHybridIdMap.begin() ; myit != aSmdsToHybridIdMap.end() ; ++myit) {
1457     aIdsFile << myit->first << " " << myit->second << std::endl;
1458   }
1459
1460   aIdsFile.close();
1461
1462   if ( ! Ok ) {
1463     if ( !_keepFiles ) {
1464       removeFile( aGMFFileName );
1465       removeFile( aRequiredVerticesFileName );
1466       removeFile( aSolFileName );
1467       removeFile( aSmdsToHybridIdMapFileName );
1468     }
1469     return error(COMPERR_BAD_INPUT_MESH);
1470   }
1471   removeFile( aResultFileName ); // needed for boundary recovery module usage
1472
1473   // -----------------
1474   // run hybrid mesher
1475   // -----------------
1476
1477   std::string cmd = HYBRIDPlugin_Hypothesis::CommandToRun( _hyp, theMesh );
1478
1479   if ( mgHybrid.IsExecutable() )
1480   {
1481     cmd += " --in "  + aGMFFileName;
1482     cmd += " --out " + aResultFileName;
1483   }
1484   std::cout << std::endl;
1485   std::cout << "Hybrid execution with geometry..." << std::endl;
1486   std::cout << cmd;
1487   if ( !_logInStandardOutput )
1488   {
1489     mgHybrid.SetLogFile( aLogFileName );
1490     if ( mgHybrid.IsExecutable() )
1491       cmd += " 1>" + aLogFileName;  // dump into file
1492     std::cout << " 1> " << aLogFileName;
1493   }
1494   std::cout << std::endl;
1495
1496   _computeCanceled = false;
1497
1498   std::string errStr;
1499   Ok = mgHybrid.Compute( cmd, errStr ); // run
1500
1501   if ( _logInStandardOutput && mgHybrid.IsLibrary() )
1502     std::cout << std::endl << mgHybrid.GetLog() << std::endl;
1503   if ( Ok )
1504     std::cout << "End of Hybrid execution !" << std::endl;
1505
1506   // --------------
1507   // read a result
1508   // --------------
1509
1510   // Mapping the result file
1511
1512   HYBRIDPlugin_Hypothesis::TSetStrings groupsToRemove = HYBRIDPlugin_Hypothesis::GetGroupsToRemove(_hyp);
1513   bool toMeshHoles =
1514     _hyp ? _hyp->GetToMeshHoles(true) : HYBRIDPlugin_Hypothesis::DefaultMeshHoles();
1515   const bool toMakeGroupsOfDomains = HYBRIDPlugin_Hypothesis::GetToMakeGroupsOfDomains( _hyp );
1516
1517   helper.IsQuadraticSubMesh( theShape );
1518   helper.SetElementsOnShape( false );
1519
1520   Ok = readGMFFile(&mgHybrid, aResultFileName.c_str(),
1521                    this,
1522                    &helper, aNodeByHybridId, aFaceByHybridId, aNodeToHybridIdMap,
1523                    aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId,
1524                    groupsToRemove, toMakeGroupsOfDomains, toMeshHoles);
1525
1526   removeEmptyGroupsOfDomains( helper.GetMesh(), !toMakeGroupsOfDomains );
1527
1528
1529
1530   // ---------------------
1531   // remove working files
1532   // ---------------------
1533
1534   if ( Ok )
1535   {
1536     if ( _removeLogOnSuccess )
1537       removeFile( aLogFileName );
1538   }
1539   else if ( mgHybrid.HasLog() )
1540   {
1541     // get problem description from the log file
1542     _Ghs2smdsConvertor conv( aNodeByHybridId );
1543     storeErrorDescription( _logInStandardOutput ? 0 : aLogFileName.c_str(),
1544                            mgHybrid.GetLog(), conv );
1545   }
1546   else if ( !errStr.empty() )
1547   {
1548     // the log file is empty
1549     removeFile( aLogFileName );
1550     INFOS( "HYBRID Error, " << errStr );
1551     error(COMPERR_ALGO_FAILED, errStr );
1552   }
1553
1554   if ( !_keepFiles ) {
1555     if (! Ok && _computeCanceled)
1556       removeFile( aLogFileName );
1557     removeFile( aGMFFileName );
1558     removeFile( aRequiredVerticesFileName );
1559     removeFile( aSolFileName );
1560     removeFile( aResSolFileName );
1561     removeFile( aResultFileName );
1562     removeFile( aSmdsToHybridIdMapFileName );
1563   }
1564   if ( mgHybrid.IsExecutable() )
1565   {
1566     std::cout << "<" << aResultFileName << "> HYBRID output file ";
1567     if ( !Ok )
1568       std::cout << "not ";
1569     std::cout << "treated !" << std::endl;
1570     std::cout << std::endl;
1571   }
1572   else
1573   {
1574     std::cout << "MG-HYBRID " << ( Ok ? "succeeded" : "failed") << std::endl;
1575   }
1576
1577   return Ok;
1578 }
1579
1580 //=============================================================================
1581 /*!
1582  *Here we are going to use the HYBRID mesher w/o geometry
1583  */
1584 //=============================================================================
1585 bool HYBRIDPlugin_HYBRID::Compute(SMESH_Mesh&         theMesh,
1586                                   SMESH_MesherHelper* theHelper)
1587 {
1588   theHelper->IsQuadraticSubMesh( theHelper->GetSubShape() );
1589
1590   // a unique working file name
1591   // to avoid access to the same files by eg different users
1592   _genericName = HYBRIDPlugin_Hypothesis::GetFileName(_hyp);
1593   std::string aGenericName((char*) _genericName.c_str() );
1594   std::string aGenericNameRequired = aGenericName + "_required";
1595
1596   std::string aLogFileName    = aGenericName + ".log";    // log
1597   std::string aResultFileName;
1598   bool Ok;
1599
1600   std::string aGMFFileName, aRequiredVerticesFileName, aSolFileName, aResSolFileName;
1601   aGMFFileName              = aGenericName + ".mesh"; // GMF mesh file
1602   aResultFileName           = aGenericName + "Vol.mesh"; // GMF mesh file
1603   aResSolFileName           = aGenericName + "Vol.sol"; // GMF mesh file
1604   aRequiredVerticesFileName = aGenericNameRequired + ".mesh"; // GMF required vertices mesh file
1605   aSolFileName              = aGenericNameRequired + ".sol"; // GMF solution file
1606
1607   std::map <int, int> nodeID2nodeIndexMap;
1608   std::map<std::vector<double>, std::string> enfVerticesWithGroup;
1609   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues coordsSizeMap;
1610   TopoDS_Shape GeomShape;
1611   std::vector<double> coords;
1612   gp_Pnt aPnt;
1613   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertex* enfVertex;
1614
1615   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexList enfVertices = HYBRIDPlugin_Hypothesis::GetEnforcedVertices(_hyp);
1616   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexList::const_iterator enfVerIt = enfVertices.begin();
1617
1618   for ( ; enfVerIt != enfVertices.end() ; ++enfVerIt)
1619   {
1620     enfVertex = (*enfVerIt);
1621     if (enfVertex->coords.size()) {
1622       coordsSizeMap.insert(std::make_pair(enfVertex->coords,enfVertex->size));
1623       enfVerticesWithGroup.insert(std::make_pair(enfVertex->coords,enfVertex->groupName));
1624     }
1625     else {
1626       GeomShape = entryToShape(enfVertex->geomEntry);
1627       for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1628         coords.clear();
1629         if (it.Value().ShapeType() == TopAbs_VERTEX){
1630           aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
1631           coords.push_back(aPnt.X());
1632           coords.push_back(aPnt.Y());
1633           coords.push_back(aPnt.Z());
1634           if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
1635             coordsSizeMap.insert(std::make_pair(coords,enfVertex->size));
1636             enfVerticesWithGroup.insert(std::make_pair(coords,enfVertex->groupName));
1637           }
1638         }
1639       }
1640     }
1641   }
1642
1643   HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap enforcedNodes = HYBRIDPlugin_Hypothesis::GetEnforcedNodes(_hyp);
1644   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap enforcedEdges = HYBRIDPlugin_Hypothesis::GetEnforcedEdges(_hyp);
1645   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap enforcedTriangles = HYBRIDPlugin_Hypothesis::GetEnforcedTriangles(_hyp);
1646   HYBRIDPlugin_Hypothesis::TID2SizeMap nodeIDToSizeMap = HYBRIDPlugin_Hypothesis::GetNodeIDToSizeMap(_hyp);
1647
1648   std::string tmpStr;
1649
1650   int nbEnforcedVertices = coordsSizeMap.size();
1651   int nbEnforcedNodes = enforcedNodes.size();
1652   (nbEnforcedNodes <= 1) ? tmpStr = "node" : tmpStr = "nodes";
1653   std::cout << nbEnforcedNodes << " enforced " << tmpStr << " from hypo" << std::endl;
1654   (nbEnforcedVertices <= 1) ? tmpStr = "vertex" : tmpStr = "vertices";
1655   std::cout << nbEnforcedVertices << " enforced " << tmpStr << " from hypo" << std::endl;
1656
1657   std::vector <const SMDS_MeshNode*> aNodeByHybridId, anEnforcedNodeByHybridId;
1658   std::vector <const SMDS_MeshElement*> aFaceByHybridId;
1659   std::map<const SMDS_MeshNode*,int> aNodeToHybridIdMap;
1660   std::vector<std::string> aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId;
1661
1662   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
1663
1664   MG_HYBRID_API mgHybrid( _computeCanceled, _progress );
1665
1666   Ok = writeGMFFile(&mgHybrid,
1667                     aGMFFileName.c_str(),
1668                     aRequiredVerticesFileName.c_str(), aSolFileName.c_str(),
1669                     *proxyMesh, *theHelper,
1670                     aNodeByHybridId, aFaceByHybridId, aNodeToHybridIdMap,
1671                     aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId,
1672                     enforcedNodes, enforcedEdges, enforcedTriangles,
1673                     enfVerticesWithGroup, coordsSizeMap);
1674
1675   // -----------------
1676   // run hybrid mesher
1677   // -----------------
1678
1679   std::string cmd = HYBRIDPlugin_Hypothesis::CommandToRun( _hyp, theMesh );
1680
1681   if ( mgHybrid.IsExecutable() )
1682   {
1683     cmd += " --in "  + aGMFFileName;
1684     cmd += " --out " + aResultFileName;
1685   }
1686   if ( !_logInStandardOutput )
1687   {
1688     cmd += " 1> " + aLogFileName;  // dump into file
1689     mgHybrid.SetLogFile( aLogFileName );
1690   }
1691   std::cout << std::endl;
1692   std::cout << "Hybrid execution w/o geometry..." << std::endl;
1693   std::cout << cmd << std::endl;
1694
1695   _computeCanceled = false;
1696
1697   std::string errStr;
1698   Ok = mgHybrid.Compute( cmd, errStr ); // run
1699
1700   if ( _logInStandardOutput && mgHybrid.IsLibrary() )
1701     std::cout << std::endl << mgHybrid.GetLog() << std::endl;
1702   if ( Ok )
1703     std::cout << "End of Hybrid execution !" << std::endl;
1704
1705   // --------------
1706   // read a result
1707   // --------------
1708   HYBRIDPlugin_Hypothesis::TSetStrings groupsToRemove = HYBRIDPlugin_Hypothesis::GetGroupsToRemove(_hyp);
1709   const bool toMakeGroupsOfDomains = HYBRIDPlugin_Hypothesis::GetToMakeGroupsOfDomains( _hyp );
1710
1711   Ok = Ok && readGMFFile(&mgHybrid,
1712                          aResultFileName.c_str(),
1713                          this,
1714                          theHelper, aNodeByHybridId, aFaceByHybridId, aNodeToHybridIdMap,
1715                          aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId,
1716                          groupsToRemove, toMakeGroupsOfDomains);
1717
1718   updateMeshGroups(theHelper->GetMesh(), groupsToRemove);
1719   removeEmptyGroupsOfDomains( theHelper->GetMesh(), !toMakeGroupsOfDomains );
1720
1721   if ( Ok ) {
1722     HYBRIDPlugin_Hypothesis* that = (HYBRIDPlugin_Hypothesis*)this->_hyp;
1723     if (that)
1724       that->ClearGroupsToRemove();
1725   }
1726   // ---------------------
1727   // remove working files
1728   // ---------------------
1729
1730   if ( Ok )
1731   {
1732     if ( _removeLogOnSuccess )
1733       removeFile( aLogFileName );
1734   }
1735   else if ( mgHybrid.HasLog() )
1736   {
1737     // get problem description from the log file
1738     _Ghs2smdsConvertor conv( aNodeByHybridId );
1739     storeErrorDescription( _logInStandardOutput ? 0 : aLogFileName.c_str(),
1740                            mgHybrid.GetLog(), conv );
1741   }
1742   else {
1743     // the log file is empty
1744     removeFile( aLogFileName );
1745     INFOS( "HYBRID Error, command '" << cmd << "' failed" );
1746     error(COMPERR_ALGO_FAILED, "hybrid: command not found" );
1747   }
1748
1749   if ( !_keepFiles )
1750   {
1751     if (! Ok && _computeCanceled)
1752       removeFile( aLogFileName );
1753     removeFile( aGMFFileName );
1754     removeFile( aResultFileName );
1755     removeFile( aRequiredVerticesFileName );
1756     removeFile( aSolFileName );
1757     removeFile( aResSolFileName );
1758   }
1759   return Ok;
1760 }
1761
1762 void HYBRIDPlugin_HYBRID::CancelCompute()
1763 {
1764   _computeCanceled = true;
1765 #if !defined(WIN32) && !defined(__APPLE__)
1766   std::string cmd = "ps xo pid,args | grep " + _genericName;
1767   //cmd += " | grep -e \"^ *[0-9]\\+ \\+" + HYBRIDPlugin_Hypothesis::GetExeName() + "\"";
1768   cmd += " | awk '{print $1}' | xargs kill -9 > /dev/null 2>&1";
1769   system( cmd.c_str() );
1770 #endif
1771 }
1772
1773 //================================================================================
1774 /*!
1775  * \brief Provide human readable text by error code reported by hybrid
1776  */
1777 //================================================================================
1778
1779 static const char* translateError(const int errNum)
1780 {
1781   switch ( errNum ) {
1782   case 0:
1783     return "error distene 0";
1784   case 1:
1785     return "error distene 1";
1786   }
1787   return "unknown distene error";
1788 }
1789
1790 //================================================================================
1791 /*!
1792  * \brief Retrieve from a string given number of integers
1793  */
1794 //================================================================================
1795
1796 static char* getIds( char* ptr, int nbIds, std::vector<int>& ids )
1797 {
1798   ids.clear();
1799   ids.reserve( nbIds );
1800   while ( nbIds )
1801   {
1802     while ( !isdigit( *ptr )) ++ptr;
1803     if ( ptr[-1] == '-' ) --ptr;
1804     ids.push_back( strtol( ptr, &ptr, 10 ));
1805     --nbIds;
1806   }
1807   return ptr;
1808 }
1809
1810 //================================================================================
1811 /*!
1812  * \brief Retrieve problem description form a log file
1813  *  \retval bool - always false
1814  */
1815 //================================================================================
1816
1817 bool HYBRIDPlugin_HYBRID::storeErrorDescription(const char*                logFile,
1818                                                 const std::string&         log,
1819                                                 const _Ghs2smdsConvertor & toSmdsConvertor )
1820 {
1821   if(_computeCanceled)
1822     return error(SMESH_Comment("interruption initiated by user"));
1823
1824   char* ptr = const_cast<char*>( log.c_str() );
1825   char* buf = ptr, * bufEnd = ptr + log.size();
1826
1827   SMESH_Comment errDescription;
1828
1829   enum { NODE = 1, EDGE, TRIA, VOL, SKIP_ID = 1 };
1830
1831   // look for MeshGems version
1832   // Since "MG-TETRA -- MeshGems 1.1-3 (January, 2013)" error codes change.
1833   // To discriminate old codes from new ones we add 1000000 to the new codes.
1834   // This way value of the new codes is same as absolute value of codes printed
1835   // in the log after "MGMESSAGE" string.
1836   int versionAddition = 0;
1837   {
1838     char* verPtr = ptr;
1839     while ( ++verPtr < bufEnd )
1840     {
1841       if ( strncmp( verPtr, "MG-TETRA -- MeshGems ", 21 ) != 0 )
1842         continue;
1843       if ( strcmp( verPtr, "MG-TETRA -- MeshGems 1.1-3 " ) >= 0 )
1844         versionAddition = 1000000;
1845       ptr = verPtr;
1846       break;
1847     }
1848   }
1849
1850   // look for errors "ERR #"
1851
1852   std::set<std::string> foundErrorStr; // to avoid reporting same error several times
1853   std::set<int>         elemErrorNums; // not to report different types of errors with bad elements
1854   while ( ++ptr < bufEnd )
1855   {
1856     if ( strncmp( ptr, "ERR ", 4 ) != 0 )
1857       continue;
1858
1859     std::list<const SMDS_MeshElement*> badElems;
1860     std::vector<int> nodeIds;
1861
1862     ptr += 4;
1863     char* errBeg = ptr;
1864     int   errNum = strtol(ptr, &ptr, 10) + versionAddition;
1865     // we treat errors enumerated in [SALOME platform 0019316] issue
1866     // and all errors from a new (Release 1.1) MeshGems User Manual
1867     switch ( errNum ) {
1868     case 0015: // The face number (numfac) with vertices (f 1, f 2, f 3) has a null vertex.
1869     case 1005620 : // a too bad quality face is detected. This face is considered degenerated.
1870       ptr = getIds(ptr, SKIP_ID, nodeIds);
1871       ptr = getIds(ptr, TRIA, nodeIds);
1872       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1873       break;
1874     case 1005621 : // a too bad quality face is detected. This face is degenerated.
1875       // hence the is degenerated it is invisible, add its edges in addition
1876       ptr = getIds(ptr, SKIP_ID, nodeIds);
1877       ptr = getIds(ptr, TRIA, nodeIds);
1878       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1879       {
1880         std::vector<int> edgeNodes( nodeIds.begin(), --nodeIds.end() ); // 01
1881         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
1882         edgeNodes[1] = nodeIds[2]; // 02
1883         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
1884         edgeNodes[0] = nodeIds[1]; // 12
1885       }      
1886       break;
1887     case 1000: // Face (f 1, f 2, f 3) appears more than once in the input surface mesh.
1888       // ERR  1000 :  1 3 2
1889     case 1002: // Face (f 1, f 2, f 3) has a vertex negative or null
1890     case 3019: // Constrained face (f 1, f 2, f 3) cannot be enforced
1891     case 1002211: // a face has a vertex negative or null.
1892     case 1005200 : // a surface mesh appears more than once in the input surface mesh.
1893     case 1008423 : // a constrained face cannot be enforced (regeneration phase failed).
1894       ptr = getIds(ptr, TRIA, nodeIds);
1895       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1896       break;
1897     case 1001: // Edge (e1, e2) appears more than once in the input surface mesh
1898     case 3009: // Constrained edge (e1, e2) cannot be enforced (warning).
1899       // ERR  3109 :  EDGE  5 6 UNIQUE
1900     case 3109: // Edge (e1, e2) is unique (i.e., bounds a hole in the surface)
1901     case 1005210 : // an edge appears more than once in the input surface mesh.
1902     case 1005820 : // an edge is unique (i.e., bounds a hole in the surface).
1903     case 1008441 : // a constrained edge cannot be enforced.
1904       ptr = getIds(ptr, EDGE, nodeIds);
1905       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1906       break;
1907     case 2004: // Vertex v1 and vertex v2 are too close to one another or coincident (warning).
1908     case 2014: // at least two points whose distance is dist, i.e., considered as coincident
1909     case 2103: // Vertex v1 and vertex v2 are too close to one another or coincident (warning).
1910       // ERR  2103 :  16 WITH  3
1911     case 1005105 : // two vertices are too close to one another or coincident.
1912     case 1005107: // Two vertices are too close to one another or coincident.
1913       ptr = getIds(ptr, NODE, nodeIds);
1914       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1915       ptr = getIds(ptr, NODE, nodeIds);
1916       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1917       break;
1918     case 2012: // Vertex v1 cannot be inserted (warning).
1919     case 1005106 : // a vertex cannot be inserted.
1920       ptr = getIds(ptr, NODE, nodeIds);
1921       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1922       break;
1923     case 3103: // The surface edge (e1, e2) intersects another surface edge (e3, e4)
1924     case 1005110 : // two surface edges are intersecting.
1925       // ERR  3103 :  1 2 WITH  7 3
1926       ptr = getIds(ptr, EDGE, nodeIds);
1927       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1928       ptr = getIds(ptr, EDGE, nodeIds);
1929       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1930       break;
1931     case 3104: // The surface edge (e1, e2) intersects the surface face (f 1, f 2, f 3)
1932       // ERR  3104 :  9 10 WITH  1 2 3
1933     case 3106: // One surface edge (say e1, e2) intersects a surface face (f 1, f 2, f 3)
1934     case 1005120 : // a surface edge intersects a surface face.
1935       ptr = getIds(ptr, EDGE, nodeIds);
1936       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1937       ptr = getIds(ptr, TRIA, nodeIds);
1938       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1939       break;
1940     case 3105: // One boundary point (say p1) lies within a surface face (f 1, f 2, f 3)
1941       // ERR  3105 :  8 IN  2 3 5
1942     case 1005150 : // a boundary point lies within a surface face.
1943       ptr = getIds(ptr, NODE, nodeIds);
1944       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1945       ptr = getIds(ptr, TRIA, nodeIds);
1946       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1947       break;
1948     case 3107: // One boundary point (say p1) lies within a surface edge (e1, e2) (stop).
1949       // ERR  3107 :  2 IN  4 1
1950     case 1005160 : // a boundary point lies within a surface edge.
1951       ptr = getIds(ptr, NODE, nodeIds);
1952       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1953       ptr = getIds(ptr, EDGE, nodeIds);
1954       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1955       break;
1956     case 9000: // ERR  9000
1957       //  ELEMENT  261 WITH VERTICES :  7 396 -8 242
1958       //  VOLUME   : -1.11325045E+11 W.R.T. EPSILON   0.
1959       // A too small volume element is detected. Are reported the index of the element,
1960       // its four vertex indices, its volume and the tolerance threshold value
1961       ptr = getIds(ptr, SKIP_ID, nodeIds);
1962       ptr = getIds(ptr, VOL, nodeIds);
1963       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1964       // even if all nodes found, volume it most probably invisible,
1965       // add its faces to demonstrate it anyhow
1966       {
1967         std::vector<int> faceNodes( nodeIds.begin(), --nodeIds.end() ); // 012
1968         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
1969         faceNodes[2] = nodeIds[3]; // 013
1970         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
1971         faceNodes[1] = nodeIds[2]; // 023
1972         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
1973         faceNodes[0] = nodeIds[1]; // 123
1974         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
1975       }
1976       break;
1977     case 9001: // ERR  9001
1978       //  %% NUMBER OF NEGATIVE VOLUME TETS  :  1
1979       //  %% THE LARGEST NEGATIVE TET        :   1.75376581E+11
1980       //  %%  NUMBER OF NULL VOLUME TETS     :  0
1981       // There exists at least a null or negative volume element
1982       break;
1983     case 9002:
1984       // There exist n null or negative volume elements
1985       break;
1986     case 9003:
1987       // A too small volume element is detected
1988       break;
1989     case 9102:
1990       // A too bad quality face is detected. This face is considered degenerated,
1991       // its index, its three vertex indices together with its quality value are reported
1992       break; // same as next
1993     case 9112: // ERR  9112
1994       //  FACE   2 WITH VERTICES :  4 2 5
1995       //  SMALL INRADIUS :   0.
1996       // A too bad quality face is detected. This face is degenerated,
1997       // its index, its three vertex indices together with its inradius are reported
1998       ptr = getIds(ptr, SKIP_ID, nodeIds);
1999       ptr = getIds(ptr, TRIA, nodeIds);
2000       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2001       // add triangle edges as it most probably has zero area and hence invisible
2002       {
2003         std::vector<int> edgeNodes(2);
2004         edgeNodes[0] = nodeIds[0]; edgeNodes[1] = nodeIds[1]; // 0-1
2005         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
2006         edgeNodes[1] = nodeIds[2]; // 0-2
2007         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
2008         edgeNodes[0] = nodeIds[1]; // 1-2
2009         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
2010       }
2011       break;
2012     case 1005103 : // the vertices of an element are too close to one another or coincident.
2013       ptr = getIds(ptr, TRIA, nodeIds);
2014       if ( nodeIds.back() == 0 ) // index of the third vertex of the element (0 for an edge)
2015         nodeIds.resize( EDGE );
2016       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2017       break;
2018     }
2019
2020     bool isNewError = foundErrorStr.insert( std::string( errBeg, ptr )).second;
2021     if ( !isNewError )
2022       continue; // not to report same error several times
2023
2024 //     const SMDS_MeshElement* nullElem = 0;
2025 //     bool allElemsOk = ( find( badElems.begin(), badElems.end(), nullElem) == badElems.end());
2026
2027 //     if ( allElemsOk && !badElems.empty() && !elemErrorNums.empty() ) {
2028 //       bool oneMoreErrorType = elemErrorNums.insert( errNum ).second;
2029 //       if ( oneMoreErrorType )
2030 //         continue; // not to report different types of errors with bad elements
2031 //     }
2032
2033     // store bad elements
2034     //if ( allElemsOk ) {
2035       std::list<const SMDS_MeshElement*>::iterator elem = badElems.begin();
2036       for ( ; elem != badElems.end(); ++elem )
2037         addBadInputElement( *elem );
2038       //}
2039
2040     // make error text
2041     std::string text = translateError( errNum );
2042     if ( errDescription.find( text ) == text.npos ) {
2043       if ( !errDescription.empty() )
2044         errDescription << "\n";
2045       errDescription << text;
2046     }
2047
2048   } // end while
2049
2050   if ( errDescription.empty() ) { // no errors found
2051     char msgLic1[] = "connection to server failed";
2052     char msgLic2[] = " Dlim ";
2053     if ( std::search( &buf[0], bufEnd, msgLic1, msgLic1 + strlen(msgLic1)) != bufEnd ||
2054          std::search( &buf[0], bufEnd, msgLic2, msgLic2 + strlen(msgLic2)) != bufEnd )
2055       errDescription << "Licence problems.";
2056     else
2057     {
2058       char msg2[] = "SEGMENTATION FAULT";
2059       if ( std::search( &buf[0], bufEnd, msg2, msg2 + strlen(msg2)) != bufEnd )
2060         errDescription << "hybrid: SEGMENTATION FAULT. ";
2061     }
2062   }
2063
2064   if ( logFile && logFile[0] )
2065   {
2066     if ( errDescription.empty() )
2067       errDescription << "See " << logFile << " for problem description";
2068     else
2069       errDescription << "\nSee " << logFile << " for more information";
2070   }
2071   return error( errDescription );
2072 }
2073
2074 //================================================================================
2075 /*!
2076  * \brief Creates _Ghs2smdsConvertor
2077  */
2078 //================================================================================
2079
2080 _Ghs2smdsConvertor::_Ghs2smdsConvertor( const std::map <int,const SMDS_MeshNode*> & ghs2NodeMap)
2081   :_ghs2NodeMap( & ghs2NodeMap ), _nodeByGhsId( 0 )
2082 {
2083 }
2084
2085 //================================================================================
2086 /*!
2087  * \brief Creates _Ghs2smdsConvertor
2088  */
2089 //================================================================================
2090
2091 _Ghs2smdsConvertor::_Ghs2smdsConvertor( const std::vector <const SMDS_MeshNode*> &  nodeByGhsId)
2092   : _ghs2NodeMap( 0 ), _nodeByGhsId( &nodeByGhsId )
2093 {
2094 }
2095
2096 //================================================================================
2097 /*!
2098  * \brief Return SMDS element by ids of HYBRID nodes
2099  */
2100 //================================================================================
2101
2102 const SMDS_MeshElement* _Ghs2smdsConvertor::getElement(const std::vector<int>& ghsNodes) const
2103 {
2104   size_t nbNodes = ghsNodes.size();
2105   std::vector<const SMDS_MeshNode*> nodes( nbNodes, 0 );
2106   for ( size_t i = 0; i < nbNodes; ++i ) {
2107     int ghsNode = ghsNodes[ i ];
2108     if ( _ghs2NodeMap ) {
2109       std::map <int,const SMDS_MeshNode*>::const_iterator in = _ghs2NodeMap->find( ghsNode);
2110       if ( in == _ghs2NodeMap->end() )
2111         return 0;
2112       nodes[ i ] = in->second;
2113     }
2114     else {
2115       if ( ghsNode < 1 || ghsNode > (int)_nodeByGhsId->size() )
2116         return 0;
2117       nodes[ i ] = (*_nodeByGhsId)[ ghsNode-1 ];
2118     }
2119   }
2120   if ( nbNodes == 1 )
2121     return nodes[0];
2122
2123   if ( nbNodes == 2 ) {
2124     const SMDS_MeshElement* edge= SMDS_Mesh::FindEdge( nodes[0], nodes[1] );
2125     if ( !edge )
2126       edge = new SMDS_LinearEdge( nodes[0], nodes[1] );
2127     return edge;
2128   }
2129   if ( nbNodes == 3 ) {
2130     const SMDS_MeshElement* face = SMDS_Mesh::FindFace( nodes );
2131     if ( !face )
2132       face = new SMDS_FaceOfNodes( nodes[0], nodes[1], nodes[2] );
2133     return face;
2134   }
2135   if ( nbNodes == 4 )
2136     return new SMDS_VolumeOfNodes( nodes[0], nodes[1], nodes[2], nodes[3] );
2137
2138   return 0;
2139 }
2140
2141
2142 //=============================================================================
2143 /*!
2144  *
2145  */
2146 //=============================================================================
2147 bool HYBRIDPlugin_HYBRID::Evaluate(SMESH_Mesh& aMesh,
2148                                  const TopoDS_Shape& aShape,
2149                                  MapShapeNbElems& aResMap)
2150 {
2151   int nbtri = 0, nbqua = 0;
2152   double fullArea = 0.0;
2153   for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
2154     TopoDS_Face F = TopoDS::Face( exp.Current() );
2155     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
2156     MapShapeNbElemsItr anIt = aResMap.find(sm);
2157     if( anIt==aResMap.end() ) {
2158       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2159       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
2160                                             "Submesh can not be evaluated",this));
2161       return false;
2162     }
2163     std::vector<int> aVec = (*anIt).second;
2164     nbtri += Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
2165     nbqua += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
2166     GProp_GProps G;
2167     BRepGProp::SurfaceProperties(F,G);
2168     double anArea = G.Mass();
2169     fullArea += anArea;
2170   }
2171
2172   // collect info from edges
2173   int nb0d_e = 0, nb1d_e = 0;
2174   bool IsQuadratic = false;
2175   bool IsFirst = true;
2176   TopTools_MapOfShape tmpMap;
2177   for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
2178     TopoDS_Edge E = TopoDS::Edge(exp.Current());
2179     if( tmpMap.Contains(E) )
2180       continue;
2181     tmpMap.Add(E);
2182     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
2183     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
2184     std::vector<int> aVec = (*anIt).second;
2185     nb0d_e += aVec[SMDSEntity_Node];
2186     nb1d_e += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
2187     if(IsFirst) {
2188       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
2189       IsFirst = false;
2190     }
2191   }
2192   tmpMap.Clear();
2193
2194   double ELen = sqrt(2.* ( fullArea/(nbtri+nbqua*2) ) / sqrt(3.0) );
2195
2196   GProp_GProps G;
2197   BRepGProp::VolumeProperties(aShape,G);
2198   double aVolume = G.Mass();
2199   double tetrVol = 0.1179*ELen*ELen*ELen;
2200   double CoeffQuality = 0.9;
2201   int nbVols = int(aVolume/tetrVol/CoeffQuality);
2202   int nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
2203   int nb1d_in = (int) ( nbVols*6 - nb1d_e - nb1d_f ) / 5;
2204   std::vector<int> aVec(SMDSEntity_Last);
2205   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
2206   if( IsQuadratic ) {
2207     aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
2208     aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
2209     aVec[SMDSEntity_Quad_Pyramid] = nbqua;
2210   }
2211   else {
2212     aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
2213     aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
2214     aVec[SMDSEntity_Pyramid] = nbqua;
2215   }
2216   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
2217   aResMap.insert(std::make_pair(sm,aVec));
2218
2219   return true;
2220 }
2221
2222 bool HYBRIDPlugin_HYBRID::importGMFMesh(const char* theGMFFileName, SMESH_Mesh& theMesh)
2223 {
2224   SMESH_ComputeErrorPtr err = theMesh.GMFToMesh( theGMFFileName, /*makeRequiredGroups =*/ true );
2225
2226   theMesh.GetMeshDS()->Modified();
2227
2228   return ( !err || err->IsOK());
2229 }
2230
2231 namespace
2232 {
2233   //================================================================================
2234   /*!
2235    * \brief Sub-mesh event listener setting enforced elements as soon as an enforced
2236    *        mesh is loaded
2237    */
2238   struct _EnforcedMeshRestorer : public SMESH_subMeshEventListener
2239   {
2240     _EnforcedMeshRestorer():
2241       SMESH_subMeshEventListener( /*isDeletable = */true, Name() )
2242     {}
2243
2244     //================================================================================
2245     /*!
2246      * \brief Returns an ID of listener
2247      */
2248     static const char* Name() { return "HYBRIDPlugin_HYBRID::_EnforcedMeshRestorer"; }
2249
2250     //================================================================================
2251     /*!
2252      * \brief Treat events of the subMesh
2253      */
2254     void ProcessEvent(const int                       event,
2255                       const int                       eventType,
2256                       SMESH_subMesh*                  subMesh,
2257                       SMESH_subMeshEventListenerData* data,
2258                       const SMESH_Hypothesis*         hyp)
2259     {
2260       if ( SMESH_subMesh::SUBMESH_LOADED == event &&
2261            SMESH_subMesh::COMPUTE_EVENT  == eventType &&
2262            data &&
2263            !data->mySubMeshes.empty() )
2264       {
2265         // An enforced mesh (subMesh->_father) has been loaded from hdf file
2266         if ( HYBRIDPlugin_Hypothesis* hyp = GetGHSHypothesis( data->mySubMeshes.front() ))
2267           hyp->RestoreEnfElemsByMeshes();
2268       }
2269     }
2270     //================================================================================
2271     /*!
2272      * \brief Returns HYBRIDPlugin_Hypothesis used to compute a subMesh
2273      */
2274     static HYBRIDPlugin_Hypothesis* GetGHSHypothesis( SMESH_subMesh* subMesh )
2275     {
2276       SMESH_HypoFilter ghsHypFilter( SMESH_HypoFilter::HasName( "HYBRID_Parameters" ));
2277       return (HYBRIDPlugin_Hypothesis* )
2278         subMesh->GetFather()->GetHypothesis( subMesh->GetSubShape(),
2279                                              ghsHypFilter,
2280                                              /*visitAncestors=*/true);
2281     }
2282   };
2283
2284   //================================================================================
2285   /*!
2286    * \brief Sub-mesh event listener removing empty groups created due to "To make
2287    *        groups of domains".
2288    */
2289   struct _GroupsOfDomainsRemover : public SMESH_subMeshEventListener
2290   {
2291     _GroupsOfDomainsRemover():
2292       SMESH_subMeshEventListener( /*isDeletable = */true,
2293                                   "HYBRIDPlugin_HYBRID::_GroupsOfDomainsRemover" ) {}
2294     /*!
2295      * \brief Treat events of the subMesh
2296      */
2297     void ProcessEvent(const int                       event,
2298                       const int                       eventType,
2299                       SMESH_subMesh*                  subMesh,
2300                       SMESH_subMeshEventListenerData* data,
2301                       const SMESH_Hypothesis*         hyp)
2302     {
2303       if (SMESH_subMesh::ALGO_EVENT == eventType &&
2304           !subMesh->GetAlgo() )
2305       {
2306         removeEmptyGroupsOfDomains( subMesh->GetFather(), /*notEmptyAsWell=*/true );
2307       }
2308     }
2309   };
2310 }
2311
2312 //================================================================================
2313 /*!
2314  * \brief Set an event listener to set enforced elements as soon as an enforced
2315  *        mesh is loaded
2316  */
2317 //================================================================================
2318
2319 void HYBRIDPlugin_HYBRID::SubmeshRestored(SMESH_subMesh* subMesh)
2320 {
2321   if ( HYBRIDPlugin_Hypothesis* hyp = _EnforcedMeshRestorer::GetGHSHypothesis( subMesh ))
2322   {
2323     HYBRIDPlugin_Hypothesis::THYBRIDEnforcedMeshList enfMeshes = hyp->_GetEnforcedMeshes();
2324     HYBRIDPlugin_Hypothesis::THYBRIDEnforcedMeshList::iterator it = enfMeshes.begin();
2325     for(;it != enfMeshes.end();++it) {
2326       HYBRIDPlugin_Hypothesis::THYBRIDEnforcedMesh* enfMesh = *it;
2327       if ( SMESH_Mesh* mesh = GetMeshByPersistentID( enfMesh->persistID ))
2328       {
2329         SMESH_subMesh* smToListen = mesh->GetSubMesh( mesh->GetShapeToMesh() );
2330         // a listener set to smToListen will care of hypothesis stored in SMESH_EventListenerData
2331         subMesh->SetEventListener( new _EnforcedMeshRestorer(),
2332                                    SMESH_subMeshEventListenerData::MakeData( subMesh ),
2333                                    smToListen);
2334       }
2335     }
2336   }
2337 }
2338
2339 //================================================================================
2340 /*!
2341  * \brief Sets an event listener removing empty groups created due to "To make
2342  *        groups of domains".
2343  * \param subMesh - submesh where algo is set
2344  *
2345  * This method is called when a submesh gets HYP_OK algo_state.
2346  * After being set, event listener is notified on each event of a submesh.
2347  */
2348 //================================================================================
2349
2350 void HYBRIDPlugin_HYBRID::SetEventListener(SMESH_subMesh* subMesh)
2351 {
2352   subMesh->SetEventListener( new _GroupsOfDomainsRemover(), 0, subMesh );
2353 }