Salome HOME
f83603b7afb8b3e8427721e8984989c73e904272
[plugins/ghs3dplugin.git] / src / GHS3DPlugin / GHS3DPlugin_GHS3D.cxx
1 // Copyright (C) 2004-2020  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      : GHS3DPlugin_GHS3D.cxx
22 // Created   : 
23 // Author    : Edward AGAPOV, modified by Lioka RAZAFINDRAZAKA (CEA) 09/02/2007
24 // Project   : SALOME
25 //=============================================================================
26 //
27 #include "GHS3DPlugin_GHS3D.hxx"
28 #include "GHS3DPlugin_Hypothesis.hxx"
29 #include "MG_Tetra_API.hxx"
30
31 #include <SMDS_FaceOfNodes.hxx>
32 #include <SMDS_LinearEdge.hxx>
33 #include <SMDS_MeshElement.hxx>
34 #include <SMDS_MeshNode.hxx>
35 #include <SMDS_VolumeOfNodes.hxx>
36 #include <SMESHDS_Group.hxx>
37 #include <SMESHDS_Mesh.hxx>
38 #include <SMESH_Comment.hxx>
39 #include <SMESH_File.hxx>
40 #include <SMESH_Group.hxx>
41 #include <SMESH_HypoFilter.hxx>
42 #include <SMESH_Mesh.hxx>
43 #include <SMESH_MeshAlgos.hxx>
44 #include <SMESH_MeshEditor.hxx>
45 #include <SMESH_MesherHelper.hxx>
46 #include <SMESH_OctreeNode.hxx>
47 #include <SMESH_subMeshEventListener.hxx>
48 #include <StdMeshers_QuadToTriaAdaptor.hxx>
49 #include <StdMeshers_ViscousLayers.hxx>
50
51 #include <BRepAdaptor_Surface.hxx>
52 #include <BRepBndLib.hxx>
53 #include <BRepBuilderAPI_MakeVertex.hxx>
54 #include <BRepClass3d.hxx>
55 #include <BRepClass3d_SolidClassifier.hxx>
56 #include <BRepExtrema_DistShapeShape.hxx>
57 #include <BRepGProp.hxx>
58 #include <BRepTools.hxx>
59 #include <BRep_Tool.hxx>
60 #include <Bnd_Box.hxx>
61 #include <GProp_GProps.hxx>
62 #include <GeomAPI_ProjectPointOnSurf.hxx>
63 #include <Precision.hxx>
64 #include <Standard_ErrorHandler.hxx>
65 #include <Standard_Failure.hxx>
66 #include <Standard_ProgramError.hxx>
67 #include <TopExp.hxx>
68 #include <TopExp_Explorer.hxx>
69 #include <TopTools_IndexedMapOfShape.hxx>
70 #include <TopTools_ListIteratorOfListOfShape.hxx>
71 #include <TopTools_MapOfShape.hxx>
72 #include <TopoDS.hxx>
73 #include <TopoDS_Shell.hxx>
74 #include <TopoDS_Solid.hxx>
75
76 #include <Basics_Utils.hxx>
77 #include <utilities.h>
78
79 #include <algorithm>
80 #include <errno.h>
81
82 #ifdef _DEBUG_
83 //#define _MY_DEBUG_
84 #endif
85
86 #define castToNode(n) static_cast<const SMDS_MeshNode *>( n );
87
88 using namespace std;
89
90 #define HOLE_ID -1
91
92 // flags returning state of enforced entities, returned from writeGMFFile
93 enum InvalidEnforcedFlags { FLAG_BAD_ENF_VERT = 1,
94                             FLAG_BAD_ENF_NODE = 2,
95                             FLAG_BAD_ENF_EDGE = 4,
96                             FLAG_BAD_ENF_TRIA = 8
97 };
98 static std::string flagsToErrorStr( int anInvalidEnforcedFlags )
99 {
100   std::string str;
101   if ( anInvalidEnforcedFlags != 0 )
102   {
103     if ( anInvalidEnforcedFlags & FLAG_BAD_ENF_VERT )
104       str = "There are enforced vertices incorrectly defined.\n";
105     if ( anInvalidEnforcedFlags & FLAG_BAD_ENF_NODE )
106       str += "There are enforced nodes incorrectly defined.\n";
107     if ( anInvalidEnforcedFlags & FLAG_BAD_ENF_EDGE )
108       str += "There are enforced edge incorrectly defined.\n";
109     if ( anInvalidEnforcedFlags & FLAG_BAD_ENF_TRIA )
110       str += "There are enforced triangles incorrectly defined.\n";
111   }
112   return str;
113 }
114
115 typedef const list<const SMDS_MeshFace*> TTriaList;
116
117 static const char theDomainGroupNamePrefix[] = "Domain_";
118
119 static void removeFile( const TCollection_AsciiString& fileName )
120 {
121   try {
122     SMESH_File( fileName.ToCString() ).remove();
123   }
124   catch ( ... ) {
125     MESSAGE("Can't remove file: " << fileName.ToCString() << " ; file does not exist or permission denied");
126   }
127 }
128
129 //=============================================================================
130 /*!
131  *  
132  */
133 //=============================================================================
134
135 GHS3DPlugin_GHS3D::GHS3DPlugin_GHS3D(int hypId, SMESH_Gen* gen)
136   : SMESH_3D_Algo(hypId, gen), _isLibUsed( false )
137 {
138   _name = Name();
139   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
140   _onlyUnaryInput = false; // Compute() will be called on a compound of solids
141   _iShape=0;
142   _nbShape=0;
143   _compatibleHypothesis.push_back( GHS3DPlugin_Hypothesis::GetHypType());
144   _compatibleHypothesis.push_back( StdMeshers_ViscousLayers::GetHypType() );
145   _requireShape = false; // can work without shape
146   
147   _computeCanceled = false;
148   _progressAdvance = 1e-4;
149 }
150
151 //=============================================================================
152 /*!
153  *
154  */
155 //=============================================================================
156
157 GHS3DPlugin_GHS3D::~GHS3DPlugin_GHS3D()
158 {
159 }
160
161 //=============================================================================
162 /*!
163  *
164  */
165 //=============================================================================
166
167 bool GHS3DPlugin_GHS3D::CheckHypothesis ( SMESH_Mesh&         aMesh,
168                                           const TopoDS_Shape& aShape,
169                                           Hypothesis_Status&  aStatus )
170 {
171   aStatus = SMESH_Hypothesis::HYP_OK;
172
173   _hyp = 0;
174   _viscousLayersHyp = 0;
175   _keepFiles = false;
176   _removeLogOnSuccess = true;
177   _logInStandardOutput = false;
178
179   const list <const SMESHDS_Hypothesis * >& hyps =
180     GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
181   list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
182   for ( ; h != hyps.end(); ++h )
183   {
184     if ( !_hyp )
185       _hyp = dynamic_cast< const GHS3DPlugin_Hypothesis*> ( *h );
186     if ( !_viscousLayersHyp )
187       _viscousLayersHyp = dynamic_cast< const StdMeshers_ViscousLayers*> ( *h );
188   }
189   if ( _hyp )
190   {
191     _keepFiles           = _hyp->GetKeepFiles();
192     _removeLogOnSuccess  = _hyp->GetRemoveLogOnSuccess();
193     _logInStandardOutput = _hyp->GetStandardOutputLog();
194   }
195
196   if ( _viscousLayersHyp )
197     error( _viscousLayersHyp->CheckHypothesis( aMesh, aShape, aStatus ));
198
199   return aStatus == HYP_OK;
200 }
201
202
203 //=======================================================================
204 //function : entryToShape
205 //purpose  : 
206 //=======================================================================
207
208 TopoDS_Shape GHS3DPlugin_GHS3D::entryToShape(std::string entry)
209 {
210   if ( SMESH_Gen_i::getStudyServant()->_is_nil() )
211     throw SALOME_Exception("MG-Tetra plugin can't work w/o publishing in the study");
212
213   GEOM::GEOM_Object_var aGeomObj;
214   TopoDS_Shape S = TopoDS_Shape();
215   SALOMEDS::SObject_var aSObj = SMESH_Gen_i::getStudyServant()->FindObjectID( entry.c_str() );
216   if (!aSObj->_is_nil() ) {
217     CORBA::Object_var obj = aSObj->GetObject();
218     aGeomObj = GEOM::GEOM_Object::_narrow(obj);
219     aSObj->UnRegister();
220   }
221   if ( !aGeomObj->_is_nil() )
222     S = SMESH_Gen_i::GetSMESHGen()->GeomObjectToShape( aGeomObj.in() );
223   return S;
224 }
225
226 //================================================================================
227 /*!
228  * \brief returns id of a solid if a triangle defined by the nodes is a temporary face
229  * either on a side facet of pyramid or a top of pentahedron and defines sub-domian
230  * outside the volume; else returns HOLE_ID
231  */
232 //================================================================================
233
234 static int checkTmpFace(const SMDS_MeshNode* node1,
235                         const SMDS_MeshNode* node2,
236                         const SMDS_MeshNode* node3)
237 {
238   // find a pyramid sharing the 3 nodes
239   SMDS_ElemIteratorPtr vIt1 = node1->GetInverseElementIterator(SMDSAbs_Volume);
240   while ( vIt1->more() )
241   {
242     const SMDS_MeshElement* vol = vIt1->next();
243     const int           nbNodes = vol->NbCornerNodes();
244     if ( nbNodes != 5 && nbNodes != 6 ) continue;
245     int i2, i3;
246     if ( (i2 = vol->GetNodeIndex( node2 )) >= 0 &&
247          (i3 = vol->GetNodeIndex( node3 )) >= 0 )
248     {
249       if ( nbNodes == 5 )
250       {
251         // Triangle defines sub-domian inside the pyramid if it's
252         // normal points out of the vol
253
254         // make i2 and i3 hold indices of base nodes of the vol while
255         // keeping the nodes order in the triangle
256         const int iApex = 4;
257         if ( i2 == iApex )
258           i2 = i3, i3 = vol->GetNodeIndex( node1 );
259         else if ( i3 == iApex )
260           i3 = i2, i2 = vol->GetNodeIndex( node1 );
261
262         int i3base = (i2+1) % 4; // next index after i2 within the pyramid base
263         bool isDomainInPyramid = ( i3base != i3 );
264         return isDomainInPyramid ? HOLE_ID : vol->getshapeId();
265       }
266       else
267       {
268         return vol->getshapeId(); // triangle is a prism top
269       }
270     }
271   }
272   return HOLE_ID;
273 }
274
275 //=======================================================================
276 //function : findShapeID
277 //purpose  : find the solid corresponding to MG-Tetra sub-domain following
278 //           the technique proposed in MG-Tetra manual (available within
279 //           MG-Tetra installation) in chapter "B.4 Subdomain (sub-region) assignment".
280 //           In brief: normal of the triangle defined by the given nodes
281 //           points out of the domain it is associated to
282 //=======================================================================
283
284 static int findShapeID(SMESH_Mesh&          mesh,
285                        const SMDS_MeshNode* node1,
286                        const SMDS_MeshNode* node2,
287                        const SMDS_MeshNode* node3,
288                        const bool           toMeshHoles)
289 {
290   const int invalidID = 0;
291   SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
292
293   // face the nodes belong to
294   vector<const SMDS_MeshNode *> nodes(3);
295   nodes[0] = node1;
296   nodes[1] = node2;
297   nodes[2] = node3;
298   const SMDS_MeshElement * face = meshDS->FindElement( nodes, SMDSAbs_Face, /*noMedium=*/true);
299   if ( !face )
300     return checkTmpFace(node1, node2, node3);
301 #ifdef _MY_DEBUG_
302   std::cout << "bnd face " << face->GetID() << " - ";
303 #endif
304   // geom face the face assigned to
305   SMESH_MeshEditor editor(&mesh);
306   int geomFaceID = editor.FindShape( face );
307   if ( !geomFaceID )
308     return checkTmpFace(node1, node2, node3);
309   TopoDS_Shape shape = meshDS->IndexToShape( geomFaceID );
310   if ( shape.IsNull() || shape.ShapeType() != TopAbs_FACE )
311     return invalidID;
312   TopoDS_Face geomFace = TopoDS::Face( shape );
313
314   // solids bounded by geom face
315   TopTools_IndexedMapOfShape solids, shells;
316   TopTools_ListIteratorOfListOfShape ansIt = mesh.GetAncestors(geomFace);
317   for ( ; ansIt.More(); ansIt.Next() ) {
318     switch ( ansIt.Value().ShapeType() ) {
319     case TopAbs_SOLID:
320       solids.Add( ansIt.Value() ); break;
321     case TopAbs_SHELL:
322       shells.Add( ansIt.Value() ); break;
323     default:;
324     }
325   }
326   // analyse found solids
327   if ( solids.Extent() == 0 || shells.Extent() == 0)
328     return invalidID;
329
330   const TopoDS_Solid& solid1 = TopoDS::Solid( solids(1) );
331   if ( solids.Extent() == 1 )
332   {
333     if ( toMeshHoles )
334       return meshDS->ShapeToIndex( solid1 );
335
336     // - Are we at a hole boundary face?
337     if ( shells(1).IsSame( BRepClass3d::OuterShell( solid1 )) )
338     { // - No, but maybe a hole is bound by two shapes? Does shells(1) touch another shell?
339       bool touch = false;
340       TopExp_Explorer eExp( shells(1), TopAbs_EDGE );
341       // check if any edge of shells(1) belongs to another shell
342       for ( ; eExp.More() && !touch; eExp.Next() ) {
343         ansIt = mesh.GetAncestors( eExp.Current() );
344         for ( ; ansIt.More() && !touch; ansIt.Next() ) {
345           if ( ansIt.Value().ShapeType() == TopAbs_SHELL )
346             touch = ( !ansIt.Value().IsSame( shells(1) ));
347         }
348       }
349       if (!touch)
350         return meshDS->ShapeToIndex( solid1 );
351     }
352   }
353   // find orientation of geom face within the first solid
354   TopExp_Explorer fExp( solid1, TopAbs_FACE );
355   for ( ; fExp.More(); fExp.Next() )
356     if ( geomFace.IsSame( fExp.Current() )) {
357       geomFace = TopoDS::Face( fExp.Current() );
358       break;
359     }
360   if ( !fExp.More() )
361     return invalidID; // face not found
362
363   // normale to triangle
364   gp_Pnt node1Pnt ( node1->X(), node1->Y(), node1->Z() );
365   gp_Pnt node2Pnt ( node2->X(), node2->Y(), node2->Z() );
366   gp_Pnt node3Pnt ( node3->X(), node3->Y(), node3->Z() );
367   gp_Vec vec12( node1Pnt, node2Pnt );
368   gp_Vec vec13( node1Pnt, node3Pnt );
369   gp_Vec meshNormal = vec12 ^ vec13;
370   if ( meshNormal.SquareMagnitude() < DBL_MIN )
371     return invalidID;
372
373   // get normale to geomFace at any node
374   bool geomNormalOK = false;
375   gp_Vec geomNormal;
376   SMESH_MesherHelper helper( mesh ); helper.SetSubShape( geomFace );
377   for ( int i = 0; !geomNormalOK && i < 3; ++i )
378   {
379     // find UV of i-th node on geomFace
380     const SMDS_MeshNode* nNotOnSeamEdge = 0;
381     if ( helper.IsSeamShape( nodes[i]->getshapeId() )) {
382       if ( helper.IsSeamShape( nodes[(i+1)%3]->getshapeId() ))
383         nNotOnSeamEdge = nodes[(i+2)%3];
384       else
385         nNotOnSeamEdge = nodes[(i+1)%3];
386     }
387     bool uvOK = true;
388     gp_XY uv = helper.GetNodeUV( geomFace, nodes[i], nNotOnSeamEdge, &uvOK );
389     // check that uv is correct
390     if (uvOK) {
391       double tol = 1e-6;
392       TopoDS_Shape nodeShape = helper.GetSubShapeByNode( nodes[i], meshDS );
393       if ( !nodeShape.IsNull() )
394         switch ( nodeShape.ShapeType() )
395         {
396         case TopAbs_FACE:   tol = BRep_Tool::Tolerance( TopoDS::Face( nodeShape )); break;
397         case TopAbs_EDGE:   tol = BRep_Tool::Tolerance( TopoDS::Edge( nodeShape )); break;
398         case TopAbs_VERTEX: tol = BRep_Tool::Tolerance( TopoDS::Vertex( nodeShape )); break;
399         default:;
400         }
401       gp_Pnt nodePnt ( nodes[i]->X(), nodes[i]->Y(), nodes[i]->Z() );
402       BRepAdaptor_Surface surface( geomFace );
403       uvOK = ( nodePnt.Distance( surface.Value( uv.X(), uv.Y() )) < 2 * tol );
404       if ( uvOK ) {
405         // normale to geomFace at UV
406         gp_Vec du, dv;
407         surface.D1( uv.X(), uv.Y(), nodePnt, du, dv );
408         geomNormal = du ^ dv;
409         if ( geomFace.Orientation() == TopAbs_REVERSED )
410           geomNormal.Reverse();
411         geomNormalOK = ( geomNormal.SquareMagnitude() > DBL_MIN * 1e3 );
412       }
413     }
414   }
415   if ( !geomNormalOK)
416     return invalidID;
417
418   // compare normals
419   bool isReverse = ( meshNormal * geomNormal ) < 0;
420   if ( !isReverse )
421     return meshDS->ShapeToIndex( solid1 );
422
423   if ( solids.Extent() == 1 )
424     return HOLE_ID; // we are inside a hole
425   else
426     return meshDS->ShapeToIndex( solids(2) );
427 }
428
429 //=======================================================================
430 //function : addElemInMeshGroup
431 //purpose  : Update or create groups in mesh
432 //=======================================================================
433
434 static void addElemInMeshGroup(SMESH_Mesh*             theMesh,
435                                const SMDS_MeshElement* anElem,
436                                std::string&            groupName,
437                                std::set<std::string>&  groupsToRemove)
438 {
439   if ( !anElem ) return; // issue 0021776
440
441   bool groupDone = false;
442   SMESH_Mesh::GroupIteratorPtr grIt = theMesh->GetGroups();
443   while (grIt->more()) {
444     SMESH_Group * group = grIt->next();
445     if ( !group ) continue;
446     SMESHDS_GroupBase* groupDS = group->GetGroupDS();
447     if ( !groupDS ) continue;
448     if ( groupDS->GetType()==anElem->GetType() &&groupName.compare(group->GetName())==0) {
449       SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
450       aGroupDS->SMDSGroup().Add(anElem);
451       groupDone = true;
452       break;
453     }
454   }
455   
456   if (!groupDone)
457   {
458     SMESH_Group* aGroup = theMesh->AddGroup(anElem->GetType(), groupName.c_str());
459     aGroup->SetName( groupName.c_str() );
460     SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
461     aGroupDS->SMDSGroup().Add(anElem);
462     groupDone = true;
463   }
464   if (!groupDone)
465     throw SALOME_Exception(LOCALIZED("A given element was not added to a group"));
466 }
467
468
469 //=======================================================================
470 //function : updateMeshGroups
471 //purpose  : Update or create groups in mesh
472 //=======================================================================
473
474 static void updateMeshGroups(SMESH_Mesh* theMesh, std::set<std::string> groupsToRemove)
475 {
476   SMESH_Mesh::GroupIteratorPtr grIt = theMesh->GetGroups();
477   while (grIt->more()) {
478     SMESH_Group * group = grIt->next();
479     if ( !group ) continue;
480     SMESHDS_GroupBase* groupDS = group->GetGroupDS();
481     if ( !groupDS ) continue;
482     std::string currentGroupName = (string)group->GetName();
483     if (groupDS->IsEmpty() && groupsToRemove.find(currentGroupName) != groupsToRemove.end()) {
484       // Previous group created by enforced elements
485       theMesh->RemoveGroup(groupDS->GetID());
486     }
487   }
488 }
489
490 //=======================================================================
491 //function : removeEmptyGroupsOfDomains
492 //purpose  : remove empty groups named "Domain_nb" created due to
493 //           "To make groups of domains" option.
494 //=======================================================================
495
496 static void removeEmptyGroupsOfDomains(SMESH_Mesh* mesh,
497                                        bool        notEmptyAsWell = false)
498 {
499   const char* refName = theDomainGroupNamePrefix;
500   const size_t refLen = strlen( theDomainGroupNamePrefix );
501
502   std::list<int> groupIDs = mesh->GetGroupIds();
503   std::list<int>::const_iterator id = groupIDs.begin();
504   for ( ; id != groupIDs.end(); ++id )
505   {
506     SMESH_Group* group = mesh->GetGroup( *id );
507     if ( !group || ( !group->GetGroupDS()->IsEmpty() && !notEmptyAsWell ))
508       continue;
509     const char* name = group->GetName();
510     char* end;
511     // check the name
512     if ( strncmp( name, refName, refLen ) == 0 && // starts from refName;
513          isdigit( *( name + refLen )) &&          // refName is followed by a digit;
514          strtol( name + refLen, &end, 10) >= 0 && // there are only digits ...
515          *end == '\0')                            // ... till a string end.
516     {
517       mesh->RemoveGroup( *id );
518     }
519   }
520 }
521
522 //================================================================================
523 /*!
524  * \brief Create the groups corresponding to domains
525  */
526 //================================================================================
527
528 static void makeDomainGroups( std::vector< std::vector< const SMDS_MeshElement* > >& elemsOfDomain,
529                               SMESH_MesherHelper*                                    theHelper)
530 {
531   // int nbDomains = 0;
532   // for ( size_t i = 0; i < elemsOfDomain.size(); ++i )
533   //   nbDomains += ( elemsOfDomain[i].size() > 0 );
534
535   // if ( nbDomains > 1 )
536   for ( size_t iDomain = 0; iDomain < elemsOfDomain.size(); ++iDomain )
537   {
538     std::vector< const SMDS_MeshElement* > & elems = elemsOfDomain[ iDomain ];
539     if ( elems.empty() ) continue;
540
541     // find existing groups
542     std::vector< SMESH_Group* > groupOfType( SMDSAbs_NbElementTypes, (SMESH_Group*)NULL );
543     const std::string domainName = ( SMESH_Comment( theDomainGroupNamePrefix ) << iDomain );
544     SMESH_Mesh::GroupIteratorPtr groupIt = theHelper->GetMesh()->GetGroups();
545     while ( groupIt->more() )
546     {
547       SMESH_Group* group = groupIt->next();
548       if ( domainName == group->GetName() &&
549            dynamic_cast< SMESHDS_Group* >( group->GetGroupDS()) )
550         groupOfType[ group->GetGroupDS()->GetType() ] = group;
551     }
552     // create and fill the groups
553     size_t iElem = 0;
554     do
555     {
556       SMESH_Group* group = groupOfType[ elems[ iElem ]->GetType() ];
557       if ( !group )
558         group = theHelper->GetMesh()->AddGroup( elems[ iElem ]->GetType(),
559                                                 domainName.c_str() );
560       SMDS_MeshGroup& groupDS =
561         static_cast< SMESHDS_Group* >( group->GetGroupDS() )->SMDSGroup();
562
563       while ( iElem < elems.size() && groupDS.Add( elems[iElem] ))
564         ++iElem;
565
566     } while ( iElem < elems.size() );
567   }
568 }
569
570 //=======================================================================
571 //function : readGMFFile
572 //purpose  : read GMF file w/o geometry associated to mesh
573 //=======================================================================
574
575 static bool readGMFFile(MG_Tetra_API*                   MGOutput,
576                         const char*                     theFile,
577                         GHS3DPlugin_GHS3D*              theAlgo,
578                         SMESH_MesherHelper*             theHelper,
579                         std::vector <const SMDS_MeshNode*> &    theNodeByGhs3dId,
580                         std::vector <const SMDS_MeshElement*> & theFaceByGhs3dId,
581                         map<const SMDS_MeshNode*,int> & theNodeToGhs3dIdMap,
582                         std::vector<std::string> &      aNodeGroupByGhs3dId,
583                         std::vector<std::string> &      anEdgeGroupByGhs3dId,
584                         std::vector<std::string> &      aFaceGroupByGhs3dId,
585                         std::set<std::string> &         groupsToRemove,
586                         bool                            toMakeGroupsOfDomains=false,
587                         bool                            toMeshHoles=true)
588 {
589   std::string tmpStr;
590   SMESHDS_Mesh* theMeshDS = theHelper->GetMeshDS();
591   const bool hasGeom = ( theHelper->GetMesh()->HasShapeToMesh() );
592
593   int nbInitialNodes = theNodeByGhs3dId.size();
594   
595 #ifdef _MY_DEBUG_
596   const bool isQuadMesh = 
597     theHelper->GetMesh()->NbEdges( ORDER_QUADRATIC ) ||
598     theHelper->GetMesh()->NbFaces( ORDER_QUADRATIC ) ||
599     theHelper->GetMesh()->NbVolumes( ORDER_QUADRATIC );
600   std::cout << "theNodeByGhs3dId.size(): " << nbInitialNodes << std::endl;
601   std::cout << "theHelper->GetMesh()->NbNodes(): " << theMeshDS->NbNodes() << std::endl;
602   std::cout << "isQuadMesh: " << isQuadMesh << std::endl;
603 #endif
604   
605   // ---------------------------------
606   // Read generated elements and nodes
607   // ---------------------------------
608
609   int nbElem = 0, nbRef = 0;
610   int aGMFNodeID = 0;
611   std::vector< const SMDS_MeshNode*> GMFNode;
612 #ifdef _MY_DEBUG_
613   std::map<int, std::set<int> > subdomainId2tetraId;
614 #endif
615   std::map <GmfKwdCod,int> tabRef;
616   const bool force3d = !hasGeom;
617   const int  noID    = 0;
618
619   tabRef[GmfVertices]       = 3; // for new nodes and enforced nodes
620   tabRef[GmfCorners]        = 1;
621   tabRef[GmfEdges]          = 2; // for enforced edges
622   tabRef[GmfRidges]         = 1;
623   tabRef[GmfTriangles]      = 3; // for enforced faces
624   tabRef[GmfQuadrilaterals] = 4;
625   tabRef[GmfTetrahedra]     = 4; // for new tetras
626   tabRef[GmfHexahedra]      = 8;
627
628   int ver, dim;
629   int InpMsh = MGOutput->GmfOpenMesh( theFile, GmfRead, &ver, &dim);
630   if (!InpMsh)
631     return false;
632
633   // Read ids of domains
634   vector< int > solidIDByDomain;
635   if ( hasGeom )
636   {
637     int solid1; // id used in case of 1 domain or some reading failure
638     if ( theHelper->GetSubShape().ShapeType() == TopAbs_SOLID )
639       solid1 = theHelper->GetSubShapeID();
640     else
641       solid1 = theMeshDS->ShapeToIndex
642         ( TopExp_Explorer( theHelper->GetSubShape(), TopAbs_SOLID ).Current() );
643
644     int nbDomains = MGOutput->GmfStatKwd( InpMsh, GmfSubDomainFromGeom );
645     if ( nbDomains > 1 )
646     {
647       solidIDByDomain.resize( nbDomains+1, theHelper->GetSubShapeID() );
648       int faceNbNodes, faceIndex, orientation, domainNb;
649       MGOutput->GmfGotoKwd( InpMsh, GmfSubDomainFromGeom );
650       for ( int i = 0; i < nbDomains; ++i )
651       {
652         faceIndex = 0;
653         MGOutput->GmfGetLin( InpMsh, GmfSubDomainFromGeom,
654                    &faceNbNodes, &faceIndex, &orientation, &domainNb, i);
655         solidIDByDomain[ domainNb ] = 1;
656         if ( 0 < faceIndex && faceIndex-1 < (int)theFaceByGhs3dId.size() )
657         {
658           const SMDS_MeshElement* face = theFaceByGhs3dId[ faceIndex-1 ];
659           const SMDS_MeshNode* nn[3] = { face->GetNode(0),
660                                          face->GetNode(1),
661                                          face->GetNode(2) };
662           if ( orientation < 0 )
663             std::swap( nn[1], nn[2] );
664           solidIDByDomain[ domainNb ] =
665             findShapeID( *theHelper->GetMesh(), nn[0], nn[1], nn[2], toMeshHoles );
666           if ( solidIDByDomain[ domainNb ] > 0 )
667           {
668 #ifdef _MY_DEBUG_
669             std::cout << "solid " << solidIDByDomain[ domainNb ] << std::endl;
670 #endif
671             const TopoDS_Shape& foundShape = theMeshDS->IndexToShape( solidIDByDomain[ domainNb ] );
672             if ( ! theHelper->IsSubShape( foundShape, theHelper->GetSubShape() ))
673               solidIDByDomain[ domainNb ] = HOLE_ID;
674           }
675         }
676       }
677     }
678     if ( solidIDByDomain.size() < 2 )
679       solidIDByDomain.resize( 2, solid1 );
680   }
681
682   // Issue 0020682. Avoid creating nodes and tetras at place where
683   // volumic elements already exist
684   SMESH_ElementSearcher* elemSearcher = 0;
685   std::vector< const SMDS_MeshElement* > foundVolumes;
686   if ( !hasGeom && theHelper->GetMesh()->NbVolumes() > 0 )
687     elemSearcher = SMESH_MeshAlgos::GetElementSearcher( *theMeshDS );
688   auto_ptr< SMESH_ElementSearcher > elemSearcherDeleter( elemSearcher );
689
690   // IMP 0022172: [CEA 790] create the groups corresponding to domains
691   std::vector< std::vector< const SMDS_MeshElement* > > elemsOfDomain;
692
693   int nbVertices = MGOutput->GmfStatKwd( InpMsh, GmfVertices ) - nbInitialNodes;
694   if ( nbVertices < 0 )
695     return false;
696   GMFNode.resize( nbVertices + 1 );
697
698   std::map <GmfKwdCod,int>::const_iterator it = tabRef.begin();
699   for ( ; it != tabRef.end() ; ++it)
700   {
701     if(theAlgo->computeCanceled()) {
702       return false;
703     }
704     int dummy, solidID;
705     GmfKwdCod token = it->first;
706     nbRef           = it->second;
707
708     nbElem = MGOutput->GmfStatKwd( InpMsh, token);
709     if (nbElem > 0) {
710       MGOutput->GmfGotoKwd( InpMsh, token);
711       std::cout << "Read " << nbElem;
712     }
713     else
714       continue;
715
716     std::vector<int> id (nbElem*tabRef[token]); // node ids
717     std::vector<int> domainID( nbElem ); // domain
718
719     if (token == GmfVertices) {
720       (nbElem <= 1) ? tmpStr = " vertex" : tmpStr = " vertices";
721 //       std::cout << nbInitialNodes << " from input mesh " << std::endl;
722
723       // Remove orphan nodes from previous enforced mesh which was cleared
724 //       if ( nbElem < nbMeshNodes ) {
725 //         const SMDS_MeshNode* node;
726 //         SMDS_NodeIteratorPtr nodeIt = theMeshDS->nodesIterator();
727 //         while ( nodeIt->more() )
728 //         {
729 //           node = nodeIt->next();
730 //           if (theNodeToGhs3dIdMap.find(node) != theNodeToGhs3dIdMap.end())
731 //             theMeshDS->RemoveNode(node);
732 //         }
733 //       }
734
735       
736       int aGMFID;
737
738       float VerTab_f[3];
739       double x, y, z;
740       const SMDS_MeshNode * aGMFNode;
741
742       for ( int iElem = 0; iElem < nbElem; iElem++ ) {
743         if(theAlgo->computeCanceled()) {
744           return false;
745         }
746         if (ver == GmfFloat) {
747           MGOutput->GmfGetLin( InpMsh, token, &VerTab_f[0], &VerTab_f[1], &VerTab_f[2], &dummy);
748           x = VerTab_f[0];
749           y = VerTab_f[1];
750           z = VerTab_f[2];
751         }
752         else {
753           MGOutput->GmfGetLin( InpMsh, token, &x, &y, &z, &dummy);
754         }
755         if (iElem >= nbInitialNodes) {
756           if ( elemSearcher &&
757                 elemSearcher->FindElementsByPoint( gp_Pnt(x,y,z), SMDSAbs_Volume, foundVolumes))
758             aGMFNode = 0;
759           else
760             aGMFNode = theHelper->AddNode(x, y, z);
761           
762           aGMFID = iElem -nbInitialNodes +1;
763           GMFNode[ aGMFID ] = aGMFNode;
764           if (aGMFID-1 < (int)aNodeGroupByGhs3dId.size() && !aNodeGroupByGhs3dId.at(aGMFID-1).empty())
765             addElemInMeshGroup(theHelper->GetMesh(), aGMFNode, aNodeGroupByGhs3dId.at(aGMFID-1), groupsToRemove);
766         }
767       }
768     }
769     else if (token == GmfCorners && nbElem > 0) {
770       (nbElem <= 1) ? tmpStr = " corner" : tmpStr = " corners";
771       for ( int iElem = 0; iElem < nbElem; iElem++ )
772         MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]]);
773     }
774     else if (token == GmfRidges && nbElem > 0) {
775       (nbElem <= 1) ? tmpStr = " ridge" : tmpStr = " ridges";
776       for ( int iElem = 0; iElem < nbElem; iElem++ )
777         MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]]);
778     }
779     else if (token == GmfEdges && nbElem > 0) {
780       (nbElem <= 1) ? tmpStr = " edge" : tmpStr = " edges";
781       for ( int iElem = 0; iElem < nbElem; iElem++ )
782         MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &domainID[iElem]);
783     }
784     else if (token == GmfTriangles && nbElem > 0) {
785       (nbElem <= 1) ? tmpStr = " triangle" : tmpStr = " triangles";
786       for ( int iElem = 0; iElem < nbElem; iElem++ )
787         MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &domainID[iElem]);
788     }
789     else if (token == GmfQuadrilaterals && nbElem > 0) {
790       (nbElem <= 1) ? tmpStr = " Quadrilateral" : tmpStr = " Quadrilaterals";
791       for ( int iElem = 0; iElem < nbElem; iElem++ )
792         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]);
793     }
794     else if (token == GmfTetrahedra && nbElem > 0) {
795       (nbElem <= 1) ? tmpStr = " Tetrahedron" : tmpStr = " Tetrahedra";
796       for ( int iElem = 0; iElem < nbElem; iElem++ ) {
797         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]);
798 #ifdef _MY_DEBUG_
799         subdomainId2tetraId[dummy].insert(iElem+1);
800 #endif
801       }
802     }
803     else if (token == GmfHexahedra && nbElem > 0) {
804       (nbElem <= 1) ? tmpStr = " Hexahedron" : tmpStr = " Hexahedra";
805       for ( int iElem = 0; iElem < nbElem; iElem++ )
806         MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3],
807                   &id[iElem*tabRef[token]+4], &id[iElem*tabRef[token]+5], &id[iElem*tabRef[token]+6], &id[iElem*tabRef[token]+7], &domainID[iElem]);
808     }
809     std::cout << tmpStr << std::endl;
810     std::cout << std::endl;
811
812     switch (token) {
813     case GmfCorners:
814     case GmfRidges:
815     case GmfEdges:
816     case GmfTriangles:
817     case GmfQuadrilaterals:
818     case GmfTetrahedra:
819     case GmfHexahedra:
820     {
821       std::vector< const SMDS_MeshNode* > node( nbRef );
822       std::vector< int >          nodeID( nbRef );
823       std::vector< SMDS_MeshNode* > enfNode( nbRef );
824       const SMDS_MeshElement* aCreatedElem;
825
826       for ( int iElem = 0; iElem < nbElem; iElem++ )
827       {
828         if(theAlgo->computeCanceled()) {
829           return false;
830         }
831         // Check if elem is already in input mesh. If yes => skip
832         bool fullyCreatedElement = false; // if at least one of the nodes was created
833         for ( int iRef = 0; iRef < nbRef; iRef++ )
834         {
835           aGMFNodeID = id[iElem*tabRef[token]+iRef]; // read nbRef aGMFNodeID
836           if (aGMFNodeID <= nbInitialNodes) // input nodes
837           {
838             aGMFNodeID--;
839             node[ iRef ] = theNodeByGhs3dId[aGMFNodeID];
840           }
841           else
842           {
843             fullyCreatedElement = true;
844             aGMFNodeID -= nbInitialNodes;
845             nodeID[ iRef ] = aGMFNodeID ;
846             node  [ iRef ] = GMFNode[ aGMFNodeID ];
847           }
848         }
849         aCreatedElem = 0;
850         switch (token)
851         {
852         case GmfEdges:
853           if (fullyCreatedElement) {
854             aCreatedElem = theHelper->AddEdge( node[0], node[1], noID, force3d );
855             if (anEdgeGroupByGhs3dId.size() && !anEdgeGroupByGhs3dId[iElem].empty())
856               addElemInMeshGroup(theHelper->GetMesh(), aCreatedElem, anEdgeGroupByGhs3dId[iElem], groupsToRemove);
857           }
858           break;
859         case GmfTriangles:
860           if (fullyCreatedElement) {
861             aCreatedElem = theHelper->AddFace( node[0], node[1], node[2], noID, force3d );
862             if (aFaceGroupByGhs3dId.size() && !aFaceGroupByGhs3dId[iElem].empty())
863               addElemInMeshGroup(theHelper->GetMesh(), aCreatedElem, aFaceGroupByGhs3dId[iElem], groupsToRemove);
864           }
865           break;
866         case GmfQuadrilaterals:
867           if (fullyCreatedElement) {
868             aCreatedElem = theHelper->AddFace( node[0], node[1], node[2], node[3], noID, force3d );
869           }
870           break;
871         case GmfTetrahedra:
872           if ( hasGeom )
873           {
874             solidID = solidIDByDomain[ domainID[iElem]];
875             if ( solidID != HOLE_ID )
876             {
877               aCreatedElem = theHelper->AddVolume( node[1], node[0], node[2], node[3],
878                                                    noID, force3d );
879               theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
880               for ( int iN = 0; iN < 4; ++iN )
881                 if ( node[iN]->getshapeId() < 1 )
882                   theMeshDS->SetNodeInVolume( node[iN], solidID );
883             }
884           }
885           else
886           {
887             if ( elemSearcher ) {
888               // Issue 0020682. Avoid creating nodes and tetras at place where
889               // volumic elements already exist
890               if ( !node[1] || !node[0] || !node[2] || !node[3] )
891                 continue;
892               if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
893                                                       SMESH_TNodeXYZ(node[1]) +
894                                                       SMESH_TNodeXYZ(node[2]) +
895                                                       SMESH_TNodeXYZ(node[3]) ) / 4.,
896                                                      SMDSAbs_Volume, foundVolumes ))
897                 break;
898             }
899             aCreatedElem = theHelper->AddVolume( node[1], node[0], node[2], node[3],
900                                                  noID, force3d );
901           }
902           break;
903         case GmfHexahedra:
904           if ( hasGeom )
905           {
906             solidID = solidIDByDomain[ domainID[iElem]];
907             if ( solidID != HOLE_ID )
908             {
909               aCreatedElem = theHelper->AddVolume( node[0], node[3], node[2], node[1],
910                                                    node[4], node[7], node[6], node[5],
911                                                    noID, force3d );
912               theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
913               for ( int iN = 0; iN < 8; ++iN )
914                 if ( node[iN]->getshapeId() < 1 )
915                   theMeshDS->SetNodeInVolume( node[iN], solidID );
916             }
917           }
918           else
919           {
920             if ( elemSearcher ) {
921               // Issue 0020682. Avoid creating nodes and tetras at place where
922               // volumic elements already exist
923               if ( !node[1] || !node[0] || !node[2] || !node[3] || !node[4] || !node[5] || !node[6] || !node[7])
924                 continue;
925               if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
926                                                       SMESH_TNodeXYZ(node[1]) +
927                                                       SMESH_TNodeXYZ(node[2]) +
928                                                       SMESH_TNodeXYZ(node[3]) +
929                                                       SMESH_TNodeXYZ(node[4]) +
930                                                       SMESH_TNodeXYZ(node[5]) +
931                                                       SMESH_TNodeXYZ(node[6]) +
932                                                       SMESH_TNodeXYZ(node[7])) / 8.,
933                                                      SMDSAbs_Volume, foundVolumes ))
934                 break;
935             }
936             aCreatedElem = theHelper->AddVolume( node[0], node[3], node[2], node[1],
937                                                  node[4], node[7], node[6], node[5],
938                                                  noID, force3d );
939           }
940           break;
941         default: continue;
942         } // switch (token)
943
944         // care about medium nodes
945         if ( aCreatedElem &&
946              aCreatedElem->IsQuadratic() &&
947              ( solidID = aCreatedElem->getshapeId() ) > 0 )
948         {
949           int iN = aCreatedElem->NbCornerNodes(), nbN = aCreatedElem->NbNodes();
950           for ( ; iN < nbN; ++iN )
951           {
952             const SMDS_MeshNode* n = aCreatedElem->GetNode(iN);
953             if ( n->getshapeId() < 1 )
954               theMeshDS->SetNodeInVolume( n, solidID );
955           }
956         }
957
958         if ( aCreatedElem && toMakeGroupsOfDomains )
959         {
960           if ( domainID[iElem] >= (int) elemsOfDomain.size() )
961             elemsOfDomain.resize( domainID[iElem] + 1 );
962           elemsOfDomain[ domainID[iElem] ].push_back( aCreatedElem );
963         }
964       } // loop on elements of one type
965       break;
966     } // case ...
967     default:;
968     } // switch (token)
969   } // loop on tabRef
970
971   // remove nodes in holes
972   if ( hasGeom )
973   {
974     for ( int i = 1; i <= nbVertices; ++i )
975       if ( GMFNode[i]->NbInverseElements() == 0 )
976         theMeshDS->RemoveFreeNode( GMFNode[i], /*sm=*/0, /*fromGroups=*/false );
977   }
978
979   MGOutput->GmfCloseMesh( InpMsh);
980
981   // 0022172: [CEA 790] create the groups corresponding to domains
982   if ( toMakeGroupsOfDomains )
983     makeDomainGroups( elemsOfDomain, theHelper );
984
985 #ifdef _MY_DEBUG_
986   std::map<int, std::set<int> >::const_iterator subdomainIt = subdomainId2tetraId.begin();
987   TCollection_AsciiString aSubdomainFileName = theFile;
988   aSubdomainFileName = aSubdomainFileName + ".subdomain";
989   ofstream aSubdomainFile  ( aSubdomainFileName.ToCString()  , ios::out);
990
991   aSubdomainFile << "Nb subdomains " << subdomainId2tetraId.size() << std::endl;
992   for(;subdomainIt != subdomainId2tetraId.end() ; ++subdomainIt) {
993     int subdomainId = subdomainIt->first;
994     std::set<int> tetraIds = subdomainIt->second;
995     std::set<int>::const_iterator tetraIdsIt = tetraIds.begin();
996     aSubdomainFile << subdomainId << std::endl;
997     for(;tetraIdsIt != tetraIds.end() ; ++tetraIdsIt) {
998       aSubdomainFile << (*tetraIdsIt) << " ";
999     }
1000     aSubdomainFile << std::endl;
1001   }
1002   aSubdomainFile.close();
1003 #endif  
1004   
1005   return true;
1006 }
1007
1008
1009 static bool writeGMFFile(MG_Tetra_API*                                   MGInput,
1010                          const char*                                     theMeshFileName,
1011                          const char*                                     theRequiredFileName,
1012                          const char*                                     theSolFileName,
1013                          const SMESH_ProxyMesh&                          theProxyMesh,
1014                          SMESH_MesherHelper&                             theHelper,
1015                          std::vector <const SMDS_MeshNode*> &            theNodeByGhs3dId,
1016                          std::vector <const SMDS_MeshElement*> &         theFaceByGhs3dId,
1017                          std::map<const SMDS_MeshNode*,int> &            aNodeToGhs3dIdMap,
1018                          std::vector<std::string> &                      aNodeGroupByGhs3dId,
1019                          std::vector<std::string> &                      anEdgeGroupByGhs3dId,
1020                          std::vector<std::string> &                      aFaceGroupByGhs3dId,
1021                          GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap & theEnforcedNodes,
1022                          GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedEdges,
1023                          GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedTriangles,
1024                          std::map<std::vector<double>, std::string> &    enfVerticesWithGroup,
1025                          GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues & theEnforcedVertices,
1026                          int &                                           theInvalidEnforcedFlags)
1027 {
1028   std::string tmpStr;
1029   int idx, idxRequired = 0, idxSol = 0;
1030   const int dummyint = 0;
1031   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues::const_iterator vertexIt;
1032   std::vector<double> enfVertexSizes;
1033   const SMDS_MeshElement* elem;
1034   TIDSortedElemSet anElemSet, theKeptEnforcedEdges, theKeptEnforcedTriangles;
1035   SMDS_ElemIteratorPtr nodeIt;
1036   std::vector <const SMDS_MeshNode*> theEnforcedNodeByGhs3dId;
1037   map<const SMDS_MeshNode*,int> anEnforcedNodeToGhs3dIdMap, anExistingEnforcedNodeToGhs3dIdMap;
1038   std::vector< const SMDS_MeshElement* > foundElems;
1039   map<const SMDS_MeshNode*,TopAbs_State> aNodeToTopAbs_StateMap;
1040   int nbFoundElems;
1041   GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap::iterator elemIt;
1042   TIDSortedElemSet::iterator elemSetIt;
1043   bool isOK;
1044   SMESH_Mesh* theMesh = theHelper.GetMesh();
1045   const bool hasGeom = theMesh->HasShapeToMesh();
1046   SMESHUtils::Deleter< SMESH_ElementSearcher > pntCls
1047     ( SMESH_MeshAlgos::GetElementSearcher(*theMesh->GetMeshDS()));
1048   
1049   int nbEnforcedVertices = theEnforcedVertices.size();
1050   theInvalidEnforcedFlags = 0;
1051
1052   // count faces
1053   int nbFaces = theProxyMesh.NbFaces();
1054   int nbNodes;
1055   theFaceByGhs3dId.reserve( nbFaces );
1056   
1057   // groups management
1058   int usedEnforcedNodes = 0;
1059   std::string gn = "";
1060
1061   if ( nbFaces == 0 )
1062     return false;
1063   
1064   idx = MGInput->GmfOpenMesh( theMeshFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1065   if (!idx)
1066     return false;
1067   
1068   /* ========================== FACES ========================== */
1069   /* TRIANGLES ========================== */
1070   SMDS_ElemIteratorPtr eIt =
1071     hasGeom ? theProxyMesh.GetFaces( theHelper.GetSubShape()) : theProxyMesh.GetFaces();
1072   while ( eIt->more() )
1073   {
1074     elem = eIt->next();
1075     anElemSet.insert(elem);
1076     nodeIt = elem->nodesIterator();
1077     nbNodes = elem->NbCornerNodes();
1078     while ( nodeIt->more() && nbNodes--)
1079     {
1080       // find MG-Tetra ID
1081       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1082       int newId = aNodeToGhs3dIdMap.size() + 1; // MG-Tetra ids count from 1
1083       aNodeToGhs3dIdMap.insert( make_pair( node, newId ));
1084     }
1085   }
1086   if ( !anElemSet.empty() &&
1087        (*anElemSet.begin())->IsQuadratic() &&
1088        theProxyMesh.NbProxySubMeshes() > 0 )
1089   {
1090     // add medium nodes of proxy triangles to theHelper (#16843)
1091     for ( elemSetIt = anElemSet.begin(); elemSetIt != anElemSet.end(); ++elemSetIt )
1092       theHelper.AddTLinks( static_cast< const SMDS_MeshFace* >( *elemSetIt ));
1093   }
1094
1095   /* EDGES ========================== */
1096
1097   // Iterate over the enforced edges
1098   for(elemIt = theEnforcedEdges.begin() ; elemIt != theEnforcedEdges.end() ; ++elemIt) {
1099     elem = elemIt->first;
1100     isOK = true;
1101     nodeIt = elem->nodesIterator();
1102     nbNodes = 2;
1103     while ( nodeIt->more() && nbNodes-- ) {
1104       // find MG-Tetra ID
1105       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1106       // Test if point is inside shape to mesh
1107       gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1108       TopAbs_State result = pntCls->GetPointState( myPoint );
1109       if ( result == TopAbs_OUT ) {
1110         isOK = false;
1111         theInvalidEnforcedFlags |= FLAG_BAD_ENF_EDGE;
1112         break;
1113       }
1114       aNodeToTopAbs_StateMap.insert( make_pair( node, result ));
1115     }
1116     if (isOK) {
1117       nodeIt = elem->nodesIterator();
1118       nbNodes = 2;
1119       int newId = -1;
1120       while ( nodeIt->more() && nbNodes-- ) {
1121         // find MG-Tetra ID
1122         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1123         gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1124         nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1125 #ifdef _MY_DEBUG_
1126         std::cout << "Node at "<<node->X()<<", "<<node->Y()<<", "<<node->Z()<<std::endl;
1127         std::cout << "Nb nodes found : "<<nbFoundElems<<std::endl;
1128 #endif
1129         if (nbFoundElems ==0) {
1130           if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
1131             newId = aNodeToGhs3dIdMap.size() + anEnforcedNodeToGhs3dIdMap.size() + 1; // MG-Tetra ids count from 1
1132             anEnforcedNodeToGhs3dIdMap.insert( make_pair( node, newId ));
1133           }
1134         }
1135         else if (nbFoundElems ==1) {
1136           const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1137           newId = (*aNodeToGhs3dIdMap.find(existingNode)).second;
1138           anExistingEnforcedNodeToGhs3dIdMap.insert( make_pair( node, newId ));
1139         }
1140         else
1141           isOK = false;
1142 #ifdef _MY_DEBUG_
1143         std::cout << "MG-Tetra node ID: "<<newId<<std::endl;
1144 #endif
1145       }
1146       if (isOK)
1147         theKeptEnforcedEdges.insert(elem);
1148       else
1149         theInvalidEnforcedFlags |= FLAG_BAD_ENF_EDGE;
1150     }
1151   }
1152   
1153   /* ENFORCED TRIANGLES ========================== */
1154   
1155   // Iterate over the enforced triangles
1156   for(elemIt = theEnforcedTriangles.begin() ; elemIt != theEnforcedTriangles.end() ; ++elemIt) {
1157     elem = elemIt->first;
1158     isOK = true;
1159     nodeIt = elem->nodesIterator();
1160     nbNodes = 3;
1161     while ( nodeIt->more() && nbNodes--) {
1162       // find MG-Tetra ID
1163       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1164       // Test if point is inside shape to mesh
1165       gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1166       TopAbs_State result = pntCls->GetPointState( myPoint );
1167       if ( result == TopAbs_OUT ) {
1168         isOK = false;
1169         theInvalidEnforcedFlags |= FLAG_BAD_ENF_TRIA;
1170         break;
1171       }
1172       aNodeToTopAbs_StateMap.insert( make_pair( node, result ));
1173     }
1174     if (isOK) {
1175       nodeIt = elem->nodesIterator();
1176       nbNodes = 3;
1177       int newId = -1;
1178       while ( nodeIt->more() && nbNodes--) {
1179         // find MG-Tetra ID
1180         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1181         gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1182         nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1183 #ifdef _MY_DEBUG_
1184         std::cout << "Nb nodes found : "<<nbFoundElems<<std::endl;
1185 #endif
1186         if (nbFoundElems ==0) {
1187           if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
1188             newId = aNodeToGhs3dIdMap.size() + anEnforcedNodeToGhs3dIdMap.size() + 1; // MG-Tetra ids count from 1
1189             anEnforcedNodeToGhs3dIdMap.insert( make_pair( node, newId ));
1190           }
1191         }
1192         else if (nbFoundElems ==1) {
1193           const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1194           newId = (*aNodeToGhs3dIdMap.find(existingNode)).second;
1195           anExistingEnforcedNodeToGhs3dIdMap.insert( make_pair( node, newId ));
1196         }
1197         else
1198           isOK = false;
1199 #ifdef _MY_DEBUG_
1200         std::cout << "MG-Tetra node ID: "<<newId<<std::endl;
1201 #endif
1202       }
1203       if (isOK)
1204         theKeptEnforcedTriangles.insert(elem);
1205       else
1206         theInvalidEnforcedFlags |= FLAG_BAD_ENF_TRIA;
1207     }
1208   }
1209   
1210   // put nodes to theNodeByGhs3dId vector
1211 #ifdef _MY_DEBUG_
1212   std::cout << "aNodeToGhs3dIdMap.size(): "<<aNodeToGhs3dIdMap.size()<<std::endl;
1213 #endif
1214   theNodeByGhs3dId.resize( aNodeToGhs3dIdMap.size() );
1215   map<const SMDS_MeshNode*,int>::const_iterator n2id = aNodeToGhs3dIdMap.begin();
1216   for ( ; n2id != aNodeToGhs3dIdMap.end(); ++ n2id)
1217   {
1218 //     std::cout << "n2id->first: "<<n2id->first<<std::endl;
1219     theNodeByGhs3dId[ n2id->second - 1 ] = n2id->first; // MG-Tetra ids count from 1
1220   }
1221
1222   // put nodes to anEnforcedNodeToGhs3dIdMap vector
1223 #ifdef _MY_DEBUG_
1224   std::cout << "anEnforcedNodeToGhs3dIdMap.size(): "<<anEnforcedNodeToGhs3dIdMap.size()<<std::endl;
1225 #endif
1226   theEnforcedNodeByGhs3dId.resize( anEnforcedNodeToGhs3dIdMap.size());
1227   n2id = anEnforcedNodeToGhs3dIdMap.begin();
1228   for ( ; n2id != anEnforcedNodeToGhs3dIdMap.end(); ++ n2id)
1229   {
1230     if (n2id->second > (int)aNodeToGhs3dIdMap.size()) {
1231       theEnforcedNodeByGhs3dId[ n2id->second - aNodeToGhs3dIdMap.size() - 1 ] = n2id->first; // MG-Tetra ids count from 1
1232     }
1233   }
1234   
1235   
1236   /* ========================== NODES ========================== */
1237   vector<const SMDS_MeshNode*> theOrderedNodes, theRequiredNodes;
1238   std::set< std::vector<double> > nodesCoords;
1239   vector<const SMDS_MeshNode*>::const_iterator ghs3dNodeIt = theNodeByGhs3dId.begin();
1240   vector<const SMDS_MeshNode*>::const_iterator after  = theNodeByGhs3dId.end();
1241   
1242   (theNodeByGhs3dId.size() <= 1) ? tmpStr = " node" : " nodes";
1243   std::cout << theNodeByGhs3dId.size() << tmpStr << " from mesh ..." << std::endl;
1244   for ( ; ghs3dNodeIt != after; ++ghs3dNodeIt )
1245   {
1246     const SMDS_MeshNode* node = *ghs3dNodeIt;
1247     std::vector<double> coords;
1248     coords.push_back(node->X());
1249     coords.push_back(node->Y());
1250     coords.push_back(node->Z());
1251     nodesCoords.insert(coords);
1252     theOrderedNodes.push_back(node);
1253   }
1254   
1255   // Iterate over the enforced nodes given by enforced elements
1256   ghs3dNodeIt = theEnforcedNodeByGhs3dId.begin();
1257   after  = theEnforcedNodeByGhs3dId.end();
1258   (theEnforcedNodeByGhs3dId.size() <= 1) ? tmpStr = " node" : " nodes";
1259   std::cout << theEnforcedNodeByGhs3dId.size() << tmpStr << " from enforced elements ..." << std::endl;
1260   for ( ; ghs3dNodeIt != after; ++ghs3dNodeIt )
1261   {
1262     const SMDS_MeshNode* node = *ghs3dNodeIt;
1263     std::vector<double> coords;
1264     coords.push_back(node->X());
1265     coords.push_back(node->Y());
1266     coords.push_back(node->Z());
1267 #ifdef _MY_DEBUG_
1268     std::cout << "Node at " << node->X()<<", " <<node->Y()<<", " <<node->Z();
1269 #endif
1270     
1271     if (nodesCoords.find(coords) != nodesCoords.end()) {
1272       // node already exists in original mesh
1273 #ifdef _MY_DEBUG_
1274       std::cout << " found" << std::endl;
1275 #endif
1276       continue;
1277     }
1278     
1279     if (theEnforcedVertices.find(coords) != theEnforcedVertices.end()) {
1280       // node already exists in enforced vertices
1281 #ifdef _MY_DEBUG_
1282       std::cout << " found" << std::endl;
1283 #endif
1284       continue;
1285     }
1286     
1287 //     gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1288 //     nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1289 //     if (nbFoundElems ==0) {
1290 //       std::cout << " not found" << std::endl;
1291 //       if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
1292 //         nodesCoords.insert(coords);
1293 //         theOrderedNodes.push_back(node);
1294 //       }
1295 //     }
1296 //     else {
1297 //       std::cout << " found in initial mesh" << std::endl;
1298 //       const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1299 //       nodesCoords.insert(coords);
1300 //       theOrderedNodes.push_back(existingNode);
1301 //     }
1302     
1303 #ifdef _MY_DEBUG_
1304     std::cout << " not found" << std::endl;
1305 #endif
1306     
1307     nodesCoords.insert(coords);
1308     theOrderedNodes.push_back(node);
1309 //     theRequiredNodes.push_back(node);
1310   }
1311   
1312   
1313   // Iterate over the enforced nodes
1314   GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap::const_iterator enfNodeIt;
1315   (theEnforcedNodes.size() <= 1) ? tmpStr = " node" : " nodes";
1316   std::cout << theEnforcedNodes.size() << tmpStr << " from enforced nodes ..." << std::endl;
1317   for(enfNodeIt = theEnforcedNodes.begin() ; enfNodeIt != theEnforcedNodes.end() ; ++enfNodeIt)
1318   {
1319     const SMDS_MeshNode* node = enfNodeIt->first;
1320     std::vector<double> coords;
1321     coords.push_back(node->X());
1322     coords.push_back(node->Y());
1323     coords.push_back(node->Z());
1324 #ifdef _MY_DEBUG_
1325     std::cout << "Node at " << node->X()<<", " <<node->Y()<<", " <<node->Z();
1326 #endif
1327     
1328     // Test if point is inside shape to mesh
1329     gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1330     TopAbs_State result = pntCls->GetPointState( myPoint );
1331     if ( result == TopAbs_OUT ) {
1332 #ifdef _MY_DEBUG_
1333       std::cout << " out of volume" << std::endl;
1334 #endif
1335       theInvalidEnforcedFlags |= FLAG_BAD_ENF_NODE;
1336       continue;
1337     }
1338     
1339     if (nodesCoords.find(coords) != nodesCoords.end()) {
1340 #ifdef _MY_DEBUG_
1341       std::cout << " found in nodesCoords" << std::endl;
1342 #endif
1343 //       theRequiredNodes.push_back(node);
1344       continue;
1345     }
1346
1347     if (theEnforcedVertices.find(coords) != theEnforcedVertices.end()) {
1348 #ifdef _MY_DEBUG_
1349       std::cout << " found in theEnforcedVertices" << std::endl;
1350 #endif
1351       continue;
1352     }
1353     
1354 //     nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1355 //     if (nbFoundElems ==0) {
1356 //       std::cout << " not found" << std::endl;
1357 //       if (result == TopAbs_IN) {
1358 //         nodesCoords.insert(coords);
1359 //         theRequiredNodes.push_back(node);
1360 //       }
1361 //     }
1362 //     else {
1363 //       std::cout << " found in initial mesh" << std::endl;
1364 //       const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1365 // //       nodesCoords.insert(coords);
1366 //       theRequiredNodes.push_back(existingNode);
1367 //     }
1368 //     
1369 //     
1370 //     
1371 //     if (pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems) == 0)
1372 //       continue;
1373
1374 //     if ( result != TopAbs_IN )
1375 //       continue;
1376     
1377 #ifdef _MY_DEBUG_
1378     std::cout << " not found" << std::endl;
1379 #endif
1380     nodesCoords.insert(coords);
1381 //     theOrderedNodes.push_back(node);
1382     theRequiredNodes.push_back(node);
1383   }
1384   int requiredNodes = theRequiredNodes.size();
1385   
1386   int solSize = 0;
1387   std::vector<std::vector<double> > ReqVerTab;
1388   if (nbEnforcedVertices) {
1389 //    ReqVerTab.clear();
1390     (nbEnforcedVertices <= 1) ? tmpStr = " node" : " nodes";
1391     std::cout << nbEnforcedVertices << tmpStr << " from enforced vertices ..." << std::endl;
1392     // Iterate over the enforced vertices
1393     for(vertexIt = theEnforcedVertices.begin() ; vertexIt != theEnforcedVertices.end() ; ++vertexIt) {
1394       double x = vertexIt->first[0];
1395       double y = vertexIt->first[1];
1396       double z = vertexIt->first[2];
1397       // Test if point is inside shape to mesh
1398       gp_Pnt myPoint(x,y,z);
1399       TopAbs_State result = pntCls->GetPointState( myPoint );
1400       if ( result == TopAbs_OUT )
1401       {
1402         std::cout << "Warning: enforced vertex at ( " << x << "," << y << "," << z << " ) is out of the meshed domain!!!" << std::endl;
1403         theInvalidEnforcedFlags |= FLAG_BAD_ENF_VERT;
1404         //continue;
1405       }
1406       std::vector<double> coords;
1407       coords.push_back(x);
1408       coords.push_back(y);
1409       coords.push_back(z);
1410       ReqVerTab.push_back(coords);
1411       enfVertexSizes.push_back(vertexIt->second);
1412       solSize++;
1413     }
1414   }
1415   
1416   
1417   // GmfVertices
1418   std::cout << "Begin writting required nodes in GmfVertices" << std::endl;
1419   std::cout << "Nb vertices: " << theOrderedNodes.size() << std::endl;
1420   MGInput->GmfSetKwd( idx, GmfVertices, theOrderedNodes.size()/*+solSize*/);
1421   for (ghs3dNodeIt = theOrderedNodes.begin();ghs3dNodeIt != theOrderedNodes.end();++ghs3dNodeIt) {
1422     MGInput->GmfSetLin( idx, GmfVertices, (*ghs3dNodeIt)->X(), (*ghs3dNodeIt)->Y(), (*ghs3dNodeIt)->Z(), dummyint);
1423   }
1424
1425   std::cout << "End writting required nodes in GmfVertices" << std::endl;
1426
1427   if (requiredNodes + solSize) {
1428     std::cout << "Begin writting in req and sol file" << std::endl;
1429     aNodeGroupByGhs3dId.resize( requiredNodes + solSize );
1430     idxRequired = MGInput->GmfOpenMesh( theRequiredFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1431     if (!idxRequired) {
1432       return false;
1433     }
1434     idxSol = MGInput->GmfOpenMesh( theSolFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1435     if (!idxSol) {
1436       return false;
1437     }
1438     int TypTab[] = {GmfSca};
1439     double ValTab[] = {0.0};
1440     MGInput->GmfSetKwd( idxRequired, GmfVertices, requiredNodes + solSize);
1441     MGInput->GmfSetKwd( idxSol, GmfSolAtVertices, requiredNodes + solSize, 1, TypTab);
1442 //     int usedEnforcedNodes = 0;
1443 //     std::string gn = "";
1444     for (ghs3dNodeIt = theRequiredNodes.begin();ghs3dNodeIt != theRequiredNodes.end();++ghs3dNodeIt) {
1445       MGInput->GmfSetLin( idxRequired, GmfVertices, (*ghs3dNodeIt)->X(), (*ghs3dNodeIt)->Y(), (*ghs3dNodeIt)->Z(), dummyint);
1446       MGInput->GmfSetLin( idxSol, GmfSolAtVertices, ValTab);
1447       if (theEnforcedNodes.find((*ghs3dNodeIt)) != theEnforcedNodes.end())
1448         gn = theEnforcedNodes.find((*ghs3dNodeIt))->second;
1449       aNodeGroupByGhs3dId[usedEnforcedNodes] = gn;
1450       usedEnforcedNodes++;
1451     }
1452
1453     for (int i=0;i<solSize;i++) {
1454       std::cout << ReqVerTab[i][0] <<" "<< ReqVerTab[i][1] << " "<< ReqVerTab[i][2] << std::endl;
1455 #ifdef _MY_DEBUG_
1456       std::cout << "enfVertexSizes.at("<<i<<"): " << enfVertexSizes.at(i) << std::endl;
1457 #endif
1458       double solTab[] = {enfVertexSizes.at(i)};
1459       MGInput->GmfSetLin( idxRequired, GmfVertices, ReqVerTab[i][0], ReqVerTab[i][1], ReqVerTab[i][2], dummyint);
1460       MGInput->GmfSetLin( idxSol, GmfSolAtVertices, solTab);
1461       aNodeGroupByGhs3dId[usedEnforcedNodes] = enfVerticesWithGroup.find(ReqVerTab[i])->second;
1462 #ifdef _MY_DEBUG_
1463       std::cout << "aNodeGroupByGhs3dId["<<usedEnforcedNodes<<"] = \""<<aNodeGroupByGhs3dId[usedEnforcedNodes]<<"\""<<std::endl;
1464 #endif
1465       usedEnforcedNodes++;
1466     }
1467     std::cout << "End writting in req and sol file" << std::endl;
1468   }
1469
1470   int nedge[2], ntri[3];
1471     
1472   // GmfEdges
1473   int usedEnforcedEdges = 0;
1474   if (theKeptEnforcedEdges.size()) {
1475     anEdgeGroupByGhs3dId.resize( theKeptEnforcedEdges.size() );
1476 //    idxRequired = MGInput->GmfOpenMesh( theRequiredFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1477 //    if (!idxRequired)
1478 //      return false;
1479     MGInput->GmfSetKwd( idx, GmfEdges, theKeptEnforcedEdges.size());
1480 //    MGInput->GmfSetKwd( idxRequired, GmfEdges, theKeptEnforcedEdges.size());
1481     for(elemSetIt = theKeptEnforcedEdges.begin() ; elemSetIt != theKeptEnforcedEdges.end() ; ++elemSetIt) {
1482       elem = (*elemSetIt);
1483       nodeIt = elem->nodesIterator();
1484       int index=0;
1485       while ( nodeIt->more() ) {
1486         // find MG-Tetra ID
1487         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1488         map< const SMDS_MeshNode*,int >::iterator it = anEnforcedNodeToGhs3dIdMap.find(node);
1489         if (it == anEnforcedNodeToGhs3dIdMap.end()) {
1490           it = anExistingEnforcedNodeToGhs3dIdMap.find(node);
1491           if (it == anEnforcedNodeToGhs3dIdMap.end())
1492             throw "Node not found";
1493         }
1494         nedge[index] = it->second;
1495         index++;
1496       }
1497       MGInput->GmfSetLin( idx, GmfEdges, nedge[0], nedge[1], dummyint);
1498       anEdgeGroupByGhs3dId[usedEnforcedEdges] = theEnforcedEdges.find(elem)->second;
1499 //      MGInput->GmfSetLin( idxRequired, GmfEdges, nedge[0], nedge[1], dummyint);
1500       usedEnforcedEdges++;
1501     }
1502   }
1503
1504
1505   if (usedEnforcedEdges) {
1506     MGInput->GmfSetKwd( idx, GmfRequiredEdges, usedEnforcedEdges);
1507     for (int enfID=1;enfID<=usedEnforcedEdges;enfID++) {
1508       MGInput->GmfSetLin( idx, GmfRequiredEdges, enfID);
1509     }
1510   }
1511
1512   // GmfTriangles
1513   int usedEnforcedTriangles = 0;
1514   if (anElemSet.size()+theKeptEnforcedTriangles.size()) {
1515     aFaceGroupByGhs3dId.resize( anElemSet.size()+theKeptEnforcedTriangles.size() );
1516     MGInput->GmfSetKwd( idx, GmfTriangles, anElemSet.size()+theKeptEnforcedTriangles.size());
1517     int k=0;
1518     for(elemSetIt = anElemSet.begin() ; elemSetIt != anElemSet.end() ; ++elemSetIt,++k) {
1519       elem = (*elemSetIt);
1520       theFaceByGhs3dId.push_back( elem );
1521       nodeIt = elem->nodesIterator();
1522       int index=0;
1523       for ( int j = 0; j < 3; ++j ) {
1524         // find MG-Tetra ID
1525         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1526         map< const SMDS_MeshNode*,int >::iterator it = aNodeToGhs3dIdMap.find(node);
1527         if (it == aNodeToGhs3dIdMap.end())
1528           throw "Node not found";
1529         ntri[index] = it->second;
1530         index++;
1531       }
1532       MGInput->GmfSetLin( idx, GmfTriangles, ntri[0], ntri[1], ntri[2], dummyint);
1533       aFaceGroupByGhs3dId[k] = "";
1534     }
1535     if ( !theHelper.GetMesh()->HasShapeToMesh() )
1536       SMESHUtils::FreeVector( theFaceByGhs3dId );
1537     if (theKeptEnforcedTriangles.size()) {
1538       for(elemSetIt = theKeptEnforcedTriangles.begin() ; elemSetIt != theKeptEnforcedTriangles.end() ; ++elemSetIt,++k) {
1539         elem = (*elemSetIt);
1540         nodeIt = elem->nodesIterator();
1541         int index=0;
1542         for ( int j = 0; j < 3; ++j ) {
1543           // find MG-Tetra ID
1544           const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1545           map< const SMDS_MeshNode*,int >::iterator it = anEnforcedNodeToGhs3dIdMap.find(node);
1546           if (it == anEnforcedNodeToGhs3dIdMap.end()) {
1547             it = anExistingEnforcedNodeToGhs3dIdMap.find(node);
1548             if (it == anEnforcedNodeToGhs3dIdMap.end())
1549               throw "Node not found";
1550           }
1551           ntri[index] = it->second;
1552           index++;
1553         }
1554         MGInput->GmfSetLin( idx, GmfTriangles, ntri[0], ntri[1], ntri[2], dummyint);
1555         aFaceGroupByGhs3dId[k] = theEnforcedTriangles.find(elem)->second;
1556         usedEnforcedTriangles++;
1557       }
1558     }
1559   }
1560
1561   
1562   if (usedEnforcedTriangles) {
1563     MGInput->GmfSetKwd( idx, GmfRequiredTriangles, usedEnforcedTriangles);
1564     for (int enfID=1;enfID<=usedEnforcedTriangles;enfID++)
1565       MGInput->GmfSetLin( idx, GmfRequiredTriangles, anElemSet.size()+enfID);
1566   }
1567
1568   MGInput->GmfCloseMesh(idx);
1569   if (idxRequired)
1570     MGInput->GmfCloseMesh(idxRequired);
1571   if (idxSol)
1572     MGInput->GmfCloseMesh(idxSol);
1573
1574   return true;
1575 }
1576
1577 //=============================================================================
1578 /*!
1579  *Here we are going to use the MG-Tetra mesher with geometry
1580  */
1581 //=============================================================================
1582
1583 bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
1584                                 const TopoDS_Shape& theShape)
1585 {
1586   bool Ok(false);
1587   TopExp_Explorer expBox ( theShape, TopAbs_SOLID );
1588
1589   // a unique working file name
1590   // to avoid access to the same files by eg different users
1591   _genericName = GHS3DPlugin_Hypothesis::GetFileName(_hyp);
1592   TCollection_AsciiString aGenericName((char*) _genericName.c_str() );
1593   TCollection_AsciiString aGenericNameRequired = aGenericName + "_required";
1594
1595   TCollection_AsciiString aLogFileName    = aGenericName + ".log";    // log
1596   TCollection_AsciiString aResultFileName;
1597
1598   TCollection_AsciiString aGMFFileName, aRequiredVerticesFileName, aSolFileName, aResSolFileName;
1599   aGMFFileName              = aGenericName + ".mesh"; // GMF mesh file
1600   aResultFileName           = aGenericName + "Vol.mesh"; // GMF mesh file
1601   aResSolFileName           = aGenericName + "Vol.sol"; // GMF mesh file
1602   aRequiredVerticesFileName = aGenericNameRequired + ".mesh"; // GMF required vertices mesh file
1603   aSolFileName              = aGenericNameRequired + ".sol"; // GMF solution file
1604   
1605   std::map <int,int> aNodeId2NodeIndexMap, aSmdsToGhs3dIdMap, anEnforcedNodeIdToGhs3dIdMap;
1606   std::map <int, int> nodeID2nodeIndexMap;
1607   std::map<std::vector<double>, std::string> enfVerticesWithGroup;
1608   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues coordsSizeMap = GHS3DPlugin_Hypothesis::GetEnforcedVerticesCoordsSize(_hyp);
1609   GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap enforcedNodes = GHS3DPlugin_Hypothesis::GetEnforcedNodes(_hyp);
1610   GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap enforcedEdges = GHS3DPlugin_Hypothesis::GetEnforcedEdges(_hyp);
1611   GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap enforcedTriangles = GHS3DPlugin_Hypothesis::GetEnforcedTriangles(_hyp);
1612   GHS3DPlugin_Hypothesis::TID2SizeMap nodeIDToSizeMap = GHS3DPlugin_Hypothesis::GetNodeIDToSizeMap(_hyp);
1613
1614   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexList enfVertices = GHS3DPlugin_Hypothesis::GetEnforcedVertices(_hyp);
1615   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexList::const_iterator enfVerIt = enfVertices.begin();
1616   std::vector<double> coords;
1617
1618   for ( ; enfVerIt != enfVertices.end() ; ++enfVerIt)
1619   {
1620     GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertex* enfVertex = (*enfVerIt);
1621     if (enfVertex->coords.size()) {
1622       coordsSizeMap.insert(make_pair(enfVertex->coords,enfVertex->size));
1623       enfVerticesWithGroup.insert(make_pair(enfVertex->coords,enfVertex->groupName));
1624     }
1625     else {
1626       TopoDS_Shape 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           gp_Pnt 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(make_pair(coords,enfVertex->size));
1636             enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
1637           }
1638         }
1639       }
1640     }
1641   }
1642   int nbEnforcedVertices = coordsSizeMap.size();
1643   int nbEnforcedNodes = enforcedNodes.size();
1644
1645   std::string tmpStr;
1646   (nbEnforcedNodes <= 1) ? tmpStr = "node" : "nodes";
1647   std::cout << nbEnforcedNodes << " enforced " << tmpStr << " from hypo" << std::endl;
1648   (nbEnforcedVertices <= 1) ? tmpStr = "vertex" : "vertices";
1649   std::cout << nbEnforcedVertices << " enforced " << tmpStr << " from hypo" << std::endl;
1650
1651   SMESH_MesherHelper helper( theMesh );
1652   helper.SetSubShape( theShape );
1653
1654   std::vector <const SMDS_MeshNode*> aNodeByGhs3dId, anEnforcedNodeByGhs3dId;
1655   std::vector <const SMDS_MeshElement*> aFaceByGhs3dId;
1656   std::map<const SMDS_MeshNode*,int> aNodeToGhs3dIdMap;
1657   std::vector<std::string> aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId;
1658
1659   MG_Tetra_API mgTetra( _computeCanceled, _progress );
1660
1661   _isLibUsed = mgTetra.IsLibrary();
1662   if ( theMesh.NbQuadrangles() > 0 )
1663     _progressAdvance /= 10;
1664   if ( _viscousLayersHyp )
1665     _progressAdvance /= 10;
1666
1667   // proxyMesh must live till readGMFFile() as a proxy face can be used by
1668   // MG-Tetra for domain indication
1669   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
1670
1671   // make prisms on quadrangles and viscous layers
1672   if ( theMesh.NbQuadrangles() > 0 || _viscousLayersHyp )
1673   {
1674     vector<SMESH_ProxyMesh::Ptr> components;
1675     for (expBox.ReInit(); expBox.More(); expBox.Next())
1676     {
1677       if ( _viscousLayersHyp )
1678       {
1679         proxyMesh = _viscousLayersHyp->Compute( theMesh, expBox.Current() );
1680         if ( !proxyMesh )
1681           return false;
1682         if ( theMesh.NbQuadrangles() == 0 )
1683           components.push_back( proxyMesh );
1684       }
1685       if ( theMesh.NbQuadrangles() > 0 )
1686       {
1687         StdMeshers_QuadToTriaAdaptor* q2t = new StdMeshers_QuadToTriaAdaptor;
1688         Ok = q2t->Compute( theMesh, expBox.Current(), proxyMesh.get() );
1689         components.push_back( SMESH_ProxyMesh::Ptr( q2t ));
1690         if ( !Ok )
1691           return false;
1692       }
1693     }
1694     proxyMesh.reset( new SMESH_ProxyMesh( components ));
1695   }
1696   // build viscous layers
1697   // else if ( _viscousLayersHyp )
1698   // {
1699   //   proxyMesh = _viscousLayersHyp->Compute( theMesh, theShape );
1700   //   if ( !proxyMesh )
1701   //     return false;
1702   // }
1703
1704   int anInvalidEnforcedFlags = 0;
1705   Ok = writeGMFFile(&mgTetra,
1706                     aGMFFileName.ToCString(),
1707                     aRequiredVerticesFileName.ToCString(),
1708                     aSolFileName.ToCString(),
1709                     *proxyMesh, helper,
1710                     aNodeByGhs3dId, aFaceByGhs3dId, aNodeToGhs3dIdMap,
1711                     aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
1712                     enforcedNodes, enforcedEdges, enforcedTriangles,
1713                     enfVerticesWithGroup, coordsSizeMap, anInvalidEnforcedFlags);
1714
1715   // Write aSmdsToGhs3dIdMap to temp file
1716   TCollection_AsciiString aSmdsToGhs3dIdMapFileName;
1717   aSmdsToGhs3dIdMapFileName = aGenericName + ".ids";  // ids relation
1718   ofstream aIdsFile  ( aSmdsToGhs3dIdMapFileName.ToCString()  , ios::out);
1719   Ok = aIdsFile.rdbuf()->is_open();
1720   if (!Ok) {
1721     INFOS( "Can't write into " << aSmdsToGhs3dIdMapFileName);
1722     return error(SMESH_Comment("Can't write into ") << aSmdsToGhs3dIdMapFileName);
1723   }
1724   INFOS( "Writing ids relation into " << aSmdsToGhs3dIdMapFileName);
1725   aIdsFile << "Smds MG-Tetra" << std::endl;
1726   map <int,int>::const_iterator myit;
1727   for (myit=aSmdsToGhs3dIdMap.begin() ; myit != aSmdsToGhs3dIdMap.end() ; ++myit) {
1728     aIdsFile << myit->first << " " << myit->second << std::endl;
1729   }
1730
1731   aIdsFile.close();
1732
1733   if ( ! Ok ) {
1734     if ( !_keepFiles ) {
1735       removeFile( aGMFFileName );
1736       removeFile( aRequiredVerticesFileName );
1737       removeFile( aSolFileName );
1738       removeFile( aSmdsToGhs3dIdMapFileName );
1739     }
1740     return error(COMPERR_BAD_INPUT_MESH);
1741   }
1742   removeFile( aResultFileName ); // needed for boundary recovery module usage
1743
1744   // -----------------
1745   // run MG-Tetra mesher
1746   // -----------------
1747
1748   TCollection_AsciiString cmd = GHS3DPlugin_Hypothesis::CommandToRun( _hyp, true, mgTetra.IsExecutable() ).c_str();
1749
1750   if ( mgTetra.IsExecutable() )
1751   {
1752     cmd += TCollection_AsciiString(" --in ") + aGMFFileName;
1753     if ( nbEnforcedVertices + nbEnforcedNodes)
1754       cmd += TCollection_AsciiString(" --required_vertices ") + aGenericNameRequired;
1755     cmd += TCollection_AsciiString(" --out ") + aResultFileName;
1756   }
1757   if ( !_logInStandardOutput )
1758   {
1759     mgTetra.SetLogFile( aLogFileName.ToCString() );
1760     cmd += TCollection_AsciiString(" 1>" ) + aLogFileName;  // dump into file
1761   }
1762
1763   BRIEF_INFOS("")
1764   BRIEF_INFOS("MG-Tetra execution...")
1765   BRIEF_INFOS(cmd)
1766
1767   _computeCanceled = false;
1768
1769   std::string errStr;
1770   Ok = mgTetra.Compute( cmd.ToCString(), errStr ); // run
1771
1772   if ( _logInStandardOutput && mgTetra.IsLibrary() ) {
1773     BRIEF_INFOS("");
1774     BRIEF_INFOS(mgTetra.GetLog());
1775     BRIEF_INFOS("")
1776   }
1777   if ( Ok ) {
1778     BRIEF_INFOS("");
1779     BRIEF_INFOS("End of MG-Tetra execution !");
1780     BRIEF_INFOS("")
1781   }
1782
1783   // --------------
1784   // read a result
1785   // --------------
1786
1787   GHS3DPlugin_Hypothesis::TSetStrings groupsToRemove = GHS3DPlugin_Hypothesis::GetGroupsToRemove(_hyp);
1788   bool toMeshHoles =
1789     _hyp ? _hyp->GetToMeshHoles(true) : GHS3DPlugin_Hypothesis::DefaultMeshHoles();
1790   const bool toMakeGroupsOfDomains = GHS3DPlugin_Hypothesis::GetToMakeGroupsOfDomains( _hyp );
1791
1792   helper.IsQuadraticSubMesh( theShape );
1793   helper.SetElementsOnShape( false );
1794
1795   Ok = readGMFFile(&mgTetra,
1796                    aResultFileName.ToCString(),
1797                    this,
1798                    &helper, aNodeByGhs3dId, aFaceByGhs3dId, aNodeToGhs3dIdMap,
1799                    aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
1800                    groupsToRemove, toMakeGroupsOfDomains, toMeshHoles);
1801
1802   removeEmptyGroupsOfDomains( helper.GetMesh(), /*notEmptyAsWell =*/ !toMakeGroupsOfDomains );
1803
1804
1805
1806   // ---------------------
1807   // remove working files
1808   // ---------------------
1809
1810   if ( Ok )
1811   {
1812     if ( anInvalidEnforcedFlags )
1813       error( COMPERR_WARNING, flagsToErrorStr( anInvalidEnforcedFlags ));
1814     if ( _removeLogOnSuccess )
1815       removeFile( aLogFileName );
1816     // if ( _hyp && _hyp->GetToMakeGroupsOfDomains() )
1817     //   error( COMPERR_WARNING, "'toMakeGroupsOfDomains' is ignored since the mesh is on shape" );
1818   }
1819   else if ( mgTetra.HasLog() )
1820   {
1821     if( _computeCanceled )
1822       error( "interruption initiated by user" );
1823     else
1824     {
1825       // get problem description from the log file
1826       _Ghs2smdsConvertor conv( aNodeByGhs3dId, proxyMesh );
1827       error( getErrorDescription( _logInStandardOutput ? 0 : aLogFileName.ToCString(),
1828                                   mgTetra.GetLog(), conv ));
1829     }
1830   }
1831   else if ( !errStr.empty() )
1832   {
1833     // the log file is empty
1834     removeFile( aLogFileName );
1835     INFOS( "MG-Tetra Error, " << errStr);
1836     error(COMPERR_ALGO_FAILED, errStr);
1837   }
1838
1839   if ( !_keepFiles ) {
1840     if (! Ok && _computeCanceled )
1841       removeFile( aLogFileName );
1842     removeFile( aGMFFileName );
1843     removeFile( aRequiredVerticesFileName );
1844     removeFile( aSolFileName );
1845     removeFile( aResSolFileName );
1846     removeFile( aResultFileName );
1847     removeFile( aSmdsToGhs3dIdMapFileName );
1848   }
1849   if ( mgTetra.IsExecutable() )
1850   {
1851     std::cout << "<" << aResultFileName.ToCString() << "> MG-Tetra output file ";
1852     if ( !Ok )
1853       std::cout << "not ";
1854     std::cout << "treated !" << std::endl;
1855     std::cout << std::endl;
1856   }
1857   else
1858   {
1859     std::cout << "MG-Tetra " << ( Ok ? "succeeded" : "failed") << std::endl;
1860   }
1861   return Ok;
1862 }
1863
1864 //=============================================================================
1865 /*!
1866  *Here we are going to use the MG-Tetra mesher w/o geometry
1867  */
1868 //=============================================================================
1869 bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
1870                                 SMESH_MesherHelper* theHelper)
1871 {
1872   theHelper->IsQuadraticSubMesh( theHelper->GetSubShape() );
1873
1874   // a unique working file name
1875   // to avoid access to the same files by eg different users
1876   _genericName = GHS3DPlugin_Hypothesis::GetFileName(_hyp);
1877   TCollection_AsciiString aGenericName((char*) _genericName.c_str() );
1878   TCollection_AsciiString aGenericNameRequired = aGenericName + "_required";
1879
1880   TCollection_AsciiString aLogFileName    = aGenericName + ".log";    // log
1881   TCollection_AsciiString aResultFileName;
1882   bool Ok;
1883
1884   TCollection_AsciiString aGMFFileName, aRequiredVerticesFileName, aSolFileName, aResSolFileName;
1885   aGMFFileName              = aGenericName + ".mesh"; // GMF mesh file
1886   aResultFileName           = aGenericName + "Vol.mesh"; // GMF mesh file
1887   aResSolFileName           = aGenericName + "Vol.sol"; // GMF mesh file
1888   aRequiredVerticesFileName = aGenericNameRequired + ".mesh"; // GMF required vertices mesh file
1889   aSolFileName              = aGenericNameRequired + ".sol"; // GMF solution file
1890
1891   std::map <int, int> nodeID2nodeIndexMap;
1892   std::map<std::vector<double>, std::string> enfVerticesWithGroup;
1893   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues coordsSizeMap;
1894   TopoDS_Shape GeomShape;
1895   std::vector<double> coords;
1896   gp_Pnt aPnt;
1897   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertex* enfVertex;
1898
1899   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexList enfVertices = GHS3DPlugin_Hypothesis::GetEnforcedVertices(_hyp);
1900   GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexList::const_iterator enfVerIt = enfVertices.begin();
1901
1902   for ( ; enfVerIt != enfVertices.end() ; ++enfVerIt)
1903   {
1904     enfVertex = (*enfVerIt);
1905     if (enfVertex->coords.size()) {
1906       coordsSizeMap.insert(make_pair(enfVertex->coords,enfVertex->size));
1907       enfVerticesWithGroup.insert(make_pair(enfVertex->coords,enfVertex->groupName));
1908     }
1909     else {
1910       GeomShape = entryToShape(enfVertex->geomEntry);
1911       for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1912         coords.clear();
1913         if (it.Value().ShapeType() == TopAbs_VERTEX){
1914           aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
1915           coords.push_back(aPnt.X());
1916           coords.push_back(aPnt.Y());
1917           coords.push_back(aPnt.Z());
1918           if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
1919             coordsSizeMap.insert(make_pair(coords,enfVertex->size));
1920             enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
1921           }
1922         }
1923       }
1924     }
1925   }
1926
1927   GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap     enforcedNodes = GHS3DPlugin_Hypothesis::GetEnforcedNodes(_hyp);
1928   GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap     enforcedEdges = GHS3DPlugin_Hypothesis::GetEnforcedEdges(_hyp);
1929   GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap enforcedTriangles = GHS3DPlugin_Hypothesis::GetEnforcedTriangles(_hyp);
1930   GHS3DPlugin_Hypothesis::TID2SizeMap             nodeIDToSizeMap = GHS3DPlugin_Hypothesis::GetNodeIDToSizeMap(_hyp);
1931
1932   std::string tmpStr;
1933
1934   int nbEnforcedVertices = coordsSizeMap.size();
1935   int nbEnforcedNodes = enforcedNodes.size();
1936   (nbEnforcedNodes <= 1) ? tmpStr = "node" : tmpStr = "nodes";
1937   std::cout << nbEnforcedNodes << " enforced " << tmpStr << " from hypo" << std::endl;
1938   (nbEnforcedVertices <= 1) ? tmpStr = "vertex" : tmpStr = "vertices";
1939   std::cout << nbEnforcedVertices << " enforced " << tmpStr << " from hypo" << std::endl;
1940
1941   std::vector <const SMDS_MeshNode*> aNodeByGhs3dId, anEnforcedNodeByGhs3dId;
1942   std::vector <const SMDS_MeshElement*> aFaceByGhs3dId;
1943   std::map<const SMDS_MeshNode*,int> aNodeToGhs3dIdMap;
1944   std::vector<std::string> aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId;
1945
1946
1947   MG_Tetra_API mgTetra( _computeCanceled, _progress );
1948
1949   _isLibUsed = mgTetra.IsLibrary();
1950   if ( theMesh.NbQuadrangles() > 0 )
1951     _progressAdvance /= 10;
1952
1953   // proxyMesh must live till readGMFFile() as a proxy face can be used by
1954   // MG-Tetra for domain indication
1955   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
1956   if ( theMesh.NbQuadrangles() > 0 )
1957   {
1958     StdMeshers_QuadToTriaAdaptor* aQuad2Trias = new StdMeshers_QuadToTriaAdaptor;
1959     Ok = aQuad2Trias->Compute( theMesh );
1960     proxyMesh.reset( aQuad2Trias );
1961     if ( !Ok )
1962       return false;
1963   }
1964
1965   int anInvalidEnforcedFlags = 0;
1966   Ok = writeGMFFile(&mgTetra,
1967                     aGMFFileName.ToCString(), aRequiredVerticesFileName.ToCString(), aSolFileName.ToCString(),
1968                     *proxyMesh, *theHelper,
1969                     aNodeByGhs3dId, aFaceByGhs3dId, aNodeToGhs3dIdMap,
1970                     aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
1971                     enforcedNodes, enforcedEdges, enforcedTriangles,
1972                     enfVerticesWithGroup, coordsSizeMap, anInvalidEnforcedFlags);
1973
1974   // -----------------
1975   // run MG-Tetra mesher
1976   // -----------------
1977
1978   TCollection_AsciiString cmd = GHS3DPlugin_Hypothesis::CommandToRun( _hyp, false, mgTetra.IsExecutable() ).c_str();
1979
1980   if ( mgTetra.IsExecutable() )
1981   {
1982     cmd += TCollection_AsciiString(" --in ") + aGMFFileName;
1983     if ( nbEnforcedVertices + nbEnforcedNodes)
1984       cmd += TCollection_AsciiString(" --required_vertices ") + aGenericNameRequired;
1985     cmd += TCollection_AsciiString(" --out ") + aResultFileName;
1986   }
1987   if ( !_logInStandardOutput )
1988   {
1989     mgTetra.SetLogFile( aLogFileName.ToCString() );
1990     cmd += TCollection_AsciiString(" 1>" ) + aLogFileName;  // dump into file
1991   }
1992
1993   BRIEF_INFOS("")
1994   BRIEF_INFOS("MG-Tetra execution...")
1995   BRIEF_INFOS(cmd)
1996
1997   _computeCanceled = false;
1998
1999   std::string errStr;
2000   Ok = mgTetra.Compute( cmd.ToCString(), errStr ); // run
2001
2002   if ( _logInStandardOutput && mgTetra.IsLibrary() ) {
2003     BRIEF_INFOS("");
2004     BRIEF_INFOS(mgTetra.GetLog());
2005     BRIEF_INFOS("")
2006   }
2007   if ( Ok ) {
2008     BRIEF_INFOS("");
2009     BRIEF_INFOS("End of MG-Tetra execution !");
2010     BRIEF_INFOS("")
2011   }
2012
2013   // --------------
2014   // read a result
2015   // --------------
2016   GHS3DPlugin_Hypothesis::TSetStrings groupsToRemove = GHS3DPlugin_Hypothesis::GetGroupsToRemove(_hyp);
2017   const bool toMakeGroupsOfDomains = GHS3DPlugin_Hypothesis::GetToMakeGroupsOfDomains( _hyp );
2018
2019   Ok = Ok && readGMFFile(&mgTetra,
2020                          aResultFileName.ToCString(),
2021                          this,
2022                          theHelper, aNodeByGhs3dId, aFaceByGhs3dId, aNodeToGhs3dIdMap,
2023                          aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
2024                          groupsToRemove, toMakeGroupsOfDomains);
2025
2026   updateMeshGroups(theHelper->GetMesh(), groupsToRemove);
2027   removeEmptyGroupsOfDomains( theHelper->GetMesh(), /*notEmptyAsWell =*/ !toMakeGroupsOfDomains );
2028
2029   if ( Ok ) {
2030     GHS3DPlugin_Hypothesis* that = (GHS3DPlugin_Hypothesis*)this->_hyp;
2031     if (that)
2032       that->ClearGroupsToRemove();
2033   }
2034   // ---------------------
2035   // remove working files
2036   // ---------------------
2037
2038   if ( Ok )
2039   {
2040     if ( anInvalidEnforcedFlags )
2041       error( COMPERR_WARNING, flagsToErrorStr( anInvalidEnforcedFlags ));
2042     if ( _removeLogOnSuccess )
2043       removeFile( aLogFileName );
2044
2045     //if ( !toMakeGroupsOfDomains && _hyp && _hyp->GetToMakeGroupsOfDomains() )
2046     //error( COMPERR_WARNING, "'toMakeGroupsOfDomains' is ignored since 'toMeshHoles' is OFF." );
2047   }
2048   else if ( mgTetra.HasLog() )
2049   {
2050     if( _computeCanceled )
2051       error( "interruption initiated by user" );
2052     else
2053     {
2054       // get problem description from the log file
2055       _Ghs2smdsConvertor conv( aNodeByGhs3dId, proxyMesh );
2056       error( getErrorDescription( _logInStandardOutput ? 0 : aLogFileName.ToCString(),
2057                                   mgTetra.GetLog(), conv ));
2058     }
2059   }
2060   else {
2061     // the log file is empty
2062     removeFile( aLogFileName );
2063     INFOS( "MG-Tetra Error, " << errStr);
2064     error(COMPERR_ALGO_FAILED, errStr);
2065   }
2066
2067   if ( !_keepFiles )
2068   {
2069     if (! Ok && _computeCanceled)
2070       removeFile( aLogFileName );
2071     removeFile( aGMFFileName );
2072     removeFile( aResultFileName );
2073     removeFile( aRequiredVerticesFileName );
2074     removeFile( aSolFileName );
2075     removeFile( aResSolFileName );
2076   }
2077   return Ok;
2078 }
2079
2080 void GHS3DPlugin_GHS3D::CancelCompute()
2081 {
2082   _computeCanceled = true;
2083 #if !defined WIN32 && !defined __APPLE__
2084   std::string cmd = "ps xo pid,args | grep " + _genericName;
2085   //cmd += " | grep -e \"^ *[0-9]\\+ \\+" + GHS3DPlugin_Hypothesis::GetExeName() + "\"";
2086   cmd += " | awk '{print $1}' | xargs kill -9 > /dev/null 2>&1";
2087   system( cmd.c_str() );
2088 #endif
2089 }
2090
2091 //================================================================================
2092 /*!
2093  * \brief Provide human readable text by error code reported by MG-Tetra
2094  */
2095 //================================================================================
2096
2097 static const char* translateError(const int errNum)
2098 {
2099   switch ( errNum ) {
2100   case 0:
2101     return "The surface mesh includes a face of type other than edge, "
2102       "triangle or quadrilateral. This face type is not supported.";
2103   case 1:
2104     return "Not enough memory for the face table.";
2105   case 2:
2106     return "Not enough memory.";
2107   case 3:
2108     return "Not enough memory.";
2109   case 4:
2110     return "Face is ignored.";
2111   case 5:
2112     return "End of file. Some data are missing in the file.";
2113   case 6:
2114     return "Read error on the file. There are wrong data in the file.";
2115   case 7:
2116     return "the metric file is inadequate (dimension other than 3).";
2117   case 8:
2118     return "the metric file is inadequate (values not per vertices).";
2119   case 9:
2120     return "the metric file contains more than one field.";
2121   case 10:
2122     return "the number of values in the \".bb\" (metric file) is incompatible with the expected"
2123       "value of number of mesh vertices in the \".noboite\" file.";
2124   case 12:
2125     return "Too many sub-domains.";
2126   case 13:
2127     return "the number of vertices is negative or null.";
2128   case 14:
2129     return "the number of faces is negative or null.";
2130   case 15:
2131     return "A face has a null vertex.";
2132   case 22:
2133     return "incompatible data.";
2134   case 131:
2135     return "the number of vertices is negative or null.";
2136   case 132:
2137     return "the number of vertices is negative or null (in the \".mesh\" file).";
2138   case 133:
2139     return "the number of faces is negative or null.";
2140   case 1000:
2141     return "A face appears more than once in the input surface mesh.";
2142   case 1001:
2143     return "An edge appears more than once in the input surface mesh.";
2144   case 1002:
2145     return "A face has a vertex negative or null.";
2146   case 1003:
2147     return "NOT ENOUGH MEMORY.";
2148   case 2000:
2149     return "Not enough available memory.";
2150   case 2002:
2151     return "Some initial points cannot be inserted. The surface mesh is probably very bad "
2152       "in terms of quality or the input list of points is wrong.";
2153   case 2003:
2154     return "Some vertices are too close to one another or coincident.";
2155   case 2004:
2156     return "Some vertices are too close to one another or coincident.";
2157   case 2012:
2158     return "A vertex cannot be inserted.";
2159   case 2014:
2160     return "There are at least two points considered as coincident.";
2161   case 2103:
2162     return "Some vertices are too close to one another or coincident.";
2163   case 3000:
2164     return "The surface mesh regeneration step has failed.";
2165   case 3009:
2166     return "Constrained edge cannot be enforced.";
2167   case 3019:
2168     return "Constrained face cannot be enforced.";
2169   case 3029:
2170     return "Missing faces.";
2171   case 3100:
2172     return "No guess to start the definition of the connected component(s).";
2173   case 3101:
2174     return "The surface mesh includes at least one hole. The domain is not well defined.";
2175   case 3102:
2176     return "Impossible to define a component.";
2177   case 3103:
2178     return "The surface edge intersects another surface edge.";
2179   case 3104:
2180     return "The surface edge intersects the surface face.";
2181   case 3105:
2182     return "One boundary point lies within a surface face.";
2183   case 3106:
2184     return "One surface edge intersects a surface face.";
2185   case 3107:
2186     return "One boundary point lies within a surface edge.";
2187   case 3108:
2188     return "Insufficient memory ressources detected due to a bad quality surface mesh leading "
2189       "to too many swaps.";
2190   case 3109:
2191     return "Edge is unique (i.e., bounds a hole in the surface).";
2192   case 3122:
2193     return "Presumably, the surface mesh is not compatible with the domain being processed.";
2194   case 3123:
2195     return "Too many components, too many sub-domain.";
2196   case 3209:
2197     return "The surface mesh includes at least one hole. "
2198       "Therefore there is no domain properly defined.";
2199   case 3300:
2200     return "Statistics.";
2201   case 3400:
2202     return "Statistics.";
2203   case 3500:
2204     return "Warning, it is dramatically tedious to enforce the boundary items.";
2205   case 4000:
2206     return "Not enough memory at this time, nevertheless, the program continues. "
2207       "The expected mesh will be correct but not really as large as required.";
2208   case 4002:
2209     return "see above error code, resulting quality may be poor.";
2210   case 4003:
2211     return "Not enough memory at this time, nevertheless, the program continues (warning).";
2212   case 8000:
2213     return "Unknown face type.";
2214   case 8005:
2215   case 8006:
2216     return "End of file. Some data are missing in the file.";
2217   case 9000:
2218     return "A too small volume element is detected.";
2219   case 9001:
2220     return "There exists at least a null or negative volume element.";
2221   case 9002:
2222     return "There exist null or negative volume elements.";
2223   case 9003:
2224     return "A too small volume element is detected. A face is considered being degenerated.";
2225   case 9100:
2226     return "Some element is suspected to be very bad shaped or wrong.";
2227   case 9102:
2228     return "A too bad quality face is detected. This face is considered degenerated.";
2229   case 9112:
2230     return "A too bad quality face is detected. This face is degenerated.";
2231   case 9122:
2232     return "Presumably, the surface mesh is not compatible with the domain being processed.";
2233   case 9999:
2234     return "Abnormal error occured, contact hotline.";
2235   case 23600:
2236     return "Not enough memory for the face table.";
2237   case 23601:
2238     return "The algorithm cannot run further. "
2239       "The surface mesh is probably very bad in terms of quality.";
2240   case 23602:
2241     return "Bad vertex number.";
2242   case 1001200:
2243     return "Cannot close mesh file NomFil.";
2244   case 1002010:
2245     return "There are wrong data.";
2246   case 1002120:
2247     return "The number of faces is negative or null.";
2248   case 1002170:
2249     return "The number of vertices is negative or null in the '.sol' file.";
2250   case 1002190:
2251     return "The number of tetrahedra is negative or null.";
2252   case 1002210:
2253     return "The number of vertices is negative or null.";
2254   case 1002211:
2255     return "A face has a vertex negative or null.";
2256   case 1002270:
2257     return "The field is not a size in file NomFil.";
2258   case 1002280:
2259     return "A count is wrong in the enclosing box in the .boite.mesh input "
2260       "file (option '--read_boite').";
2261   case 1002290:
2262     return "A tetrahedron has a vertex with a negative number.";
2263   case 1002300:
2264     return "the 'MeshVersionFormatted' is not 1 or 2 in the '.mesh' file or the '.sol'.";
2265  case 1002370:
2266    return "The number of values in the '.sol' (metric file) is incompatible with "
2267      "the expected value of number of mesh vertices in the '.mesh' file.";
2268   case 1003000:
2269     return "Not enough memory.";
2270   case 1003020:
2271     return "Not enough memory for the face table.";
2272   case 1003050:
2273     return "Insufficient memory ressources detected due to a bad quality "
2274       "surface mesh leading to too many swaps.";
2275   case 1005010:
2276     return "The surface coordinates of a vertex are differing from the "
2277       "volume coordinates, probably due to a precision problem.";
2278   case 1005050:
2279     return "Invalid dimension. Dimension 3 expected.";
2280   case 1005100:
2281     return "A point has a tag 0. This point is probably outside the domain which has been meshed.";
2282   case 1005103:
2283     return "The vertices of an element are too close to one another or coincident.";
2284   case 1005104:
2285     return "There are at least two points whose distance is very small, and considered as coincident.";
2286   case 1005105:
2287     return "Two vertices are too close to one another or coincident.";
2288   case 1005106:
2289     return "A vertex cannot be inserted.";
2290   case 1005107:
2291     return "Two vertices are too close to one another or coincident. Note : When "
2292       "this error occurs during the overconstrained processing phase, this is only "
2293       "a warning which means that it is difficult to break some overconstrained facets.";
2294   case 1005110:
2295     return "Two surface edges are intersecting.";
2296   case 1005120:
2297     return "A surface edge intersects a surface face.";
2298   case 1005150:
2299     return "A boundary point lies within a surface face.";
2300   case 1005160:
2301     return "A boundary point lies within a surface edge.";
2302   case 1005200:
2303     return "A surface mesh appears more than once in the input surface mesh.";
2304   case 1005210:
2305     return "An edge appears more than once in the input surface mesh.";
2306   case 1005225:
2307     return "Surface with unvalid triangles.";
2308   case 1005270:
2309     return "The metric in the '.sol' file contains more than one field.";
2310   case 1005300:
2311     return "The surface mesh includes at least one hole. The domain is not well defined.";
2312   case 1005301:
2313     return "Presumably, the surface mesh is not compatible with the domain being processed (warning).";
2314   case 1005302:
2315     return "Probable faces overlapping somewher.";
2316   case 1005320:
2317     return "The quadratic version does not work with prescribed free edges.";
2318   case 1005321:
2319     return "The quadratic version does not work with a volume mesh.";
2320   case 1005370:
2321     return "The metric in the '.sol' file is inadequate (values not per vertices).";
2322   case 1005371:
2323     return "The number of vertices in the '.sol' is different from the one in the "
2324       "'.mesh' file for the required vertices (option '--required_vertices').";
2325   case 1005372:
2326     return "More than one type in file NomFil. The type must be equal to 1 in the '.sol'"
2327       "for the required vertices (option '--required_vertices').";
2328   case 1005515:
2329     return "Bad vertex number.";
2330   case 1005560:
2331     return "No guess to start the definition of the connected component(s).";
2332   case 1005602:
2333     return "Some initial points cannot be inserted.";
2334   case 1005620:
2335     return "A too bad quality face is detected. This face is considered degenerated.";
2336   case 1005621:
2337     return "A too bad quality face is detected. This face is degenerated.";
2338   case 1005622:
2339     return "The algorithm cannot run further.";
2340   case 1005690:
2341     return "A too small volume element is detected.";
2342   case 1005691:
2343     return "A tetrahedra is suspected to be very bad shaped or wrong.";
2344   case 1005692:
2345     return "There is at least a null or negative volume element. The resulting mesh"
2346       "may be inappropriate.";
2347   case 1005693:
2348     return "There are some null or negative volume element. The resulting mesh may"
2349       "be inappropriate.";
2350   case 1005820:
2351     return "An edge is unique (i.e., bounds a hole in the surface).";
2352   case 1007000:
2353     return "Abnormal or internal error.";
2354   case 1007010:
2355     return "Too many components with respect to too many sub-domain.";
2356   case 1007400:
2357     return "An internal error has been encountered or a signal has been received. "
2358       "Current mesh will not be saved.";
2359   case 1008491:
2360     return "Impossible to define a component.";
2361   case 1008410:
2362     return "There are some overconstrained edges.";
2363   case 1008420:
2364     return "There are some overconstrained facets.";
2365   case 1008422:
2366     return "Give the number of missing faces (information given when regeneration phase failed).";
2367   case 1008423:
2368     return "A constrained face cannot be enforced (information given when regeneration phase failed).";
2369   case 1008441:
2370     return "A constrained edge cannot be enforced.";
2371   case 1008460:
2372     return "It is dramatically tedious to enforce the boundary items.";
2373   case 1008480:
2374     return "The surface mesh regeneration step has failed. A .boite.mesh and .boite.map files are created.";
2375   case 1008490:
2376     return "Invalid resulting mesh.";
2377   case 1008495:
2378     return "P2 correction not successful.";
2379   case 1009000:
2380     return "Program has received an interruption or a termination signal sent by the "
2381       "user or the system administrator. Current mesh will not be saved.";
2382   }
2383   return "";
2384 }
2385
2386 //================================================================================
2387 /*!
2388  * \brief Retrieve from a string given number of integers
2389  */
2390 //================================================================================
2391
2392 static char* getIds( char* ptr, int nbIds, vector<int>& ids )
2393 {
2394   ids.clear();
2395   ids.reserve( nbIds );
2396   while ( nbIds )
2397   {
2398     while ( !isdigit( *ptr )) ++ptr;
2399     if ( ptr[-1] == '-' ) --ptr;
2400     ids.push_back( strtol( ptr, &ptr, 10 ));
2401     --nbIds;
2402   }
2403   return ptr;
2404 }
2405
2406 //================================================================================
2407 /*!
2408  * \brief Retrieve problem description form a log file
2409  *  \retval bool - always false
2410  */
2411 //================================================================================
2412
2413 SMESH_ComputeErrorPtr
2414 GHS3DPlugin_GHS3D::getErrorDescription(const char*                logFile,
2415                                        const std::string&         log,
2416                                        const _Ghs2smdsConvertor & toSmdsConvertor,
2417                                        const bool                 isOk/* = false*/ )
2418 {
2419   SMESH_BadInputElements* badElemsErr =
2420     new SMESH_BadInputElements( toSmdsConvertor.getMesh(), COMPERR_ALGO_FAILED );
2421   SMESH_ComputeErrorPtr err( badElemsErr );
2422
2423   char* ptr = const_cast<char*>( log.c_str() );
2424   char* buf = ptr, * bufEnd = ptr + log.size();
2425
2426
2427   SMESH_Comment errDescription;
2428
2429   enum { NODE = 1, EDGE, TRIA, VOL, SKIP_ID = 1 };
2430
2431   // look for MeshGems version
2432   // Since "MG-TETRA -- MeshGems 1.1-3 (January, 2013)" error codes change.
2433   // To discriminate old codes from new ones we add 1000000 to the new codes.
2434   // This way value of the new codes is same as absolute value of codes printed
2435   // in the log after "MGMESSAGE" string.
2436   int versionAddition = 0;
2437   {
2438     char* verPtr = ptr;
2439     while ( ++verPtr < bufEnd )
2440     {
2441       if ( strncmp( verPtr, "MG-TETRA -- MeshGems ", 21 ) != 0 )
2442         continue;
2443       if ( strcmp( verPtr, "MG-TETRA -- MeshGems 1.1-3 " ) >= 0 )
2444         versionAddition = 1000000;
2445       ptr = verPtr;
2446       break;
2447     }
2448   }
2449
2450   // look for errors "ERR #"
2451
2452   set<string> foundErrorStr; // to avoid reporting same error several times
2453   set<int>    elemErrorNums; // not to report different types of errors with bad elements
2454   while ( ++ptr < bufEnd )
2455   {
2456     if ( strncmp( ptr, "ERR ", 4 ) != 0 )
2457       continue;
2458
2459     list<const SMDS_MeshElement*>& badElems = badElemsErr->myBadElements;
2460     vector<int> nodeIds;
2461
2462     ptr += 4;
2463     char* errBeg = ptr;
2464     int   errNum = strtol(ptr, &ptr, 10) + versionAddition;
2465     // we treat errors enumerated in [SALOME platform 0019316] issue
2466     // and all errors from a new (Release 1.1) MeshGems User Manual
2467     switch ( errNum ) {
2468     case 0015: // The face number (numfac) with vertices (f 1, f 2, f 3) has a null vertex.
2469     case 1005620 : // a too bad quality face is detected. This face is considered degenerated.
2470       ptr = getIds(ptr, SKIP_ID, nodeIds);
2471       ptr = getIds(ptr, TRIA, nodeIds);
2472       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2473       break;
2474     case 1005621 : // a too bad quality face is detected. This face is degenerated.
2475       // hence the is degenerated it is invisible, add its edges in addition
2476       ptr = getIds(ptr, SKIP_ID, nodeIds);
2477       ptr = getIds(ptr, TRIA, nodeIds);
2478       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2479       {
2480         vector<int> edgeNodes( nodeIds.begin(), --nodeIds.end() ); // 01
2481         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
2482         edgeNodes[1] = nodeIds[2]; // 02
2483         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
2484         edgeNodes[0] = nodeIds[1]; // 12
2485       }      
2486       break;
2487     case 1000: // Face (f 1, f 2, f 3) appears more than once in the input surface mesh.
2488       // ERR  1000 :  1 3 2
2489     case 1002: // Face (f 1, f 2, f 3) has a vertex negative or null
2490     case 3019: // Constrained face (f 1, f 2, f 3) cannot be enforced
2491     case 1002211: // a face has a vertex negative or null.
2492     case 1005200 : // a surface mesh appears more than once in the input surface mesh.
2493     case 1008423 : // a constrained face cannot be enforced (regeneration phase failed).
2494       ptr = getIds(ptr, TRIA, nodeIds);
2495       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2496       break;
2497     case 1001: // Edge (e1, e2) appears more than once in the input surface mesh
2498     case 3009: // Constrained edge (e1, e2) cannot be enforced (warning).
2499       // ERR  3109 :  EDGE  5 6 UNIQUE
2500     case 3109: // Edge (e1, e2) is unique (i.e., bounds a hole in the surface)
2501     case 1005210 : // an edge appears more than once in the input surface mesh.
2502     case 1005820 : // an edge is unique (i.e., bounds a hole in the surface).
2503     case 1008441 : // a constrained edge cannot be enforced.
2504       ptr = getIds(ptr, EDGE, nodeIds);
2505       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2506       break;
2507     case 2004: // Vertex v1 and vertex v2 are too close to one another or coincident (warning).
2508     case 2014: // at least two points whose distance is dist, i.e., considered as coincident
2509     case 2103: // Vertex v1 and vertex v2 are too close to one another or coincident (warning).
2510       // ERR  2103 :  16 WITH  3
2511     case 1005105 : // two vertices are too close to one another or coincident.
2512     case 1005107: // Two vertices are too close to one another or coincident.
2513       ptr = getIds(ptr, NODE, nodeIds);
2514       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2515       ptr = getIds(ptr, NODE, nodeIds);
2516       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2517       break;
2518     case 2012: // Vertex v1 cannot be inserted (warning).
2519     case 1005106 : // a vertex cannot be inserted.
2520       ptr = getIds(ptr, NODE, nodeIds);
2521       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2522       break;
2523     case 3103: // The surface edge (e1, e2) intersects another surface edge (e3, e4)
2524     case 1005110 : // two surface edges are intersecting.
2525       // ERR  3103 :  1 2 WITH  7 3
2526       ptr = getIds(ptr, EDGE, nodeIds);
2527       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2528       ptr = getIds(ptr, EDGE, nodeIds);
2529       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2530       break;
2531     case 3104: // The surface edge (e1, e2) intersects the surface face (f 1, f 2, f 3)
2532       // ERR  3104 :  9 10 WITH  1 2 3
2533     case 3106: // One surface edge (say e1, e2) intersects a surface face (f 1, f 2, f 3)
2534     case 1005120 : // a surface edge intersects a surface face.
2535       ptr = getIds(ptr, EDGE, nodeIds);
2536       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2537       ptr = getIds(ptr, TRIA, nodeIds);
2538       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2539       break;
2540     case 3105: // One boundary point (say p1) lies within a surface face (f 1, f 2, f 3)
2541       // ERR  3105 :  8 IN  2 3 5
2542     case 1005150 : // a boundary point lies within a surface face.
2543       ptr = getIds(ptr, NODE, nodeIds);
2544       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2545       ptr = getIds(ptr, TRIA, nodeIds);
2546       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2547       break;
2548     case 3107: // One boundary point (say p1) lies within a surface edge (e1, e2) (stop).
2549       // ERR  3107 :  2 IN  4 1
2550     case 1005160 : // a boundary point lies within a surface edge.
2551       ptr = getIds(ptr, NODE, nodeIds);
2552       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2553       ptr = getIds(ptr, EDGE, nodeIds);
2554       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2555       break;
2556     case 9000: // ERR  9000
2557       //  ELEMENT  261 WITH VERTICES :  7 396 -8 242
2558       //  VOLUME   : -1.11325045E+11 W.R.T. EPSILON   0.
2559       // A too small volume element is detected. Are reported the index of the element,
2560       // its four vertex indices, its volume and the tolerance threshold value
2561       ptr = getIds(ptr, SKIP_ID, nodeIds);
2562       ptr = getIds(ptr, VOL, nodeIds);
2563       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2564       // even if all nodes found, volume it most probably invisible,
2565       // add its faces to demonstrate it anyhow
2566       {
2567         vector<int> faceNodes( nodeIds.begin(), --nodeIds.end() ); // 012
2568         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
2569         faceNodes[2] = nodeIds[3]; // 013
2570         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
2571         faceNodes[1] = nodeIds[2]; // 023
2572         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
2573         faceNodes[0] = nodeIds[1]; // 123
2574         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
2575       }
2576       break;
2577     case 9001: // ERR  9001
2578       //  %% NUMBER OF NEGATIVE VOLUME TETS  :  1
2579       //  %% THE LARGEST NEGATIVE TET        :   1.75376581E+11
2580       //  %%  NUMBER OF NULL VOLUME TETS     :  0
2581       // There exists at least a null or negative volume element
2582       break;
2583     case 9002:
2584       // There exist n null or negative volume elements
2585       break;
2586     case 9003:
2587       // A too small volume element is detected
2588       break;
2589     case 9102:
2590       // A too bad quality face is detected. This face is considered degenerated,
2591       // its index, its three vertex indices together with its quality value are reported
2592       break; // same as next
2593     case 9112: // ERR  9112
2594       //  FACE   2 WITH VERTICES :  4 2 5
2595       //  SMALL INRADIUS :   0.
2596       // A too bad quality face is detected. This face is degenerated,
2597       // its index, its three vertex indices together with its inradius are reported
2598       ptr = getIds(ptr, SKIP_ID, nodeIds);
2599       ptr = getIds(ptr, TRIA, nodeIds);
2600       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2601       // add triangle edges as it most probably has zero area and hence invisible
2602       {
2603         vector<int> edgeNodes(2);
2604         edgeNodes[0] = nodeIds[0]; edgeNodes[1] = nodeIds[1]; // 0-1
2605         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
2606         edgeNodes[1] = nodeIds[2]; // 0-2
2607         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
2608         edgeNodes[0] = nodeIds[1]; // 1-2
2609         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
2610       }
2611       break;
2612     case 1005103 : // the vertices of an element are too close to one another or coincident.
2613       ptr = getIds(ptr, TRIA, nodeIds);
2614       if ( nodeIds.back() == 0 ) // index of the third vertex of the element (0 for an edge)
2615         nodeIds.resize( EDGE );
2616       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2617       break;
2618     }
2619
2620     bool isNewError = foundErrorStr.insert( string( errBeg, ptr )).second;
2621     if ( !isNewError )
2622       continue; // not to report same error several times
2623
2624 //     const SMDS_MeshElement* nullElem = 0;
2625 //     bool allElemsOk = ( find( badElems.begin(), badElems.end(), nullElem) == badElems.end());
2626
2627 //     if ( allElemsOk && !badElems.empty() && !elemErrorNums.empty() ) {
2628 //       bool oneMoreErrorType = elemErrorNums.insert( errNum ).second;
2629 //       if ( oneMoreErrorType )
2630 //         continue; // not to report different types of errors with bad elements
2631 //     }
2632
2633     // make error text
2634     string text = translateError( errNum );
2635     if ( errDescription.find( text ) == text.npos ) {
2636       if ( !errDescription.empty() )
2637         errDescription << "\n";
2638       errDescription << text;
2639     }
2640
2641   } // end while
2642
2643   if ( errDescription.empty() ) { // no errors found
2644     char msgLic1[] = "connection to server failed";
2645     char msgLic2[] = " Dlim ";
2646     if ( search( &buf[0], bufEnd, msgLic1, msgLic1 + strlen(msgLic1)) != bufEnd ||
2647          search( &buf[0], bufEnd, msgLic2, msgLic2 + strlen(msgLic2)) != bufEnd )
2648       errDescription << "Licence problems.";
2649     else
2650     {
2651       char msg2[] = "SEGMENTATION FAULT";
2652       if ( search( &buf[0], bufEnd, msg2, msg2 + strlen(msg2)) != bufEnd )
2653         errDescription << "MG-Tetra: SEGMENTATION FAULT. ";
2654     }
2655   }
2656
2657   if ( !isOk && logFile && logFile[0] )
2658   {
2659     if ( errDescription.empty() )
2660       errDescription << "See " << logFile << " for problem description";
2661     else
2662       errDescription << "\nSee " << logFile << " for more information";
2663   }
2664
2665   err->myComment = errDescription;
2666
2667   if ( err->myComment.empty() && !err->HasBadElems() )
2668     err = SMESH_ComputeError::New(); // OK
2669
2670   return err;
2671 }
2672
2673 //================================================================================
2674 /*!
2675  * \brief Creates _Ghs2smdsConvertor
2676  */
2677 //================================================================================
2678
2679 _Ghs2smdsConvertor::_Ghs2smdsConvertor( const map <int,const SMDS_MeshNode*> & ghs2NodeMap,
2680                                         SMESH_ProxyMesh::Ptr                   mesh)
2681   :_ghs2NodeMap( & ghs2NodeMap ), _nodeByGhsId( 0 ), _mesh( mesh )
2682 {
2683 }
2684
2685 //================================================================================
2686 /*!
2687  * \brief Creates _Ghs2smdsConvertor
2688  */
2689 //================================================================================
2690
2691 _Ghs2smdsConvertor::_Ghs2smdsConvertor( const vector <const SMDS_MeshNode*> &  nodeByGhsId,
2692                                         SMESH_ProxyMesh::Ptr                   mesh)
2693   : _ghs2NodeMap( 0 ), _nodeByGhsId( &nodeByGhsId ), _mesh( mesh )
2694 {
2695 }
2696
2697 //================================================================================
2698 /*!
2699  * \brief Return SMDS element by ids of MG-Tetra nodes
2700  */
2701 //================================================================================
2702
2703 const SMDS_MeshElement* _Ghs2smdsConvertor::getElement(const vector<int>& ghsNodes) const
2704 {
2705   size_t nbNodes = ghsNodes.size();
2706   vector<const SMDS_MeshNode*> nodes( nbNodes, 0 );
2707   for ( size_t i = 0; i < nbNodes; ++i ) {
2708     int ghsNode = ghsNodes[ i ];
2709     if ( _ghs2NodeMap ) {
2710       map <int,const SMDS_MeshNode*>::const_iterator in = _ghs2NodeMap->find( ghsNode);
2711       if ( in == _ghs2NodeMap->end() )
2712         return 0;
2713       nodes[ i ] = in->second;
2714     }
2715     else {
2716       if ( ghsNode < 1 || ghsNode > (int)_nodeByGhsId->size() )
2717         return 0;
2718       nodes[ i ] = (*_nodeByGhsId)[ ghsNode-1 ];
2719     }
2720   }
2721   if ( nbNodes == 1 )
2722     return nodes[0];
2723
2724   if ( nbNodes == 2 ) {
2725     const SMDS_MeshElement* edge= SMDS_Mesh::FindEdge( nodes[0], nodes[1] );
2726     if ( !edge || edge->GetID() < 1 || _mesh->IsTemporary( edge ))
2727       edge = new SMDS_LinearEdge( nodes[0], nodes[1] );
2728     return edge;
2729   }
2730   if ( nbNodes == 3 ) {
2731     const SMDS_MeshElement* face = SMDS_Mesh::FindFace( nodes );
2732     if ( !face || face->GetID() < 1 || _mesh->IsTemporary( face ))
2733       face = new SMDS_FaceOfNodes( nodes[0], nodes[1], nodes[2] );
2734     return face;
2735   }
2736   if ( nbNodes == 4 )
2737     return new SMDS_VolumeOfNodes( nodes[0], nodes[1], nodes[2], nodes[3] );
2738
2739   return 0;
2740 }
2741
2742 //================================================================================
2743 /*!
2744  * \brief Return a mesh
2745  */
2746 //================================================================================
2747
2748 const SMDS_Mesh* _Ghs2smdsConvertor::getMesh() const
2749 {
2750   return _mesh->GetMeshDS();
2751 }
2752
2753 //=============================================================================
2754 /*!
2755  *
2756  */
2757 //=============================================================================
2758 bool GHS3DPlugin_GHS3D::Evaluate(SMESH_Mesh& aMesh,
2759                                  const TopoDS_Shape& aShape,
2760                                  MapShapeNbElems& aResMap)
2761 {
2762   int nbtri = 0, nbqua = 0;
2763   double fullArea = 0.0;
2764   for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
2765     TopoDS_Face F = TopoDS::Face( exp.Current() );
2766     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
2767     MapShapeNbElemsItr anIt = aResMap.find(sm);
2768     if( anIt==aResMap.end() ) {
2769       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2770       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
2771                                             "Submesh can not be evaluated",this));
2772       return false;
2773     }
2774     std::vector<int> aVec = (*anIt).second;
2775     nbtri += Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
2776     nbqua += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
2777     GProp_GProps G;
2778     BRepGProp::SurfaceProperties(F,G);
2779     double anArea = G.Mass();
2780     fullArea += anArea;
2781   }
2782
2783   // collect info from edges
2784   int nb0d_e = 0, nb1d_e = 0;
2785   bool IsQuadratic = false;
2786   bool IsFirst = true;
2787   TopTools_MapOfShape tmpMap;
2788   for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
2789     TopoDS_Edge E = TopoDS::Edge(exp.Current());
2790     if( tmpMap.Contains(E) )
2791       continue;
2792     tmpMap.Add(E);
2793     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
2794     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
2795     std::vector<int> aVec = (*anIt).second;
2796     nb0d_e += aVec[SMDSEntity_Node];
2797     nb1d_e += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
2798     if(IsFirst) {
2799       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
2800       IsFirst = false;
2801     }
2802   }
2803   tmpMap.Clear();
2804
2805   double ELen = sqrt(2.* ( fullArea/(nbtri+nbqua*2) ) / sqrt(3.0) );
2806
2807   GProp_GProps G;
2808   BRepGProp::VolumeProperties(aShape,G);
2809   double aVolume = G.Mass();
2810   double tetrVol = 0.1179*ELen*ELen*ELen;
2811   double CoeffQuality = 0.9;
2812   int nbVols = int(aVolume/tetrVol/CoeffQuality);
2813   int nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
2814   int nb1d_in = (int) ( nbVols*6 - nb1d_e - nb1d_f ) / 5;
2815   std::vector<int> aVec(SMDSEntity_Last);
2816   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
2817   if( IsQuadratic ) {
2818     aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
2819     aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
2820     aVec[SMDSEntity_Quad_Pyramid] = nbqua;
2821   }
2822   else {
2823     aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
2824     aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
2825     aVec[SMDSEntity_Pyramid] = nbqua;
2826   }
2827   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
2828   aResMap.insert(std::make_pair(sm,aVec));
2829
2830   return true;
2831 }
2832
2833 bool GHS3DPlugin_GHS3D::importGMFMesh(const char* theGMFFileName, SMESH_Mesh& theMesh)
2834 {
2835   SMESH_ComputeErrorPtr err = theMesh.GMFToMesh( theGMFFileName, /*makeRequiredGroups =*/ true );
2836
2837   theMesh.GetMeshDS()->Modified();
2838
2839   return ( !err || err->IsOK());
2840 }
2841
2842 namespace
2843 {
2844   //================================================================================
2845   /*!
2846    * \brief Sub-mesh event listener setting enforced elements as soon as an enforced
2847    *        mesh is loaded
2848    */
2849   struct _EnforcedMeshRestorer : public SMESH_subMeshEventListener
2850   {
2851     _EnforcedMeshRestorer():
2852       SMESH_subMeshEventListener( /*isDeletable = */true, Name() )
2853     {}
2854
2855     //================================================================================
2856     /*!
2857      * \brief Returns an ID of listener
2858      */
2859     static const char* Name() { return "GHS3DPlugin_GHS3D::_EnforcedMeshRestorer"; }
2860
2861     //================================================================================
2862     /*!
2863      * \brief Treat events of the subMesh
2864      */
2865     void ProcessEvent(const int                       event,
2866                       const int                       eventType,
2867                       SMESH_subMesh*                  subMesh,
2868                       SMESH_subMeshEventListenerData* data,
2869                       const SMESH_Hypothesis*         hyp)
2870     {
2871       if ( SMESH_subMesh::SUBMESH_LOADED == event &&
2872            SMESH_subMesh::COMPUTE_EVENT  == eventType &&
2873            data &&
2874            !data->mySubMeshes.empty() )
2875       {
2876         // An enforced mesh (subMesh->_father) has been loaded from hdf file
2877         if ( GHS3DPlugin_Hypothesis* hyp = GetGHSHypothesis( data->mySubMeshes.front() ))
2878           hyp->RestoreEnfElemsByMeshes();
2879       }
2880     }
2881     //================================================================================
2882     /*!
2883      * \brief Returns GHS3DPlugin_Hypothesis used to compute a subMesh
2884      */
2885     static GHS3DPlugin_Hypothesis* GetGHSHypothesis( SMESH_subMesh* subMesh )
2886     {
2887       SMESH_HypoFilter ghsHypFilter
2888         ( SMESH_HypoFilter::HasName( GHS3DPlugin_Hypothesis::GetHypType() ));
2889       return (GHS3DPlugin_Hypothesis* )
2890         subMesh->GetFather()->GetHypothesis( subMesh->GetSubShape(),
2891                                              ghsHypFilter,
2892                                              /*visitAncestors=*/true);
2893     }
2894   };
2895
2896   //================================================================================
2897   /*!
2898    * \brief Sub-mesh event listener removing empty groups created due to "To make
2899    *        groups of domains".
2900    */
2901   struct _GroupsOfDomainsRemover : public SMESH_subMeshEventListener
2902   {
2903     _GroupsOfDomainsRemover():
2904       SMESH_subMeshEventListener( /*isDeletable = */true,
2905                                   "GHS3DPlugin_GHS3D::_GroupsOfDomainsRemover" ) {}
2906     /*!
2907      * \brief Treat events of the subMesh
2908      */
2909     void ProcessEvent(const int                       event,
2910                       const int                       eventType,
2911                       SMESH_subMesh*                  subMesh,
2912                       SMESH_subMeshEventListenerData* data,
2913                       const SMESH_Hypothesis*         hyp)
2914     {
2915       if (SMESH_subMesh::ALGO_EVENT == eventType &&
2916           !subMesh->GetAlgo() )
2917       {
2918         removeEmptyGroupsOfDomains( subMesh->GetFather(), /*notEmptyAsWell=*/true );
2919       }
2920     }
2921   };
2922 }
2923
2924 //================================================================================
2925 /*!
2926  * \brief Set an event listener to set enforced elements as soon as an enforced
2927  *        mesh is loaded
2928  */
2929 //================================================================================
2930
2931 void GHS3DPlugin_GHS3D::SubmeshRestored(SMESH_subMesh* subMesh)
2932 {
2933   if ( GHS3DPlugin_Hypothesis* hyp = _EnforcedMeshRestorer::GetGHSHypothesis( subMesh ))
2934   {
2935     GHS3DPlugin_Hypothesis::TGHS3DEnforcedMeshList enfMeshes = hyp->_GetEnforcedMeshes();
2936     GHS3DPlugin_Hypothesis::TGHS3DEnforcedMeshList::iterator it = enfMeshes.begin();
2937     for(;it != enfMeshes.end();++it) {
2938       GHS3DPlugin_Hypothesis::TGHS3DEnforcedMesh* enfMesh = *it;
2939       if ( SMESH_Mesh* mesh = GetMeshByPersistentID( enfMesh->persistID ))
2940       {
2941         SMESH_subMesh* smToListen = mesh->GetSubMesh( mesh->GetShapeToMesh() );
2942         // a listener set to smToListen will care of hypothesis stored in SMESH_EventListenerData
2943         subMesh->SetEventListener( new _EnforcedMeshRestorer(),
2944                                    SMESH_subMeshEventListenerData::MakeData( subMesh ),
2945                                    smToListen);
2946       }
2947     }
2948   }
2949 }
2950
2951 //================================================================================
2952 /*!
2953  * \brief Sets an event listener removing empty groups created due to "To make
2954  *        groups of domains".
2955  * \param subMesh - submesh where algo is set
2956  *
2957  * This method is called when a submesh gets HYP_OK algo_state.
2958  * After being set, event listener is notified on each event of a submesh.
2959  */
2960 //================================================================================
2961
2962 void GHS3DPlugin_GHS3D::SetEventListener(SMESH_subMesh* subMesh)
2963 {
2964   subMesh->SetEventListener( new _GroupsOfDomainsRemover(), 0, subMesh );
2965 }
2966
2967 //================================================================================
2968 /*!
2969  * \brief If possible, returns progress of computation [0.,1.]
2970  */
2971 //================================================================================
2972
2973 double GHS3DPlugin_GHS3D::GetProgress() const
2974 {
2975   if ( _isLibUsed )
2976   {
2977     // this->_progress is advanced by MG_Tetra_API according to messages from MG library
2978     // but sharply. Advance it a bit to get smoother advancement.
2979     GHS3DPlugin_GHS3D* me = const_cast<GHS3DPlugin_GHS3D*>( this );
2980     if ( _progress < 0.1 ) // the first message is at 10%
2981       me->_progress = GetProgressByTic();
2982     else if ( _progress < 0.98 )
2983       me->_progress += _progressAdvance;
2984     return _progress;
2985   }
2986
2987   return -1;
2988 }