Salome HOME
26f97394bb46dd8726ba5ae379086fcccc8c86e5
[plugins/ghs3dplugin.git] / src / GHS3DPlugin / GHS3DPlugin_Hypothesis.cxx
1 // Copyright (C) 2004-2022  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_Hypothesis.cxx
22 // Created   : Wed Apr  2 12:36:29 2008
23 // Author    : Edward AGAPOV (eap)
24 //=============================================================================
25 //
26 #include "GHS3DPlugin_Hypothesis.hxx"
27
28 #include <Basics_DirUtils.hxx>
29 #include <SMESHDS_Mesh.hxx>
30 #include <SMESH_File.hxx>
31
32 #include <TCollection_AsciiString.hxx>
33
34 #ifdef WIN32
35 #include <process.h>
36 #define getpid _getpid
37 #endif
38
39 using namespace std;
40
41 namespace
42 {
43   struct GET_DEFAULT // struct used to get default value from GetOptionValue()
44   {
45     bool isDefault;
46     operator bool* () { return &isDefault; }
47   };
48 }
49
50 //=======================================================================
51 //function : GHS3DPlugin_Hypothesis
52 //=======================================================================
53
54 GHS3DPlugin_Hypothesis::GHS3DPlugin_Hypothesis(int hypId, SMESH_Gen * gen)
55   : SMESH_Hypothesis(hypId, gen),
56     myToMeshHoles(DefaultMeshHoles()),
57     myToMakeGroupsOfDomains(DefaultToMakeGroupsOfDomains()),
58     myMaximumMemory(-1),
59     myInitialMemory(-1),
60     myOptimizationLevel(DefaultOptimizationLevel()),
61     myKeepFiles(DefaultKeepFiles()),
62     myWorkingDirectory(DefaultWorkingDirectory()),
63     myVerboseLevel(DefaultVerboseLevel()),
64     myToCreateNewNodes(DefaultToCreateNewNodes()),
65     myToUseBoundaryRecoveryVersion(DefaultToUseBoundaryRecoveryVersion()),
66     myToUseFemCorrection(DefaultToUseFEMCorrection()),
67     myToRemoveCentralPoint(DefaultToRemoveCentralPoint()),
68     myLogInStandardOutput(DefaultStandardOutputLog()),
69     myRemoveLogOnSuccess( DefaultRemoveLogOnSuccess() ),
70     myGradation(DefaultGradation()),
71     myUseVolumeProximity(DefaultUseVolumeProximity()),
72     myNbVolumeProximityLayers(DefaultNbVolumeProximityLayers()),
73     myAlgorithm(DefaultAlgorithm()),    
74     myNumOfThreads(DefaultNumOfThreads()),
75     myUseNumOfThreads(false),
76     myPthreadModeMG(0),
77     myPthreadModeMGHPC(0),
78     myMinSize(0),
79     myMinSizeDefault(0),
80     myMaxSize(0),
81     myMaxSizeDefault(0)
82 {
83   _name = GetHypType();
84   _param_algo_dim = 3;
85
86   const char* boolOptionNames[] = { "no_initial_central_point",                          // no
87                                     "force_max_size",                                    // no
88                                     "apply_gradation_on_skin_vertex_sizes",              // yes
89                                     "optimise_worst_elements",                           // no
90                                     "force_output_quadratic_mesh",                       // no
91                                     "rectify_jacobian",                                  // yes
92                                     "jacobian_rectification_respect_input_surface_mesh", // yes
93                                     "" // mark of end
94   };
95   const char* intOptionNames[] = { "max_number_of_errors_printed", // 1
96                                    "" // mark of end
97   };
98   const char* doubleOptionNames[] = { "target_quality",  // 0
99                                       "sliver_angle",    // 5
100                                       "" // mark of end
101   };
102   const char* charOptionNames[] = { "boundary_regeneration",            // standard
103                                     "split_overconstrained_tetrahedra", // no
104                                     "" // mark of end
105   };
106   _commonMGTetraAdvancedOptions = { "split_overconstrained_tetrahedra" };
107   int i = 0;
108   while (boolOptionNames[i][0])
109   {
110     _boolOptions.insert( boolOptionNames[i] );
111     _option2value[boolOptionNames[i++]].clear();
112   }
113   i = 0;
114   while (intOptionNames[i][0])
115     _option2value[intOptionNames[i++]].clear();
116   
117   i = 0;
118   while (doubleOptionNames[i][0]) {
119     _doubleOptions.insert(doubleOptionNames[i]);
120     _option2value[doubleOptionNames[i++]].clear();
121   }
122   i = 0;
123   while (charOptionNames[i][0]) {
124     _charOptions.insert(charOptionNames[i]);
125     _option2value[charOptionNames[i++]].clear();
126   }
127
128   // default values to be used while MG meshing
129
130   _defaultOptionValues["no_initial_central_point"                         ] = "no";
131   _defaultOptionValues["force_max_size"                                   ] = "no";
132   _defaultOptionValues["apply_gradation_on_skin_vertex_sizes"             ] = "yes";
133   _defaultOptionValues["optimise_worst_elements"                          ] = "no";
134   _defaultOptionValues["force_output_quadratic_mesh"                      ] = "no";
135   _defaultOptionValues["rectify_jacobian"                                 ] = "yes";
136   _defaultOptionValues["jacobian_rectification_respect_input_surface_mesh"] = "yes";
137   _defaultOptionValues["max_number_of_errors_printed"                     ] = "1";
138   _defaultOptionValues["target_quality"                                   ] = "";//NoValue();
139   _defaultOptionValues["sliver_angle"                                     ] = "5";
140   _defaultOptionValues["boundary_regeneration"                            ] = "standard";
141   _defaultOptionValues["split_overconstrained_tetrahedra"                 ] = "no";
142
143 #ifdef _DEBUG_
144   // check validity of option names of _defaultOptionValues
145   TOptionValues::iterator n2v = _defaultOptionValues.begin();
146   for ( ; n2v != _defaultOptionValues.end(); ++n2v )
147     ASSERT( _option2value.count( n2v->first ));
148   ASSERT( _option2value.size() == _defaultOptionValues.size() );
149 #endif
150 }
151
152 //=======================================================================
153 //function : SetToMeshHoles
154 //=======================================================================
155
156 void GHS3DPlugin_Hypothesis::SetToMeshHoles(bool toMesh)
157 {
158   if ( myToMeshHoles != toMesh ) {
159     myToMeshHoles = toMesh;
160     NotifySubMeshesHypothesisModification();
161   }
162 }
163
164 //=======================================================================
165 //function : GetToMeshHoles
166 //=======================================================================
167
168 bool GHS3DPlugin_Hypothesis::GetToMeshHoles(bool checkFreeOption) const
169 {
170   if ( checkFreeOption )
171   {
172     std::string optionName = "components";
173     TOptionValues::const_iterator op_val = _customOption2value.find(optionName);
174     if ( op_val != _customOption2value.end())
175     {
176       if ( op_val->second.find("all"))
177         return true;
178       if ( op_val->second.find("outside_components"))
179         return false;
180     }
181   }
182   return myToMeshHoles;
183 }
184
185 //=======================================================================
186 //function : SetToMakeGroupsOfDomains
187 //=======================================================================
188
189 void GHS3DPlugin_Hypothesis::SetToMakeGroupsOfDomains(bool toMakeGroups)
190 {
191   if ( myToMakeGroupsOfDomains != toMakeGroups ) {
192     myToMakeGroupsOfDomains = toMakeGroups;
193     NotifySubMeshesHypothesisModification();
194   }
195 }
196
197 //=======================================================================
198 //function : GetToMakeGroupsOfDomains
199 //=======================================================================
200
201 bool GHS3DPlugin_Hypothesis::GetToMakeGroupsOfDomains() const
202 {
203   return myToMakeGroupsOfDomains;
204 }
205
206 //=======================================================================
207 //function : GetToMakeGroupsOfDomains
208 //=======================================================================
209
210 bool GHS3DPlugin_Hypothesis::GetToMakeGroupsOfDomains(const GHS3DPlugin_Hypothesis* hyp)
211 {
212   bool res;
213   if ( hyp ) res = /*hyp->GetToMeshHoles(true) &&*/ hyp->GetToMakeGroupsOfDomains();
214   else       res = /*DefaultMeshHoles()        &&*/ DefaultToMakeGroupsOfDomains();
215   return res;
216 }
217
218 //=======================================================================
219 //function : SetMaximumMemory
220 //=======================================================================
221
222 void GHS3DPlugin_Hypothesis::SetMaximumMemory(float MB)
223 {
224   if ( myMaximumMemory != MB ) {
225     myMaximumMemory = MB;
226     NotifySubMeshesHypothesisModification();
227   }
228 }
229
230 //=======================================================================
231 //function : GetMaximumMemory
232 //           * automatic memory adjustment mode. Default is zero
233 //=======================================================================
234
235 float GHS3DPlugin_Hypothesis::GetMaximumMemory() const
236 {
237   return myMaximumMemory;
238 }
239
240 //=======================================================================
241 //function : SetInitialMemory
242 //=======================================================================
243
244 void GHS3DPlugin_Hypothesis::SetInitialMemory(float MB)
245 {
246   if ( myInitialMemory != MB ) {
247     myInitialMemory = MB;
248     NotifySubMeshesHypothesisModification();
249   }
250 }
251
252 //=======================================================================
253 //function : GetInitialMemory
254 //=======================================================================
255
256 float GHS3DPlugin_Hypothesis::GetInitialMemory() const
257 {
258   return myInitialMemory;
259 }
260
261 //=======================================================================
262 //function : SetOptimizationLevel
263 //=======================================================================
264
265 void GHS3DPlugin_Hypothesis::SetOptimizationLevel(OptimizationLevel level)
266 {
267   if ( myOptimizationLevel != level ) {
268     myOptimizationLevel = level;
269     NotifySubMeshesHypothesisModification();
270   }
271 }
272
273 //=======================================================================
274 //function : GetOptimizationLevel
275 //=======================================================================
276
277 GHS3DPlugin_Hypothesis::OptimizationLevel GHS3DPlugin_Hypothesis::GetOptimizationLevel() const
278 {
279   return (OptimizationLevel) myOptimizationLevel;
280 }
281
282 //=======================================================================
283 //function : SetWorkingDirectory
284 //=======================================================================
285
286 void GHS3DPlugin_Hypothesis::SetWorkingDirectory(const std::string& path)
287 {
288   if ( myWorkingDirectory != path ) {
289     myWorkingDirectory = path;
290     NotifySubMeshesHypothesisModification();
291   }
292 }
293
294 //=======================================================================
295 //function : GetWorkingDirectory
296 //=======================================================================
297
298 std::string GHS3DPlugin_Hypothesis::GetWorkingDirectory() const
299 {
300   return myWorkingDirectory;
301 }
302
303 //=======================================================================
304 //function : SetKeepFiles
305 //=======================================================================
306
307 void GHS3DPlugin_Hypothesis::SetKeepFiles(bool toKeep)
308 {
309   if ( myKeepFiles != toKeep ) {
310     myKeepFiles = toKeep;
311     NotifySubMeshesHypothesisModification();
312   }
313 }
314
315 //=======================================================================
316 //function : GetKeepFiles
317 //=======================================================================
318
319 bool GHS3DPlugin_Hypothesis::GetKeepFiles() const
320 {
321   return myKeepFiles;
322 }
323
324 //=======================================================================
325 //function : SetVerboseLevel
326 //=======================================================================
327
328 void GHS3DPlugin_Hypothesis::SetVerboseLevel(short level)
329 {
330   if ( myVerboseLevel != level ) {
331     myVerboseLevel = level;
332     NotifySubMeshesHypothesisModification();
333   }
334 }
335
336 //=======================================================================
337 //function : GetVerboseLevel
338 //=======================================================================
339
340 short GHS3DPlugin_Hypothesis::GetVerboseLevel() const
341 {
342   return myVerboseLevel;
343 }
344
345 //=======================================================================
346 //function : SetToCreateNewNodes
347 //=======================================================================
348
349 void GHS3DPlugin_Hypothesis::SetToCreateNewNodes(bool toCreate)
350 {
351   if ( myToCreateNewNodes != toCreate ) {
352     myToCreateNewNodes = toCreate;
353     NotifySubMeshesHypothesisModification();
354   }
355 }
356
357 //=======================================================================
358 //function : SetAlgorithm
359 //=======================================================================
360 void GHS3DPlugin_Hypothesis::SetAlgorithm(ImplementedAlgorithms algoId)
361 {
362   if ( myAlgorithm != algoId ) {
363     myAlgorithm = algoId;
364     NotifySubMeshesHypothesisModification();
365   }
366 }
367
368 //=======================================================================
369 //function :   short GetAlgorithm() const;
370
371 //=======================================================================
372 GHS3DPlugin_Hypothesis::ImplementedAlgorithms GHS3DPlugin_Hypothesis::GetAlgorithm() const
373 {
374   return (ImplementedAlgorithms) myAlgorithm;
375 }
376
377 //=======================================================================
378 //function : SetPthreadMode
379 //=======================================================================
380 void GHS3DPlugin_Hypothesis::SetPthreadMode(PThreadMode pThreadsMode )
381 {
382   if ( myPthreadModeMG != pThreadsMode ) {
383     myPthreadModeMG = pThreadsMode;
384     NotifySubMeshesHypothesisModification();
385   }
386 }
387
388 //=======================================================================
389 //function :   short GetPthreadMode() const;
390
391 //=======================================================================
392 GHS3DPlugin_Hypothesis::PThreadMode GHS3DPlugin_Hypothesis::GetPthreadMode() const
393 {
394   return (PThreadMode)myPthreadModeMG;
395 }
396
397 //=======================================================================
398 //function : SetParallelMode
399 //=======================================================================
400 void GHS3DPlugin_Hypothesis::SetParallelMode(ParallelMode parallelMode )
401 {
402   if ( myPthreadModeMGHPC != parallelMode ) {
403     myPthreadModeMGHPC = parallelMode;
404     NotifySubMeshesHypothesisModification();
405   }
406 }
407
408 //=======================================================================
409 //function :   short GetParallelMode() const;
410
411 //=======================================================================
412 GHS3DPlugin_Hypothesis::ParallelMode GHS3DPlugin_Hypothesis::GetParallelMode() const
413 {
414   return (ParallelMode)myPthreadModeMGHPC;
415 }
416
417 //=======================================================================
418 //function : SetUseNumOfThreads
419 //=======================================================================
420 void GHS3DPlugin_Hypothesis::SetUseNumOfThreads(bool setUseOfThreads)
421 {
422   if ( myUseNumOfThreads != setUseOfThreads ) {
423     myUseNumOfThreads = setUseOfThreads;
424     NotifySubMeshesHypothesisModification();
425   }
426 }
427
428 //=======================================================================
429 //function :   bool GetUseNumOfThreads() const;
430
431 //=======================================================================
432 bool GHS3DPlugin_Hypothesis::GetUseNumOfThreads() const
433 {
434   return myUseNumOfThreads;
435 }
436
437 //=======================================================================
438 //function : SetNumOfThreads
439 //=======================================================================
440 void GHS3DPlugin_Hypothesis::SetNumOfThreads(short numOfThreads)
441 {
442   if ( myNumOfThreads != numOfThreads ) {
443     myNumOfThreads = numOfThreads;
444     NotifySubMeshesHypothesisModification();
445   }
446 }
447
448 //=======================================================================
449 //function :   short GetUseNumOfThreads() const;
450
451 //=======================================================================
452 short GHS3DPlugin_Hypothesis::GetNumOfThreads() const
453 {
454   return myNumOfThreads;
455 }
456
457 //=======================================================================
458 //function : GetToCreateNewNodes
459 //=======================================================================
460 bool GHS3DPlugin_Hypothesis::GetToCreateNewNodes() const
461 {
462   return myToCreateNewNodes;
463 }
464
465 //=======================================================================
466 //function : SetToUseBoundaryRecoveryVersion
467 //=======================================================================
468
469 void GHS3DPlugin_Hypothesis::SetToUseBoundaryRecoveryVersion(bool toUse)
470 {
471   if ( myToUseBoundaryRecoveryVersion != toUse ) {
472     myToUseBoundaryRecoveryVersion = toUse;
473     NotifySubMeshesHypothesisModification();
474   }
475 }
476
477 //=======================================================================
478 //function : GetToUseBoundaryRecoveryVersion
479 //=======================================================================
480
481 bool GHS3DPlugin_Hypothesis::GetToUseBoundaryRecoveryVersion() const
482 {
483   return myToUseBoundaryRecoveryVersion;
484 }
485
486 //=======================================================================
487 //function : SetFEMCorrection
488 //=======================================================================
489
490 void GHS3DPlugin_Hypothesis::SetFEMCorrection(bool toUseFem)
491 {
492   if ( myToUseFemCorrection != toUseFem ) {
493     myToUseFemCorrection = toUseFem;
494     NotifySubMeshesHypothesisModification();
495   }
496 }
497
498 //=======================================================================
499 //function : GetFEMCorrection
500 //=======================================================================
501
502 bool GHS3DPlugin_Hypothesis::GetFEMCorrection() const
503 {
504   return myToUseFemCorrection;
505 }
506
507 //=======================================================================
508 //function : SetToRemoveCentralPoint
509 //=======================================================================
510
511 void GHS3DPlugin_Hypothesis::SetToRemoveCentralPoint(bool toRemove)
512 {
513   SetOptionValue( "no_initial_central_point", toRemove ? "yes" : "no" );
514   myToRemoveCentralPoint = toRemove;
515 }
516
517 //=======================================================================
518 //function : GetToRemoveCentralPoint
519 //=======================================================================
520
521 bool GHS3DPlugin_Hypothesis::GetToRemoveCentralPoint() const
522 {
523   return myToRemoveCentralPoint;
524 }
525
526 //=======================================================================
527 //function : SetAdvancedOption
528 //=======================================================================
529
530 void GHS3DPlugin_Hypothesis::SetAdvancedOption(const std::string& option)
531 {
532   size_t wsPos = option.find(' ');
533   if ( wsPos == string::npos )
534   {
535     SetOptionValue( option, "" );
536   }
537   else
538   {
539     std::string opt( option, 0, wsPos );
540     std::string val( option, wsPos + 1 );
541     SetOptionValue( opt, val );
542   }
543 }
544
545 //=======================================================================
546 //function : GetAdvancedOption
547 //=======================================================================
548
549 std::string GHS3DPlugin_Hypothesis::GetAdvancedOption() const
550 {
551   SMESH_Comment txt;
552
553   TOptionValues::const_iterator o2v = _option2value.begin();
554   for ( ; o2v != _option2value.end(); ++o2v )
555     if ( !o2v->second.empty() )
556     {
557       if ( !txt.empty() )
558         txt << " ";
559       txt << o2v->first << " " << o2v->second;
560     }
561   for ( o2v = _customOption2value.begin(); o2v != _customOption2value.end(); ++o2v )
562   {
563     if ( !txt.empty() )
564       txt << " ";
565     txt << o2v->first << " " << o2v->second;
566   }
567   return txt;
568 }
569
570 //=======================================================================
571 //function : SetGradation
572 //=======================================================================
573
574 void GHS3DPlugin_Hypothesis::SetGradation(double gradation)
575 {
576   if ( myGradation != gradation ) {
577     myGradation = gradation;
578     NotifySubMeshesHypothesisModification();
579   }
580 }
581
582 //=======================================================================
583 //function : GetGradation
584 //=======================================================================
585
586 double GHS3DPlugin_Hypothesis::GetGradation() const
587 {
588   return myGradation;
589 }
590
591 //=============================================================================
592 void GHS3DPlugin_Hypothesis::SetMinSize(double theMinSize)
593 {
594   if ( theMinSize != myMinSize )
595   {
596     myMinSize = theMinSize;
597     NotifySubMeshesHypothesisModification();
598   }
599 }
600
601 //=============================================================================
602 void GHS3DPlugin_Hypothesis::SetMaxSize(double theMaxSize)
603 {
604   if ( theMaxSize != myMaxSize )
605   {
606     myMaxSize = theMaxSize;
607     NotifySubMeshesHypothesisModification();
608   }
609 }
610
611 //=============================================================================
612 void GHS3DPlugin_Hypothesis::SetUseVolumeProximity( bool toUse )
613 {
614   if ( myUseVolumeProximity != toUse )
615   {
616     myUseVolumeProximity = toUse;
617     NotifySubMeshesHypothesisModification();
618   }
619 }
620
621 //=============================================================================
622 void GHS3DPlugin_Hypothesis::SetNbVolumeProximityLayers( int nbLayers )
623 {
624   if ( myNbVolumeProximityLayers != nbLayers )
625   {
626     myNbVolumeProximityLayers = nbLayers;
627     NotifySubMeshesHypothesisModification();
628   }
629 }
630
631 //=======================================================================
632 //function : SetStandardOutputLog
633 //=======================================================================
634
635 void GHS3DPlugin_Hypothesis::SetStandardOutputLog(bool logInStandardOutput)
636 {
637   if ( myLogInStandardOutput != logInStandardOutput ) {
638     myLogInStandardOutput = logInStandardOutput;
639     NotifySubMeshesHypothesisModification();
640   }
641 }
642
643 //=======================================================================
644 //function : GetStandardOutputLog
645 //=======================================================================
646
647 bool GHS3DPlugin_Hypothesis::GetStandardOutputLog() const
648 {
649   return myLogInStandardOutput;
650 }
651
652 //=======================================================================
653 //function : SetRemoveLogOnSuccess
654 //=======================================================================
655
656 void GHS3DPlugin_Hypothesis::SetRemoveLogOnSuccess(bool removeLogOnSuccess)
657 {
658   if ( myRemoveLogOnSuccess != removeLogOnSuccess ) {
659     myRemoveLogOnSuccess = removeLogOnSuccess;
660     NotifySubMeshesHypothesisModification();
661   }
662 }
663
664 //=======================================================================
665 //function : GetRemoveLogOnSuccess
666 //=======================================================================
667
668 bool GHS3DPlugin_Hypothesis::GetRemoveLogOnSuccess() const
669 {
670   return myRemoveLogOnSuccess;
671 }
672
673 //=======================================================================
674 //function : SetEnforcedVertex
675 //=======================================================================
676
677 bool GHS3DPlugin_Hypothesis::SetEnforcedVertex(std::string theName,
678                                                std::string theEntry,
679                                                std::string theGroupName,
680                                                double      size,
681                                                double x, double y, double z,
682                                                bool        isCompound)
683 {
684   MESSAGE("GHS3DPlugin_Hypothesis::SetEnforcedVertex(\""<< theName << "\", \""<< theEntry << "\", \"" << theGroupName << "\", "
685                                                       << size << ", " << x << ", " << y << ", " << z  << ", "<< isCompound << ")");
686
687   bool toNotify = false;
688   bool toCreate = true;
689
690   TGHS3DEnforcedVertex *oldEnVertex;
691   TGHS3DEnforcedVertex *newEnfVertex = new TGHS3DEnforcedVertex();
692   newEnfVertex->name = theName;
693   newEnfVertex->geomEntry = theEntry;
694   newEnfVertex->coords.clear();
695   if (!isCompound) {
696     newEnfVertex->coords.push_back(x);
697     newEnfVertex->coords.push_back(y);
698     newEnfVertex->coords.push_back(z);
699   }
700   newEnfVertex->groupName = theGroupName;
701   newEnfVertex->size = size;
702   newEnfVertex->isCompound = isCompound;
703   
704   
705   // update _enfVertexList
706   TGHS3DEnforcedVertexList::iterator it = _enfVertexList.find(newEnfVertex);
707   if (it != _enfVertexList.end()) {
708     toCreate = false;
709     oldEnVertex = (*it);
710     MESSAGE("Enforced Vertex was found => Update");
711     if (oldEnVertex->name != theName) {
712       MESSAGE("Update name from \"" << oldEnVertex->name << "\" to \"" << theName << "\"");
713       oldEnVertex->name = theName;
714       toNotify = true;
715     }
716     if (oldEnVertex->groupName != theGroupName) {
717       MESSAGE("Update group name from \"" << oldEnVertex->groupName << "\" to \"" << theGroupName << "\"");
718       oldEnVertex->groupName = theGroupName;
719       toNotify = true;
720     }
721     if (oldEnVertex->size != size) {
722       MESSAGE("Update size from \"" << oldEnVertex->size << "\" to \"" << size << "\"");
723       oldEnVertex->size = size;
724       toNotify = true;
725     }
726     if (toNotify) {
727       // update map coords / enf vertex if needed
728       if (oldEnVertex->coords.size()) {
729         _coordsEnfVertexMap[oldEnVertex->coords] = oldEnVertex;
730         _enfVertexCoordsSizeList[oldEnVertex->coords] = size;
731       }
732
733       // update map geom entry / enf vertex if needed
734       if (oldEnVertex->geomEntry != "") {
735         _geomEntryEnfVertexMap[oldEnVertex->geomEntry] = oldEnVertex;
736         _enfVertexEntrySizeList[oldEnVertex->geomEntry] = size;
737       }
738     }
739   }
740
741 //   //////// CREATE ////////////
742   if (toCreate) {
743     toNotify = true;
744     MESSAGE("Creating new enforced vertex");
745     _enfVertexList.insert(newEnfVertex);
746     if (theEntry == "") {
747       _coordsEnfVertexMap[newEnfVertex->coords] = newEnfVertex;
748       _enfVertexCoordsSizeList[newEnfVertex->coords] = size;
749     }
750     else {
751       _geomEntryEnfVertexMap[newEnfVertex->geomEntry] = newEnfVertex;
752       _enfVertexEntrySizeList[newEnfVertex->geomEntry] = size;
753     }
754   }
755
756   if (toNotify)
757     NotifySubMeshesHypothesisModification();
758
759   MESSAGE("GHS3DPlugin_Hypothesis::SetEnforcedVertex END");
760   return toNotify;
761 }
762
763
764 //=======================================================================
765 //function : SetEnforcedMesh
766 //=======================================================================
767 bool GHS3DPlugin_Hypothesis::SetEnforcedMesh(SMESH_Mesh& theMesh, SMESH::ElementType elementType, std::string name, std::string entry, std::string groupName)
768 {
769   TIDSortedElemSet theElemSet;
770   SMDS_ElemIteratorPtr eIt = theMesh.GetMeshDS()->elementsIterator(SMDSAbs_ElementType(elementType));
771   while ( eIt->more() )
772     theElemSet.insert( eIt->next() );
773   MESSAGE("Add "<<theElemSet.size()<<" types["<<elementType<<"] from source mesh");
774   bool added = SetEnforcedElements( theElemSet, elementType, groupName);
775   if (added) {
776     TGHS3DEnforcedMesh* newEnfMesh = new TGHS3DEnforcedMesh();
777     newEnfMesh->persistID   = theMesh.GetMeshDS()->GetPersistentId();
778     newEnfMesh->name        = name;
779     newEnfMesh->entry       = entry;
780     newEnfMesh->elementType = elementType;
781     newEnfMesh->groupName   = groupName;
782     
783     TGHS3DEnforcedMeshList::iterator it = _enfMeshList.find(newEnfMesh);
784     if (it == _enfMeshList.end()) {
785       _entryEnfMeshMap[entry].insert(newEnfMesh);
786       _enfMeshList.insert(newEnfMesh);
787     }
788     else {
789       delete newEnfMesh;
790     }
791   }
792   return added;
793 }
794
795 //=======================================================================
796 //function : SetEnforcedGroup
797 //=======================================================================
798 bool GHS3DPlugin_Hypothesis::SetEnforcedGroup(const SMESHDS_Mesh* theMeshDS, SMESH::smIdType_array_var theIDs, SMESH::ElementType elementType, std::string name, std::string entry, std::string groupName)
799 {
800   MESSAGE("GHS3DPlugin_Hypothesis::SetEnforcedGroup");
801   TIDSortedElemSet theElemSet;
802     if ( theIDs->length() == 0 ){MESSAGE("The source group is empty");}
803     for ( CORBA::ULong i = 0; i < theIDs->length(); i++) {
804       SMESH::smIdType ind = theIDs[i];
805       if (elementType == SMESH::NODE)
806       {
807         const SMDS_MeshNode * node = theMeshDS->FindNode(ind);
808         if (node)
809           theElemSet.insert( node );
810       }
811       else
812       {
813         const SMDS_MeshElement * elem = theMeshDS->FindElement(ind);
814         if (elem)
815           theElemSet.insert( elem );
816       }
817     }
818
819 //   SMDS_ElemIteratorPtr it = theGroup->GetGroupDS()->GetElements();
820 //   while ( it->more() ) 
821 //     theElemSet.insert( it->next() );
822
823   MESSAGE("Add "<<theElemSet.size()<<" types["<<elementType<<"] from source group ");
824   bool added = SetEnforcedElements( theElemSet, elementType, groupName);
825   if (added) {
826     TGHS3DEnforcedMesh* newEnfMesh = new TGHS3DEnforcedMesh();
827     newEnfMesh->name = name;
828     newEnfMesh->entry = entry;
829     newEnfMesh->elementType = elementType;
830     newEnfMesh->groupName = groupName;
831     
832     TGHS3DEnforcedMeshList::iterator it = _enfMeshList.find(newEnfMesh);
833     if (it == _enfMeshList.end()) {
834       _entryEnfMeshMap[entry].insert(newEnfMesh);
835       _enfMeshList.insert(newEnfMesh);
836     }
837   }
838   return added;
839 }
840
841 //=======================================================================
842 //function : SetEnforcedElements
843 //=======================================================================
844 bool GHS3DPlugin_Hypothesis::SetEnforcedElements(TIDSortedElemSet theElemSet, SMESH::ElementType elementType, std::string groupName)
845 {
846   MESSAGE("GHS3DPlugin_Hypothesis::SetEnforcedElements");
847   TIDSortedElemSet::const_iterator it = theElemSet.begin();
848   const SMDS_MeshElement* elem;
849   const SMDS_MeshNode* node;
850   bool added = true;
851   pair<TIDSortedNodeGroupMap::iterator,bool> nodeRet;
852   pair<TIDSortedElemGroupMap::iterator,bool> elemRet;
853
854   for (;it != theElemSet.end();++it)
855   {
856     elem = (*it);
857     switch (elementType) {
858       case SMESH::NODE:
859         node = dynamic_cast<const SMDS_MeshNode*>(elem);
860         if (node) {
861           nodeRet = _enfNodes.insert(make_pair(node,groupName));
862           added = added && nodeRet.second;
863           string msg = added ? "yes":"no";
864           MESSAGE( "Node (" <<node->X()<<","<<node->Y()<<","<<node->Z()<< ") with ID " << node->GetID() <<" added ? " << msg);
865         }
866         else {
867           SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
868           for (;nodeIt->more();) {
869             node = dynamic_cast<const SMDS_MeshNode*>(nodeIt->next());
870             nodeRet = _enfNodes.insert(make_pair(node,groupName));
871             added = added && nodeRet.second;
872           }
873         }
874         break;
875       case SMESH::EDGE:
876         if (elem->GetType() == SMDSAbs_Edge) {
877           elemRet = _enfEdges.insert(make_pair(elem,groupName));
878           added = added && elemRet.second;
879         }
880         else if (elem->GetType() > SMDSAbs_Edge) {
881           // SMDS_ElemIteratorPtr it = elem->edgesIterator();
882           // for (;it->more();) {
883           //   const SMDS_MeshElement* anEdge = it->next();
884           //   elemRet = _enfEdges.insert(make_pair(anEdge,groupName));
885           //   added = added && elemRet.second;
886           // }
887         }
888         break;
889       case SMESH::FACE:
890         if (elem->GetType() == SMDSAbs_Face)
891         {
892           if (elem->NbCornerNodes() == 3) {
893             elemRet = _enfTriangles.insert(make_pair(elem,groupName));
894             added = added && elemRet.second;
895           }
896         }
897         else if (elem->GetType() > SMDSAbs_Face) { // Group of faces
898           // SMDS_ElemIteratorPtr it = elem->facesIterator();
899           // for (;it->more();) {
900           //   const SMDS_MeshElement* aFace = it->next();
901           //   if (aFace->NbCornerNodes() == 3) {
902           //     elemRet = _enfTriangles.insert(make_pair(aFace,groupName));
903           //     added = added && elemRet.second;
904           //   }
905           // }
906         }
907         break;
908       default:
909         break;
910     };
911   }
912   if (added)
913     NotifySubMeshesHypothesisModification();
914   return added;
915 }
916
917
918 //=======================================================================
919 //function : GetEnforcedVertex
920 //=======================================================================
921
922 GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertex* GHS3DPlugin_Hypothesis::GetEnforcedVertex(double x, double y, double z)
923 {
924   std::vector<double> coord(3);
925   coord[0] = x;
926   coord[1] = y;
927   coord[2] = z;
928   if (_coordsEnfVertexMap.count(coord)>0)
929     return _coordsEnfVertexMap[coord];
930   std::ostringstream msg ;
931   msg << "No enforced vertex at " << x << ", " << y << ", " << z;
932   throw std::invalid_argument(msg.str());
933 }
934
935 GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertex* GHS3DPlugin_Hypothesis::GetEnforcedVertex(const std::string theEntry)
936 {
937   if (_geomEntryEnfVertexMap.count(theEntry)>0)
938     return _geomEntryEnfVertexMap[theEntry];
939   
940   std::ostringstream msg ;
941   msg << "No enforced vertex with entry " << theEntry;
942   throw std::invalid_argument(msg.str());
943 }
944
945 //=======================================================================
946 //function : RemoveEnforcedVertex
947 //=======================================================================
948
949 bool GHS3DPlugin_Hypothesis::RemoveEnforcedVertex(double x, double y, double z, const std::string theEntry)
950 {
951   bool toNotify = false;
952   std::ostringstream msg;
953   TGHS3DEnforcedVertex *oldEnfVertex;
954   std::vector<double> coords(3);
955   coords[0] = x;
956   coords[1] = y;
957   coords[2] = z;
958   
959   // check that enf vertex with given enf vertex entry exists
960   TGeomEntryGHS3DEnforcedVertexMap::iterator it_enfVertexEntry = _geomEntryEnfVertexMap.find(theEntry);
961   if (it_enfVertexEntry != _geomEntryEnfVertexMap.end()) {
962     // Success
963     MESSAGE("Found enforced vertex with geom entry " << theEntry);
964     oldEnfVertex = it_enfVertexEntry->second;
965     _geomEntryEnfVertexMap.erase(it_enfVertexEntry);
966   } else {
967     // Fail
968     MESSAGE("Enforced vertex with geom entry " << theEntry << " not found");
969     // check that enf vertex with given coords exists
970     TCoordsGHS3DEnforcedVertexMap::iterator it_coords_enf = _coordsEnfVertexMap.find(coords);
971     if (it_coords_enf != _coordsEnfVertexMap.end()) {
972       // Success
973       MESSAGE("Found enforced vertex with coords " << x << ", " << y << ", " << z);
974       oldEnfVertex = it_coords_enf->second;
975       _coordsEnfVertexMap.erase(it_coords_enf);
976       _enfVertexCoordsSizeList.erase(_enfVertexCoordsSizeList.find(coords));
977     } else {
978       // Fail
979       MESSAGE("Enforced vertex with coords " << x << ", " << y << ", " << z << " not found");
980       throw std::invalid_argument(msg.str());
981     }
982   }
983
984   MESSAGE("Remove enf vertex from _enfVertexList");
985
986   // update _enfVertexList
987   TGHS3DEnforcedVertexList::iterator it = _enfVertexList.find(oldEnfVertex);
988   if (it != _enfVertexList.end()) {
989     if ((*it)->groupName != "")
990       _groupsToRemove.insert((*it)->groupName);
991     _enfVertexList.erase(it);
992     toNotify = true;
993     MESSAGE("Done");
994   }
995
996   if (toNotify)
997     NotifySubMeshesHypothesisModification();
998
999   return toNotify;
1000 }
1001
1002 //=======================================================================
1003 //function : ClearEnforcedVertices
1004 //=======================================================================
1005 void GHS3DPlugin_Hypothesis::ClearEnforcedVertices()
1006 {
1007   TGHS3DEnforcedVertexList::const_iterator it = _enfVertexList.begin();
1008   for(;it != _enfVertexList.end();++it) {
1009     if ((*it)->groupName != "")
1010       _groupsToRemove.insert((*it)->groupName);
1011   }
1012   _enfVertexList.clear();
1013   _coordsEnfVertexMap.clear();
1014   _geomEntryEnfVertexMap.clear();
1015   _enfVertexCoordsSizeList.clear();
1016   _enfVertexEntrySizeList.clear();
1017   NotifySubMeshesHypothesisModification();
1018 }
1019
1020 //=======================================================================
1021 //function : ClearEnforcedMeshes
1022 //=======================================================================
1023 void GHS3DPlugin_Hypothesis::ClearEnforcedMeshes()
1024 {
1025   TGHS3DEnforcedMeshList::const_iterator it = _enfMeshList.begin();
1026   for(;it != _enfMeshList.end();++it) {
1027     if ((*it)->groupName != "")
1028       _groupsToRemove.insert((*it)->groupName);
1029   }
1030   _enfNodes.clear();
1031   _enfEdges.clear();
1032   _enfTriangles.clear();
1033   _nodeIDToSizeMap.clear();
1034   _enfMeshList.clear();
1035   _entryEnfMeshMap.clear();
1036   NotifySubMeshesHypothesisModification();
1037 }
1038
1039 //================================================================================
1040 /*!
1041  * \brief At mesh loading, restore enforced elements by just loaded enforced meshes
1042  */
1043 //================================================================================
1044
1045 void GHS3DPlugin_Hypothesis::RestoreEnfElemsByMeshes()
1046 {
1047   TGHS3DEnforcedMeshList::const_iterator it = _enfMeshList.begin();
1048   for(;it != _enfMeshList.end();++it) {
1049     TGHS3DEnforcedMesh* enfMesh = *it;
1050     if ( SMESH_Mesh* mesh = GetMeshByPersistentID( enfMesh->persistID ))
1051       SetEnforcedMesh( *mesh,
1052                        enfMesh->elementType,
1053                        enfMesh->name,
1054                        enfMesh->entry,
1055                        enfMesh->groupName );
1056     enfMesh->persistID = -1; // not to restore again
1057   }
1058 }
1059
1060 //=======================================================================
1061 //function : SetGroupsToRemove
1062 //=======================================================================
1063
1064 void GHS3DPlugin_Hypothesis::ClearGroupsToRemove()
1065 {
1066   _groupsToRemove.clear();
1067 }
1068
1069
1070 //=======================================================================
1071 //function : DefaultMeshHoles
1072 //=======================================================================
1073
1074 bool GHS3DPlugin_Hypothesis::DefaultMeshHoles()
1075 {
1076   return false; // PAL19680
1077 }
1078
1079 //=======================================================================
1080 //function : DefaultToMakeGroupsOfDomains
1081 //=======================================================================
1082
1083 bool GHS3DPlugin_Hypothesis::DefaultToMakeGroupsOfDomains()
1084 {
1085   return false; // issue 0022172
1086 }
1087
1088 //=======================================================================
1089 //function : DefaultMaximumMemory
1090 //=======================================================================
1091
1092 #if defined(WIN32)
1093 #include <windows.h>
1094 #elif !defined(__APPLE__)
1095 #include <sys/sysinfo.h>
1096 #endif
1097
1098 float GHS3DPlugin_Hypothesis::DefaultMaximumMemory()
1099 {
1100 #if defined(WIN32)
1101   // See http://msdn.microsoft.com/en-us/library/aa366589.aspx
1102   MEMORYSTATUSEX statex;
1103   statex.dwLength = sizeof (statex);
1104   long err = GlobalMemoryStatusEx (&statex);
1105   if (err != 0) {
1106     double totMB = double( statex.ullAvailPhys ) / 1024. / 1024.;
1107     return float( 0.7 * totMB );
1108   }
1109 #elif !defined(__APPLE__)
1110   struct sysinfo si;
1111   long err = sysinfo( &si );
1112   if ( err == 0 ) {
1113     double ramMB = double( si.totalram * si.mem_unit / 1024 / 1024 );
1114     return float( 0.7 * ramMB );
1115   }
1116 #endif
1117   return 1024;
1118 }
1119
1120 //=======================================================================
1121 //function : DefaultInitialMemory
1122 //=======================================================================
1123
1124 float GHS3DPlugin_Hypothesis::DefaultInitialMemory()
1125 {
1126   return DefaultMaximumMemory();
1127 }
1128
1129 //=======================================================================
1130 //function : DefaultOptimizationLevel
1131 //=======================================================================
1132
1133 short GHS3DPlugin_Hypothesis::DefaultOptimizationLevel()
1134 {
1135   return Medium;
1136 }
1137
1138 //=======================================================================
1139 //function : DefaultWorkingDirectory
1140 //=======================================================================
1141
1142 std::string GHS3DPlugin_Hypothesis::DefaultWorkingDirectory()
1143 {
1144   TCollection_AsciiString aTmpDir;
1145
1146   char *Tmp_dir = getenv("SALOME_TMP_DIR");
1147   if(Tmp_dir != NULL) {
1148     aTmpDir = Tmp_dir;
1149   }
1150   else {
1151 #ifdef WIN32
1152     aTmpDir = TCollection_AsciiString("C:\\");
1153 #else
1154     aTmpDir = TCollection_AsciiString("/tmp/");
1155 #endif
1156   }
1157   return aTmpDir.ToCString();
1158 }
1159
1160 //=======================================================================
1161 //function : DefaultKeepFiles
1162 //=======================================================================
1163
1164 bool   GHS3DPlugin_Hypothesis::DefaultKeepFiles()
1165 {
1166   return false;
1167 }
1168
1169 //=======================================================================
1170 //function : DefaultRemoveLogOnSuccess
1171 //=======================================================================
1172
1173 bool   GHS3DPlugin_Hypothesis::DefaultRemoveLogOnSuccess()
1174 {
1175   return false;
1176 }
1177
1178
1179 //=======================================================================
1180 //function : DefaultVerboseLevel
1181 //=======================================================================
1182
1183 short  GHS3DPlugin_Hypothesis::DefaultVerboseLevel()
1184 {
1185   return 10;
1186 }
1187
1188 //=======================================================================
1189 //function : DefaultToCreateNewNodes
1190 //=======================================================================
1191
1192 bool GHS3DPlugin_Hypothesis::DefaultToCreateNewNodes()
1193 {
1194   return true;
1195 }
1196
1197 //=======================================================================
1198 //function : DefaultToUseBoundaryRecoveryVersion
1199 //=======================================================================
1200
1201 bool GHS3DPlugin_Hypothesis::DefaultToUseBoundaryRecoveryVersion()
1202 {
1203   return false;
1204 }
1205
1206 //=======================================================================
1207 //function : DefaultToUseFEMCorrection
1208 //=======================================================================
1209
1210 bool GHS3DPlugin_Hypothesis::DefaultToUseFEMCorrection()
1211 {
1212   return false;
1213 }
1214
1215 //=======================================================================
1216 //function : DefaultToRemoveCentralPoint
1217 //=======================================================================
1218
1219 bool GHS3DPlugin_Hypothesis::DefaultToRemoveCentralPoint()
1220 {
1221   return false;
1222 }
1223
1224 //=======================================================================
1225 //function : DefaultStandardOutputLog
1226 //=======================================================================
1227
1228 bool GHS3DPlugin_Hypothesis::DefaultStandardOutputLog()
1229 {
1230   return false;
1231 }
1232
1233 // //=======================================================================
1234 // //function : DefaultID2SizeMap
1235 // //=======================================================================
1236 // 
1237 // GHS3DPlugin_Hypothesis::TID2SizeMap GHS3DPlugin_Hypothesis::DefaultID2SizeMap()
1238 // {
1239 //   return GHS3DPlugin_Hypothesis::TID2SizeMap();
1240 // }
1241
1242
1243 //=======================================================================
1244 //function : SaveTo
1245 //=======================================================================
1246
1247 std::ostream & GHS3DPlugin_Hypothesis::SaveTo(std::ostream & save)
1248 {
1249   save << (int) myToMeshHoles                 << " ";
1250   save << myMaximumMemory                     << " ";
1251   save << myInitialMemory                     << " ";
1252   save << myOptimizationLevel                 << " ";
1253   save << myWorkingDirectory                  << " ";
1254   save << (int)myKeepFiles                    << " ";
1255   save << myVerboseLevel                      << " ";
1256   save << (int)myToCreateNewNodes             << " ";
1257   save << (int)myToUseBoundaryRecoveryVersion << " ";
1258   save << (int)myToUseFemCorrection           << " ";
1259   save << (int)myToRemoveCentralPoint         << " ";
1260   save << myGradation                         << " ";
1261   save << myToMakeGroupsOfDomains             << " ";
1262   // if (!myTextOption.empty()) {
1263   //   save << "__OPTIONS_BEGIN__ ";
1264   //   save << myTextOption                      << " ";
1265   //   save << "__OPTIONS_END__ ";
1266   // }
1267   
1268
1269   TGHS3DEnforcedVertexList::iterator it  = _enfVertexList.begin();
1270   if (it != _enfVertexList.end()) {
1271     save << " " << "__ENFORCED_VERTICES_BEGIN__ ";
1272     for ( ; it != _enfVertexList.end(); ++it ) {
1273       TGHS3DEnforcedVertex *enfVertex = (*it);
1274       save << " " << "__BEGIN_VERTEX__";
1275       if (!enfVertex->name.empty()) {
1276         save << " " << "__BEGIN_NAME__";
1277         save << " " << enfVertex->name;
1278         save << " " << "__END_NAME__";
1279       }
1280       if (!enfVertex->geomEntry.empty()) {
1281         save << " " << "__BEGIN_ENTRY__";
1282         save << " " << enfVertex->geomEntry;
1283         save << " " << enfVertex->isCompound;
1284         save << " " << "__END_ENTRY__";
1285       }
1286       if (!enfVertex->groupName.empty()) {
1287         save << " " << "__BEGIN_GROUP__";
1288         save << " " << enfVertex->groupName;
1289         save << " " << "__END_GROUP__";
1290       }
1291       if (enfVertex->coords.size()) {
1292         save << " " << "__BEGIN_COORDS__";
1293         for ( size_t i = 0; i < enfVertex->coords.size(); i++ )
1294           save << " " << enfVertex->coords[i];
1295         save << " " << "__END_COORDS__";
1296       }
1297       save << " " << "__BEGIN_SIZE__";
1298       save << " " << enfVertex->size;
1299       save << " " << "__END_SIZE__";
1300       save << " " << "__END_VERTEX__";
1301     }
1302     save << " " << "__ENFORCED_VERTICES_END__ ";
1303   }
1304
1305   TGHS3DEnforcedMeshList::iterator it_mesh  = _enfMeshList.begin();
1306   if (it_mesh != _enfMeshList.end()) {
1307     save << " " << "__ENFORCED_MESHES_BEGIN__ ";
1308     for ( ; it_mesh != _enfMeshList.end(); ++it_mesh ) {
1309       TGHS3DEnforcedMesh *enfMesh = (*it_mesh);
1310       save << " " << "__BEGIN_ENF_MESH__";
1311
1312       save << " " << "__BEGIN_NAME__";
1313       save << " " << enfMesh->name;
1314       save << " " << "__END_NAME__";
1315
1316       save << " " << "__BEGIN_ENTRY__";
1317       save << " " << enfMesh->entry;
1318       save << " " << "__END_ENTRY__";
1319
1320       save << " " << "__BEGIN_ELEM_TYPE__";
1321       save << " " << (int)enfMesh->elementType;
1322       save << " " << "__END_ELEM_TYPE__";
1323
1324       if (!enfMesh->groupName.empty()) {
1325         save << " " << "__BEGIN_GROUP__";
1326         save << " " << enfMesh->groupName;
1327         save << " " << "__END_GROUP__";
1328       }
1329       save << " " << "__PERSIST_ID__";
1330       save << " " << enfMesh->persistID;
1331       save << " " << "__END_ENF_MESH__";
1332       std::cout << "Saving of enforced mesh " << enfMesh->name.c_str() << " done" << std::endl;
1333     }
1334     save << " "  << "__ENFORCED_MESHES_END__ ";
1335   }
1336
1337   // New options in 2.9.6 (issue #17784)
1338
1339   save << " " << myUseVolumeProximity;
1340   save << " " << myNbVolumeProximityLayers;
1341   save << " " << myMinSize;
1342   save << " " << myMaxSize;
1343   save << " " << myMinSizeDefault;
1344   save << " " << myMaxSizeDefault;
1345
1346   save << " " << _option2value.size();
1347   TOptionValues::iterator o2v = _option2value.begin();
1348   for ( ; o2v != _option2value.end(); ++o2v )
1349     save << " -" << o2v->first << " -" << o2v->second;
1350   
1351   save << " " << _customOption2value.size();
1352   for ( o2v = _customOption2value.begin(); o2v != _customOption2value.end(); ++o2v )
1353     save << " -" << o2v->first << " -" << o2v->second;
1354
1355   return save;
1356 }
1357
1358 //=======================================================================
1359 //function : LoadFrom
1360 //=======================================================================
1361
1362 std::istream & GHS3DPlugin_Hypothesis::LoadFrom(std::istream & load)
1363 {
1364   bool isOK = true;
1365   int i;
1366   double d;
1367
1368   isOK = static_cast<bool>(load >> i);
1369   if (isOK)
1370     myToMeshHoles = i;
1371   else
1372     load.clear(ios::badbit | load.rdstate());
1373
1374   isOK = static_cast<bool>(load >> d);
1375   if (isOK)
1376     myMaximumMemory = float( d );
1377   else
1378     load.clear(ios::badbit | load.rdstate());
1379
1380   isOK = static_cast<bool>(load >> d);
1381   if (isOK)
1382     myInitialMemory = float( d );
1383   else
1384     load.clear(ios::badbit | load.rdstate());
1385
1386   isOK = static_cast<bool>(load >> i);
1387   if (isOK)
1388     myOptimizationLevel = (short int) i;
1389   else
1390     load.clear(ios::badbit | load.rdstate());
1391
1392   isOK = static_cast<bool>(load >> myWorkingDirectory);
1393   if (isOK) {
1394     if ( myWorkingDirectory == "0") { // myWorkingDirectory was empty
1395       myKeepFiles = false;
1396       myWorkingDirectory.clear();
1397     }
1398     else if ( myWorkingDirectory == "1" ) {
1399       myKeepFiles = true;
1400       myWorkingDirectory.clear();
1401     }
1402   }
1403   else
1404     load.clear(ios::badbit | load.rdstate());
1405
1406   if ( !myWorkingDirectory.empty() ) {
1407     isOK = static_cast<bool>(load >> i);
1408     if (isOK)
1409       myKeepFiles = i;
1410     else
1411       load.clear(ios::badbit | load.rdstate());
1412   }
1413
1414   isOK = static_cast<bool>(load >> i);
1415   if (isOK)
1416     myVerboseLevel = (short) i;
1417   else
1418     load.clear(ios::badbit | load.rdstate());
1419
1420   isOK = static_cast<bool>(load >> i);
1421   if (isOK)
1422     myToCreateNewNodes = (bool) i;
1423   else
1424     load.clear(ios::badbit | load.rdstate());
1425
1426   isOK = static_cast<bool>(load >> i);
1427   if (isOK)
1428     myToUseBoundaryRecoveryVersion = (bool) i;
1429   else
1430     load.clear(ios::badbit | load.rdstate());
1431
1432   isOK = static_cast<bool>(load >> i);
1433   if (isOK)
1434     myToUseFemCorrection = (bool) i;
1435   else
1436     load.clear(ios::badbit | load.rdstate());
1437
1438   isOK = static_cast<bool>(load >> i);
1439   if (isOK)
1440     myToRemoveCentralPoint = (bool) i;
1441   else
1442     load.clear(ios::badbit | load.rdstate());
1443
1444   isOK = static_cast<bool>(load >> d);
1445   if (isOK)
1446     myGradation = d;
1447   else
1448     load.clear(ios::badbit | load.rdstate());
1449
1450   std::string separator;
1451   bool hasOptions = false;
1452   bool hasEnforcedVertices = false;
1453   bool hasEnforcedMeshes = false;
1454   isOK = static_cast<bool>(load >> separator);
1455
1456   if ( isOK && ( separator == "0" || separator == "1" ))
1457   {
1458     myToMakeGroupsOfDomains = ( separator == "1" );
1459     isOK = static_cast<bool>(load >> separator);
1460   }
1461
1462   if (isOK) {
1463     if (separator == "__OPTIONS_BEGIN__")
1464       hasOptions = true;
1465     else if (separator == "__ENFORCED_VERTICES_BEGIN__")
1466       hasEnforcedVertices = true;
1467     else if (separator == "__ENFORCED_MESHES_BEGIN__")
1468       hasEnforcedMeshes = true;
1469   }
1470
1471   if (hasOptions) {
1472     std::string txt;
1473     while (isOK) {
1474       isOK = static_cast<bool>(load >> txt);
1475       if (isOK) {
1476         if (txt == "__OPTIONS_END__") {
1477           // if (!myTextOption.empty()) {
1478           //   // Remove last space
1479           //   myTextOption.erase(myTextOption.end()-1);
1480           // }
1481           isOK = false;
1482           break;
1483         }
1484         // myTextOption += txt;
1485         // myTextOption += " ";
1486       }
1487     }
1488   }
1489
1490   if (hasOptions) {
1491     isOK = static_cast<bool>(load >> separator);
1492     if (isOK && separator == "__ENFORCED_VERTICES_BEGIN__")
1493       hasEnforcedVertices = true;
1494     if (isOK && separator == "__ENFORCED_MESHES_BEGIN__")
1495       hasEnforcedMeshes = true;
1496   }
1497
1498   if (hasEnforcedVertices) {
1499     std::string txt, name, entry, groupName;
1500     double size, coords[3];
1501     bool isCompound;
1502     bool hasCoords = false;
1503     isOK = static_cast<bool>(load >> txt);  // __BEGIN_VERTEX__
1504     while (isOK) {
1505       if (txt == "__ENFORCED_VERTICES_END__") {
1506         //isOK = false;
1507         break;
1508       }
1509       
1510       TGHS3DEnforcedVertex *enfVertex = new TGHS3DEnforcedVertex();
1511       while (isOK) {
1512         isOK = static_cast<bool>(load >> txt);
1513         if (txt == "__END_VERTEX__") {
1514           enfVertex->name = name;
1515           enfVertex->geomEntry = entry;
1516           enfVertex->isCompound = isCompound;
1517           enfVertex->groupName = groupName;
1518           enfVertex->coords.clear();
1519           if (hasCoords)
1520             enfVertex->coords.assign(coords,coords+3);
1521
1522           _enfVertexList.insert(enfVertex);
1523
1524           if (enfVertex->coords.size())
1525             _coordsEnfVertexMap[enfVertex->coords] = enfVertex;
1526           if (!enfVertex->geomEntry.empty())
1527             _geomEntryEnfVertexMap[enfVertex->geomEntry] = enfVertex;
1528
1529           name.clear();
1530           entry.clear();
1531           groupName.clear();
1532           hasCoords = false;
1533           isOK = false;
1534         }
1535
1536         if (txt == "__BEGIN_NAME__") {  // __BEGIN_NAME__
1537           while (isOK && (txt != "__END_NAME__")) {
1538             isOK = static_cast<bool>(load >> txt);
1539             if (txt != "__END_NAME__") {
1540               if (!name.empty())
1541                 name += " ";
1542               name += txt;
1543             }
1544           }
1545           MESSAGE("name: " <<name);
1546         }
1547
1548         if (txt == "__BEGIN_ENTRY__") {  // __BEGIN_ENTRY__
1549           isOK = static_cast<bool>(load >> entry);
1550           isOK = static_cast<bool>(load >> isCompound);
1551           isOK = static_cast<bool>(load >> txt); // __END_ENTRY__
1552           if (txt != "__END_ENTRY__")
1553             throw std::exception();
1554           MESSAGE("entry: " << entry);
1555         }
1556
1557         if (txt == "__BEGIN_GROUP__") {  // __BEGIN_GROUP__
1558           while (isOK && (txt != "__END_GROUP__")) {
1559             isOK = static_cast<bool>(load >> txt);
1560             if (txt != "__END_GROUP__") {
1561               if (!groupName.empty())
1562                 groupName += " ";
1563               groupName += txt;
1564             }
1565           }
1566           MESSAGE("groupName: " << groupName);
1567         }
1568
1569         if (txt == "__BEGIN_COORDS__") {  // __BEGIN_COORDS__
1570           hasCoords = true;
1571           isOK = static_cast<bool>(load >> coords[0] >> coords[1] >> coords[2]);
1572           isOK = static_cast<bool>(load >> txt); // __END_COORDS__
1573           if (txt != "__END_COORDS__")
1574             throw std::exception();
1575           MESSAGE("coords: " << coords[0] <<","<< coords[1] <<","<< coords[2]);
1576         }
1577
1578         if (txt == "__BEGIN_SIZE__") {  // __BEGIN_ENTRY__
1579           isOK = static_cast<bool>(load >> size);
1580           isOK = static_cast<bool>(load >> txt); // __END_ENTRY__
1581           if (txt != "__END_SIZE__") {
1582             throw std::exception();
1583           }
1584           MESSAGE("size: " << size);
1585         }
1586       }
1587       isOK = static_cast<bool>(load >> txt);  // __BEGIN_VERTEX__
1588     }
1589   }
1590
1591   if (hasEnforcedVertices) {
1592     isOK = static_cast<bool>(load >> separator);
1593     if (isOK && separator == "__ENFORCED_MESHES_BEGIN__")
1594       hasEnforcedMeshes = true;
1595   }
1596
1597   if (hasEnforcedMeshes) {
1598     std::string txt, name, entry, groupName;
1599     int elementType = -1, persistID = -1;
1600     isOK = static_cast<bool>(load >> txt);  // __BEGIN_ENF_MESH__
1601     while (isOK) {
1602       //                if (isOK) {
1603       if (txt == "__ENFORCED_MESHES_END__")
1604         isOK = false;
1605
1606       TGHS3DEnforcedMesh *enfMesh = new TGHS3DEnforcedMesh();
1607       while (isOK) {
1608         isOK = static_cast<bool>(load >> txt);
1609         if (txt == "__END_ENF_MESH__") {
1610           enfMesh->name = name;
1611           enfMesh->entry = entry;
1612           enfMesh->elementType = (SMESH::ElementType)elementType;
1613           enfMesh->groupName = groupName;
1614           enfMesh->persistID = persistID;
1615
1616           _enfMeshList.insert(enfMesh);
1617           //std::cout << "Restoring of enforced mesh " <<name  << " done" << std::endl;
1618
1619           name.clear();
1620           entry.clear();
1621           elementType = -1;
1622           groupName.clear();
1623           persistID = -1;
1624           isOK = false;
1625         }
1626
1627         if (txt == "__BEGIN_NAME__") {  // __BEGIN_NAME__
1628           while (isOK && (txt != "__END_NAME__")) {
1629             isOK = static_cast<bool>(load >> txt);
1630             if (txt != "__END_NAME__") {
1631               if (!name.empty())
1632                 name += " ";
1633               name += txt;
1634             }
1635           }
1636           MESSAGE("name: " <<name);
1637         }
1638
1639         if (txt == "__BEGIN_ENTRY__") {  // __BEGIN_ENTRY__
1640           isOK = static_cast<bool>(load >> entry);
1641           isOK = static_cast<bool>(load >> txt); // __END_ENTRY__
1642           if (txt != "__END_ENTRY__")
1643             throw std::exception();
1644           MESSAGE("entry: " << entry);
1645         }
1646
1647         if (txt == "__BEGIN_ELEM_TYPE__") {  // __BEGIN_ELEM_TYPE__
1648           isOK = static_cast<bool>(load >> elementType);
1649           isOK = static_cast<bool>(load >> txt); // __END_ELEM_TYPE__
1650           if (txt != "__END_ELEM_TYPE__")
1651             throw std::exception();
1652           MESSAGE("elementType: " << elementType);
1653         }
1654
1655         if (txt == "__BEGIN_GROUP__") {  // __BEGIN_GROUP__
1656           while (isOK && (txt != "__END_GROUP__")) {
1657             isOK = static_cast<bool>(load >> txt);
1658             if (txt != "__END_GROUP__") {
1659               if (!groupName.empty())
1660                 groupName += " ";
1661               groupName += txt;
1662             }
1663           } // while
1664           MESSAGE("groupName: " << groupName);
1665         } // if
1666
1667         if (txt == "__PERSIST_ID__") {
1668           isOK = static_cast<bool>(load >> persistID);
1669           MESSAGE("persistID: " << persistID);
1670         }
1671         //std::cout << "isOK: " << isOK << std::endl;
1672       } // while
1673       //                } // if
1674       isOK = static_cast<bool>(load >> txt);  // __BEGIN_ENF_MESH__
1675     } // while
1676   } // if
1677
1678   // New options in 2.9.6 (issue #17784)
1679
1680   if ( ! hasOptions && ! hasEnforcedVertices && ! hasEnforcedMeshes )
1681     myUseVolumeProximity = ( separator == "1" );
1682   else if ( static_cast<bool>( load >> i ))
1683     myUseVolumeProximity = (bool) i;
1684
1685   if ( static_cast<bool>( load >> myNbVolumeProximityLayers ))
1686   {
1687     load >> myMinSize;
1688     load >> myMaxSize;
1689     load >> myMinSizeDefault;
1690     load >> myMaxSizeDefault;
1691
1692     std::string option, value;
1693     if ( static_cast<bool>( load >> i ) && i >= 0 )
1694     {
1695       for ( int nbRead = 0; nbRead < i; ++nbRead )
1696       {
1697         load >> option >> value;
1698         _option2value[ std::string( option, 1 )] = std::string( value, 1 );
1699       }
1700     }
1701     if ( static_cast<bool>( load >> i ) && i >= 0 )
1702     {
1703       for ( int nbRead = 0; nbRead < i; ++nbRead )
1704       {
1705         load >> option >> value;
1706         _customOption2value[ std::string( option, 1 )] = std::string( value, 1 );
1707       }
1708     }
1709   }
1710
1711   return load;
1712 }
1713
1714 //=======================================================================
1715 //function : SetParametersByMesh
1716 //=======================================================================
1717
1718 bool GHS3DPlugin_Hypothesis::SetParametersByMesh(const SMESH_Mesh* ,const TopoDS_Shape&)
1719 {
1720   return false;
1721 }
1722
1723
1724 //================================================================================
1725 /*!
1726  * \brief Sets myToMakeGroupsOfDomains depending on whether theMesh is on shape or not
1727  */
1728 //================================================================================
1729
1730 bool GHS3DPlugin_Hypothesis::SetParametersByDefaults(const TDefaults&  dflts,
1731                                                      const SMESH_Mesh* /*theMesh*/)
1732 {
1733   myToMakeGroupsOfDomains = ( !dflts._shape || dflts._shape->IsNull() );
1734
1735   double diagonal = dflts._elemLength * _gen->GetBoundaryBoxSegmentation();
1736   myMinSizeDefault = 1e-3 * diagonal;
1737   myMaxSizeDefault = diagonal / 5.;
1738
1739   return true;
1740 }
1741
1742 void GHS3DPlugin_Hypothesis::SetAdvancedOptionsInCommandLine( std::string & cmd, bool isMGTetra ) const
1743 {
1744   std::string option, value;
1745   bool isDefault;
1746   const TOptionValues* options[] = { & this->_option2value, & this->_customOption2value };
1747   for ( int iOp = 0; iOp < 2; ++iOp )
1748   {
1749     TOptionValues::const_iterator o2v = options[iOp]->begin();
1750     for ( ; o2v != options[iOp]->end(); ++o2v )
1751     {
1752       option = o2v->first;
1753       value = this->GetOptionValue( option, &isDefault );
1754       std::cout << option << ", " << value << std::endl;
1755
1756       if ( isDefault )
1757         continue;
1758
1759       if ( value.empty() )//value == NoValue() )
1760       {
1761         if ( this->_defaultOptionValues.count( option ))
1762           continue; // non-custom option with no value
1763         //value.clear();
1764       }    
1765
1766       if ( strncmp( "no", option.c_str(), 2 ) == 0 ) // options w/o values: --no_*
1767       {
1768         if ( !value.empty() && ToBool( value ) == false )
1769           continue;
1770         value.clear();
1771       }
1772
1773       if ( option[0] != '-' )
1774         cmd += " --";
1775       else
1776         cmd += " ";
1777       cmd += option + " " + value;
1778     }
1779   }
1780 }
1781
1782 //================================================================================
1783 /*!
1784  * \brief Return command to run MG-Tetra mesher excluding file prefix (-f)
1785  */
1786 //================================================================================
1787
1788 std::string GHS3DPlugin_Hypothesis::CommandToRun(const GHS3DPlugin_Hypothesis* hyp,
1789                                                  const bool                    hasShapeToMesh,
1790                                                  const bool                    forExecutable)
1791 {
1792   std::string cmd = GetExeName();
1793   // check if any option is overridden by hyp->myTextOption
1794   bool max_memory     = hyp ? !hyp->HasOptionDefined("max_memory")               : true;
1795   bool auto_memory    = hyp ? !hyp->HasOptionDefined("automatic_memory")         : true;
1796   bool comp           = hyp ? !hyp->HasOptionDefined("components")               : true;
1797   bool optim_level    = hyp ? !hyp->HasOptionDefined("optimisation_level")       : true;
1798   bool no_int_points  = hyp ? !hyp->HasOptionDefined("no_internal_points")       : true;
1799   bool C              = hyp ? !hyp->HasOptionDefined("-C")                       : true;
1800   bool verbose        = hyp ? !hyp->HasOptionDefined("verbose")                  : true;
1801   bool gra            = hyp ? !hyp->HasOptionDefined("-Dcpropa")                 : true;
1802   bool rem            = hyp ? !hyp->HasOptionDefined("no_initial_central_point") : true;
1803   //bool fem            = hyp ? !hyp->HasOptionDefined("-FEM")                     : true;
1804
1805   // if use boundary recovery version, few options are allowed
1806   bool useBndRecovery = !C;
1807   if ( !useBndRecovery && hyp )
1808     useBndRecovery = hyp->myToUseBoundaryRecoveryVersion;
1809
1810   // MG-Tetra needs to know amount of memory it may use (MB).
1811   // Default memory is defined at MG-Tetra installation but it may be not enough,
1812   // so allow to use about all available memory
1813   if ( max_memory ) {
1814     float aMaximumMemory = hyp ? hyp->myMaximumMemory : -1;
1815     cmd += " --max_memory ";
1816     if ( aMaximumMemory < 0 ) cmd += SMESH_Comment( int( DefaultMaximumMemory() ));
1817     else                      cmd += SMESH_Comment( int( aMaximumMemory ));
1818   }
1819   if ( auto_memory && !useBndRecovery ) {
1820     float aInitialMemory = hyp ? hyp->myInitialMemory : -1;
1821     cmd += " --automatic_memory ";
1822     if ( aInitialMemory > 0 ) cmd += SMESH_Comment( int( aInitialMemory ));
1823     else                      cmd += "100";
1824   }
1825   // component to mesh
1826   if ( comp && !useBndRecovery ) {
1827     // We always run MG-Tetra with "to mesh holes'==TRUE (see PAL19680)
1828     if ( hasShapeToMesh )
1829       cmd += " --components all";
1830     else {
1831       bool aToMeshHoles = hyp ? hyp->myToMeshHoles : DefaultMeshHoles();
1832       if ( aToMeshHoles ) cmd += " --components all";
1833       else                cmd += " --components outside_components";
1834     }
1835   }
1836   const bool toCreateNewNodes = ( no_int_points && ( !hyp || hyp->myToCreateNewNodes ));
1837
1838   // optimization level
1839   if ( !toCreateNewNodes ) {
1840     cmd += " --optimisation_level none"; // issue 22608
1841   }
1842   else if ( optim_level && hyp && !useBndRecovery ) {
1843     if ( hyp->myOptimizationLevel >= 0 && hyp->myOptimizationLevel < 5 ) {
1844       const char* level[] = { "none" , "light" , "standard" , "standard+" , "strong" };
1845       cmd += " --optimisation_level ";
1846       cmd += level[ hyp->myOptimizationLevel ];
1847     }
1848   }
1849
1850   // to create internal nodes
1851   if ( no_int_points && !toCreateNewNodes ) {
1852     if ( forExecutable )
1853       cmd += " --no_internal_points";
1854     else
1855       cmd += " --internalpoints no";
1856   }
1857
1858   if ( hyp ) 
1859   {
1860     // verbose mode
1861     if ( verbose ) {
1862       cmd += " --verbose " + SMESH_Comment( hyp->myVerboseLevel );
1863     }
1864
1865     // boundary recovery version
1866     // if ( useBndRecovery ) {
1867     //   cmd += " -C";
1868     // }
1869
1870     // to use FEM correction
1871     // if ( fem && hyp && hyp->myToUseFemCorrection) {
1872     //   cmd += " -FEM";
1873     // }
1874
1875     // to remove initial central point.
1876     if ( rem && hyp->myToRemoveCentralPoint ) {
1877       if ( forExecutable )
1878         cmd += " --no_initial_central_point";
1879       else
1880         cmd += " --centralpoint no";
1881     }
1882
1883     // options as text
1884     // if ( !hyp->myTextOption.empty() ) {
1885     //   cmd += " " + hyp->myTextOption;
1886     // }
1887
1888
1889     if ( hyp->GetMinSize() > 0 )
1890       cmd += " --min_size " + SMESH_Comment( hyp->GetMinSize() );
1891
1892     if ( hyp->GetMaxSize() > 0 )
1893       cmd += " --max_size " + SMESH_Comment( hyp->GetMaxSize() );
1894
1895     // to define volumic gradation.
1896     if ( gra )
1897       cmd += " --gradation " + SMESH_Comment( hyp->myGradation );
1898
1899     if ( hyp->GetUseNumOfThreads() )
1900     {
1901       cmd += " --max_number_of_threads "  + SMESH_Comment( hyp->GetNumOfThreads() );
1902       const char* pthreadMode[] = { "none" , "aggressive" , "safe" };
1903       if ( hyp->myPthreadModeMG >= 0 && hyp->myPthreadModeMG < 3 ) {
1904         cmd += " --pthreads_mode ";
1905         cmd += pthreadMode[ hyp->myPthreadModeMG ];
1906       }
1907     }
1908
1909     // proximity
1910     if ( hyp->GetUseVolumeProximity() )
1911     {
1912       cmd += " --volume_proximity_layers " + SMESH_Comment( hyp->GetNbVolumeProximityLayers() );
1913     }
1914     
1915     hyp->SetAdvancedOptionsInCommandLine( cmd, true );
1916   }
1917
1918 #ifdef WIN32
1919   cmd += " < NUL";
1920 #endif
1921
1922   return cmd;
1923 }
1924
1925 //================================================================================
1926 /*!
1927  * \brief Return a unique file name for MGTetra
1928  */
1929 //================================================================================
1930
1931 std::string GHS3DPlugin_Hypothesis::GetFileName(const GHS3DPlugin_Hypothesis* hyp)
1932 {
1933   std::string aTmpDir = hyp ? hyp->GetWorkingDirectory() : DefaultWorkingDirectory();
1934   if ( !SMESH_File( aTmpDir ).exists() )
1935     aTmpDir = Kernel_Utils::GetTmpDirByPath( aTmpDir );
1936
1937   const char lastChar = *aTmpDir.rbegin();
1938 #ifdef WIN32
1939     if(lastChar != '\\') aTmpDir+='\\';
1940 #else
1941     if(lastChar != '/') aTmpDir+='/';
1942 #endif      
1943
1944   TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
1945   aGenericName += "GHS3D_";
1946   aGenericName += getpid();
1947   aGenericName += "_";
1948   aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
1949
1950   return aGenericName.ToCString();
1951 }
1952
1953 //================================================================================
1954 /*!
1955  * \brief Return a unique file name when running MGTetra HPC
1956  */
1957 //================================================================================
1958
1959 std::string GHS3DPlugin_Hypothesis::GetFileNameHPC(const GHS3DPlugin_Hypothesis* hyp)
1960 {
1961   std::string aTmpDir = hyp ? hyp->GetWorkingDirectory() : DefaultWorkingDirectory();
1962   if ( !SMESH_File( aTmpDir ).exists() )
1963     aTmpDir = Kernel_Utils::GetTmpDirByPath( aTmpDir );
1964
1965   const char lastChar = *aTmpDir.rbegin();
1966 #ifdef WIN32
1967     if(lastChar != '\\') aTmpDir+='\\';
1968 #else
1969     if(lastChar != '/') aTmpDir+='/';
1970 #endif      
1971
1972   TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
1973   aGenericName += "MGTETRAHPC_";
1974   aGenericName += getpid();
1975   aGenericName += "_";
1976   aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
1977
1978   return aGenericName.ToCString();
1979 }
1980
1981 //================================================================================
1982 /*
1983  * Return the name of executable
1984  */
1985 //================================================================================
1986
1987 std::string GHS3DPlugin_Hypothesis::GetExeName()
1988 {
1989   return "mg-tetra.exe";
1990 }
1991
1992 //================================================================================
1993 /*!
1994 * \brief Return the enforced vertices
1995 */
1996 //================================================================================
1997
1998 GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexList GHS3DPlugin_Hypothesis::GetEnforcedVertices(const GHS3DPlugin_Hypothesis* hyp)
1999 {
2000   return hyp ? hyp->_GetEnforcedVertices(): TGHS3DEnforcedVertexList();
2001 }
2002
2003 GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues GHS3DPlugin_Hypothesis::GetEnforcedVerticesCoordsSize (const GHS3DPlugin_Hypothesis* hyp)
2004 {  
2005   return hyp ? hyp->_GetEnforcedVerticesCoordsSize(): TGHS3DEnforcedVertexCoordsValues();
2006 }
2007
2008 GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexEntryValues GHS3DPlugin_Hypothesis::GetEnforcedVerticesEntrySize (const GHS3DPlugin_Hypothesis* hyp)
2009 {  
2010   return hyp ? hyp->_GetEnforcedVerticesEntrySize(): TGHS3DEnforcedVertexEntryValues();
2011 }
2012
2013 GHS3DPlugin_Hypothesis::TCoordsGHS3DEnforcedVertexMap GHS3DPlugin_Hypothesis::GetEnforcedVerticesByCoords (const GHS3DPlugin_Hypothesis* hyp)
2014 {  
2015   return hyp ? hyp->_GetEnforcedVerticesByCoords(): TCoordsGHS3DEnforcedVertexMap();
2016 }
2017
2018 GHS3DPlugin_Hypothesis::TGeomEntryGHS3DEnforcedVertexMap GHS3DPlugin_Hypothesis::GetEnforcedVerticesByEntry (const GHS3DPlugin_Hypothesis* hyp)
2019 {  
2020   return hyp ? hyp->_GetEnforcedVerticesByEntry(): TGeomEntryGHS3DEnforcedVertexMap();
2021 }
2022
2023 GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap GHS3DPlugin_Hypothesis::GetEnforcedNodes(const GHS3DPlugin_Hypothesis* hyp)
2024 {
2025   return hyp ? hyp->_GetEnforcedNodes():TIDSortedNodeGroupMap();
2026 }
2027
2028 GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap GHS3DPlugin_Hypothesis::GetEnforcedEdges(const GHS3DPlugin_Hypothesis* hyp)
2029 {
2030   return hyp ? hyp->_GetEnforcedEdges():TIDSortedElemGroupMap();
2031 }
2032
2033 GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap GHS3DPlugin_Hypothesis::GetEnforcedTriangles(const GHS3DPlugin_Hypothesis* hyp)
2034 {
2035   return hyp ? hyp->_GetEnforcedTriangles():TIDSortedElemGroupMap();
2036 }
2037
2038 GHS3DPlugin_Hypothesis::TID2SizeMap GHS3DPlugin_Hypothesis::GetNodeIDToSizeMap(const GHS3DPlugin_Hypothesis* hyp)
2039 {
2040   return hyp ? hyp->_GetNodeIDToSizeMap(): TID2SizeMap();
2041 }
2042
2043 GHS3DPlugin_Hypothesis::TSetStrings GHS3DPlugin_Hypothesis::GetGroupsToRemove(const GHS3DPlugin_Hypothesis* hyp)
2044 {
2045   return hyp ? hyp->_GetGroupsToRemove(): TSetStrings();
2046 }
2047
2048
2049 //=============================================================================
2050 void GHS3DPlugin_Hypothesis::SetOptionValue(const std::string& optionName,
2051                                             const std::string& optionValue)
2052 {
2053   TOptionValues::iterator op_val = _option2value.find(optionName);
2054   if (op_val == _option2value.end())
2055   {
2056     op_val = _customOption2value.find( optionName );
2057     if ( op_val != _customOption2value.end() && op_val->second != optionValue )
2058       NotifySubMeshesHypothesisModification();
2059     _customOption2value[ optionName ] = optionValue;
2060     return;
2061   }
2062
2063   if (op_val->second != optionValue)
2064   {
2065     const char* ptr = optionValue.c_str();
2066     // strip white spaces
2067     while (ptr[0] == ' ')
2068       ptr++;
2069     size_t i = strlen(ptr);
2070     while (i != 0 && ptr[i - 1] == ' ')
2071       i--;
2072     // check value type
2073     bool typeOk = true;
2074     std::string typeName;
2075     if (i == 0) {
2076       // empty string
2077     } else if (_charOptions.count(optionName)) {
2078       // do not check strings
2079     } else if (_doubleOptions.count(optionName)) {
2080       // check if value is double
2081       ToDbl(ptr, &typeOk);
2082       typeName = "real";
2083     } else if (_boolOptions.count(optionName)) {
2084       // check if value is bool
2085       ToBool(ptr, &typeOk);
2086       typeName = "bool";
2087     } else {
2088       // check if value is int
2089       ToInt(ptr, &typeOk);
2090       typeName = "integer";
2091     }
2092     if ( typeOk ) // check some specific values ?
2093     {
2094     }
2095     if ( !typeOk )
2096     {
2097       std::string msg = "Advanced option '" + optionName + "' = '" + optionValue + "' but must be " + typeName;
2098       throw std::invalid_argument(msg);
2099     }
2100     std::string value( ptr, i );
2101     if ( _defaultOptionValues[ optionName ] == value )
2102       value.clear();
2103
2104     op_val->second = value;
2105
2106     NotifySubMeshesHypothesisModification();
2107   }
2108 }
2109
2110 //=============================================================================
2111 //! Return option value. If isDefault provided, it can be a default value,
2112 //  then *isDefault == true. If isDefault is not provided, the value will be
2113 //  empty if it equals a default one.
2114 std::string GHS3DPlugin_Hypothesis::GetOptionValue(const std::string& optionName,
2115                                                    bool*              isDefault) const
2116 {
2117   TOptionValues::const_iterator op_val = _option2value.find(optionName);
2118   if (op_val == _option2value.end())
2119   {
2120     op_val = _customOption2value.find(optionName);
2121     if (op_val == _customOption2value.end())
2122     {
2123       std::string msg = "Unknown MG-Tetra option: <" + optionName + ">";
2124       throw std::invalid_argument(msg);
2125     }
2126   }
2127   std::string val = op_val->second;
2128   if ( isDefault ) *isDefault = ( val.empty() );
2129
2130   if ( val.empty() && isDefault )
2131   {
2132     op_val = _defaultOptionValues.find( optionName );
2133     if (op_val != _defaultOptionValues.end())
2134       val = op_val->second;
2135   }
2136   return val;
2137 }
2138
2139
2140 //=============================================================================
2141 bool GHS3DPlugin_Hypothesis::HasOptionDefined( const std::string& optionName ) const
2142 {
2143   bool isDefault = false;
2144   try
2145   {
2146     GetOptionValue( optionName, &isDefault );
2147   }
2148   catch ( std::invalid_argument& )
2149   {
2150     return false;
2151   }
2152   return !isDefault;
2153 }
2154
2155 //=============================================================================
2156 void GHS3DPlugin_Hypothesis::ClearOption(const std::string& optionName)
2157 {
2158   TOptionValues::iterator op_val = _customOption2value.find(optionName);
2159   if (op_val != _customOption2value.end())
2160    _customOption2value.erase(op_val);
2161   else {
2162     op_val = _option2value.find(optionName);
2163     if (op_val != _option2value.end())
2164       op_val->second.clear();
2165   }
2166 }
2167
2168 //=============================================================================
2169 GHS3DPlugin_Hypothesis::TOptionValues GHS3DPlugin_Hypothesis::GetOptionValues() const
2170 {
2171   TOptionValues vals;
2172   TOptionValues::const_iterator op_val = _option2value.begin();
2173   for ( ; op_val != _option2value.end(); ++op_val )
2174     vals.insert( make_pair( op_val->first, GetOptionValue( op_val->first, GET_DEFAULT() )));
2175
2176   return vals;
2177 }
2178
2179 //================================================================================
2180 /*!
2181  * \brief Converts a string to a bool
2182  */
2183 //================================================================================
2184
2185 bool GHS3DPlugin_Hypothesis::ToBool(const std::string& str, bool* isOk )
2186 {
2187   std::string s = str;
2188   if ( isOk ) *isOk = true;
2189
2190   for ( size_t i = 0; i <= s.size(); ++i )
2191     s[i] = (char) tolower( s[i] );
2192
2193   if ( s == "1" || s == "true" || s == "active" || s == "yes" )
2194     return true;
2195
2196   if ( s == "0" || s == "false" || s == "inactive" || s == "no" )
2197     return false;
2198
2199   if ( isOk )
2200     *isOk = false;
2201   else {
2202     std::string msg = "Not a Boolean value:'" + str + "'";
2203     throw std::invalid_argument(msg);
2204   }
2205   return false;
2206 }
2207
2208 //================================================================================
2209 /*!
2210  * \brief Converts a string to a real value
2211  */
2212 //================================================================================
2213
2214 double GHS3DPlugin_Hypothesis::ToDbl(const std::string& str, bool* isOk )
2215 {
2216   if ( str.empty() ) throw std::invalid_argument("Empty value provided");
2217
2218   char * endPtr;
2219   double val = strtod(&str[0], &endPtr);
2220   bool ok = (&str[0] != endPtr);
2221
2222   if ( isOk ) *isOk = ok;
2223
2224   if ( !ok )
2225   {
2226     std::string msg = "Not a real value:'" + str + "'";
2227     throw std::invalid_argument(msg);
2228   }
2229   return val;
2230 }
2231
2232 //================================================================================
2233 /*!
2234  * \brief Converts a string to a integer value
2235  */
2236 //================================================================================
2237
2238 int GHS3DPlugin_Hypothesis::ToInt(const std::string& str, bool* isOk )
2239 {
2240   if ( str.empty() ) throw std::invalid_argument("Empty value provided");
2241
2242   char * endPtr;
2243   int val = (int)strtol( &str[0], &endPtr, 10);
2244   bool ok = (&str[0] != endPtr);
2245
2246   if ( isOk ) *isOk = ok;
2247
2248   if ( !ok )
2249   {
2250     std::string msg = "Not an integer value:'" + str + "'";
2251     throw std::invalid_argument(msg);
2252   }
2253   return val;
2254 }
2255