Salome HOME
Adding code for Python parallel mesh with test + removing nbMesherThreads
[modules/smesh.git] / src / SMESH / SMESH_Gen.cxx
1 // Copyright (C) 2007-2022  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SMESH SMESH : implementation of SMESH idl descriptions
24 //  File   : SMESH_Gen.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27 //
28
29 //#define CHRONODEF
30
31 #include "SMESH_Gen.hxx"
32
33 #include "SMESH_DriverMesh.hxx"
34 #include "SMDS_Mesh.hxx"
35 #include "SMDS_MeshElement.hxx"
36 #include "SMDS_MeshNode.hxx"
37 #include "SMESHDS_Document.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MesherHelper.hxx"
41 #include "SMESH_subMesh.hxx"
42
43 #include <utilities.h>
44 #include <Utils_ExceptHandlers.hxx>
45
46 #include <TopExp_Explorer.hxx>
47 #include <TopoDS.hxx>
48 #include <TopoDS_Iterator.hxx>
49
50 #include "memoire.h"
51 #include <functional>
52
53 #ifdef WIN32
54   #include <windows.h>
55 #endif
56
57 #include <Basics_Utils.hxx>
58
59 using namespace std;
60 #include <boost/filesystem.hpp>
61 #include <boost/asio.hpp>
62 namespace fs = boost::filesystem;
63
64 // Environment variable separator
65 #ifdef WIN32
66   #define env_sep ';'
67 #else
68   #define env_sep ':'
69 #endif
70
71 namespace
72 {
73   // a structure used to nullify SMESH_Gen field of SMESH_Hypothesis,
74   // which is needed for SMESH_Hypothesis not deleted before ~SMESH_Gen()
75   struct _Hyp : public SMESH_Hypothesis
76   {
77     void NullifyGen()
78     {
79       _gen = 0;
80     }
81   };
82
83   //================================================================================
84   /*!
85    * \brief Fill a map of shapes with all sub-shape of a sub-mesh
86    */
87   //================================================================================
88
89   TopTools_IndexedMapOfShape * fillAllowed( SMESH_subMesh*               sm,
90                                             const bool                   toFill,
91                                             TopTools_IndexedMapOfShape * allowedSub )
92   {
93     if ( !toFill || !allowedSub )
94     {
95       return nullptr;
96     }
97     if ( allowedSub->IsEmpty() )
98     {
99       allowedSub->ReSize( sm->DependsOn().size() + 1 );
100       allowedSub->Add( sm->GetSubShape() );
101       for ( const auto & key_sm : sm->DependsOn() )
102         allowedSub->Add( key_sm.second->GetSubShape() );
103     }
104     return allowedSub;
105   }
106 }
107
108 //=============================================================================
109 /*!
110  *  Constructor
111  */
112 //=============================================================================
113
114 SMESH_Gen::SMESH_Gen()
115 {
116   _studyContext = new StudyContextStruct;
117   _studyContext->myDocument = new SMESHDS_Document();
118   _localId = 0;
119   _hypId   = 0;
120   _segmentation = _nbSegments = 10;
121   _compute_canceled = false;
122 }
123
124 //=============================================================================
125 /*!
126  * Destructor
127  */
128 //=============================================================================
129
130 SMESH_Gen::~SMESH_Gen()
131 {
132   std::map < int, SMESH_Hypothesis * >::iterator i_hyp = _studyContext->mapHypothesis.begin();
133   for ( ; i_hyp != _studyContext->mapHypothesis.end(); ++i_hyp )
134   {
135     if ( _Hyp* h = static_cast< _Hyp*>( i_hyp->second ))
136       h->NullifyGen();
137   }
138   delete _studyContext->myDocument;
139   delete _studyContext;
140 }
141
142 //=============================================================================
143 /*!
144  * Creates a mesh in a study.
145  * if (theIsEmbeddedMode) { mesh modification commands are not logged }
146  */
147 //=============================================================================
148
149 SMESH_Mesh* SMESH_Gen::CreateMesh(bool theIsEmbeddedMode)
150 {
151   Unexpect aCatch(SalomeException);
152
153   // create a new SMESH_mesh object
154   SMESH_Mesh *aMesh = new SMESH_Mesh(_localId++,
155                                      this,
156                                      theIsEmbeddedMode,
157                                      _studyContext->myDocument);
158   _studyContext->mapMesh[_localId-1] = aMesh;
159
160   return aMesh;
161 }
162
163
164
165 bool SMESH_Gen::sequentialComputeSubMeshes(
166           SMESH_Mesh & aMesh,
167           const TopoDS_Shape & aShape,
168           const ::MeshDimension       aDim,
169           TSetOfInt*                  aShapesId /*=0*/,
170           TopTools_IndexedMapOfShape* allowedSubShapes,
171           SMESH_subMesh::compute_event &computeEvent,
172           const bool includeSelf,
173           const bool complexShapeFirst,
174           const bool   aShapeOnly)
175 {
176   MESSAGE("Compute submeshes sequentialy");
177
178   bool ret = true;
179
180   SMESH_subMeshIteratorPtr smIt;
181   SMESH_subMesh *shapeSM = aMesh.GetSubMesh(aShape);
182
183   smIt = shapeSM->getDependsOnIterator(includeSelf, !complexShapeFirst);
184   while ( smIt->more() )
185   {
186     SMESH_subMesh* smToCompute = smIt->next();
187
188     // do not mesh vertices of a pseudo shape
189     const TopoDS_Shape&        shape = smToCompute->GetSubShape();
190     const TopAbs_ShapeEnum shapeType = shape.ShapeType();
191     if ( !aMesh.HasShapeToMesh() && shapeType == TopAbs_VERTEX )
192       continue;
193
194     // check for preview dimension limitations
195     if ( aShapesId && GetShapeDim( shapeType ) > (int)aDim )
196     {
197       // clear compute state not to show previous compute errors
198       //  if preview invoked less dimension less than previous
199       smToCompute->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
200       continue;
201     }
202
203     if (smToCompute->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE)
204     {
205       if (_compute_canceled)
206         return false;
207       smToCompute->SetAllowedSubShapes( fillAllowed( shapeSM, aShapeOnly, allowedSubShapes ));
208       setCurrentSubMesh( smToCompute );
209       smToCompute->ComputeStateEngine( computeEvent );
210       setCurrentSubMesh( nullptr );
211       smToCompute->SetAllowedSubShapes( nullptr );
212     }
213
214     // we check all the sub-meshes here and detect if any of them failed to compute
215     if (smToCompute->GetComputeState() == SMESH_subMesh::FAILED_TO_COMPUTE &&
216         ( shapeType != TopAbs_EDGE || !SMESH_Algo::isDegenerated( TopoDS::Edge( shape ))))
217       ret = false;
218     else if ( aShapesId )
219       aShapesId->insert( smToCompute->GetId() );
220   }
221   //aMesh.GetMeshDS()->Modified();
222   return ret;
223
224 };
225
226 //=============================================================================
227 /*
228  * Parallel compute of a submesh
229  * This function is used to pass to thread_pool
230  */
231 //=============================================================================
232 const std::function<void(SMESH_subMesh*,
233                          SMESH_subMesh::compute_event,
234                          SMESH_subMesh*,
235                          bool,
236                          TopTools_IndexedMapOfShape *,
237                          TSetOfInt*)>
238      compute_function([&] (SMESH_subMesh* sm,
239                           SMESH_subMesh::compute_event event,
240                           SMESH_subMesh *shapeSM,
241                           bool aShapeOnly,
242                           TopTools_IndexedMapOfShape *allowedSubShapes,
243                           TSetOfInt*                  aShapesId) -> void
244 {
245   if (sm->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE)
246   {
247     sm->SetAllowedSubShapes( fillAllowed( shapeSM, aShapeOnly, allowedSubShapes ));
248     //setCurrentSubMesh( sm );
249     sm->ComputeStateEngine(event);
250     //setCurrentSubMesh( nullptr );
251     sm->SetAllowedSubShapes( nullptr );
252   }
253
254   if ( aShapesId )
255     aShapesId->insert( sm->GetId() );
256
257 });
258
259 bool SMESH_Gen::parallelComputeSubMeshes(
260           SMESH_Mesh & aMesh,
261           const TopoDS_Shape & aShape,
262           const ::MeshDimension       aDim,
263           TSetOfInt*                  aShapesId /*=0*/,
264           TopTools_IndexedMapOfShape* allowedSubShapes,
265           SMESH_subMesh::compute_event &computeEvent,
266           const bool includeSelf,
267           const bool complexShapeFirst,
268           const bool   aShapeOnly)
269 {
270
271   bool ret = true;
272
273   SMESH_subMeshIteratorPtr smIt;
274   SMESH_subMesh *shapeSM = aMesh.GetSubMesh(aShape);
275
276   // Pool of thread for computation
277   // TODO: move when parallelMesh created
278   aMesh.InitPoolThreads();
279
280   TopAbs_ShapeEnum previousShapeType = TopAbs_VERTEX;
281   int nbThreads = aMesh.GetNbThreads();
282   MESSAGE("Compute submeshes with threads: " << nbThreads);
283
284
285   smIt = shapeSM->getDependsOnIterator(includeSelf, !complexShapeFirst);
286   while ( smIt->more() )
287   {
288     SMESH_subMesh* smToCompute = smIt->next();
289
290     // do not mesh vertices of a pseudo shape
291     const TopoDS_Shape&        shape = smToCompute->GetSubShape();
292     const TopAbs_ShapeEnum shapeType = shape.ShapeType();
293     // Not doing in parallel 1D and 2D meshes
294     if ( !aMesh.HasShapeToMesh() && shapeType == TopAbs_VERTEX )
295       continue;
296     if(shapeType==TopAbs_FACE||shapeType==TopAbs_EDGE)
297       aMesh.SetNbThreads(0);
298     else
299       aMesh.SetNbThreads(nbThreads);
300
301
302     if (shapeType != previousShapeType) {
303       // Waiting for all threads for the previous type to end
304       aMesh.wait();
305
306       std::string file_name;
307       switch(previousShapeType){
308         case TopAbs_FACE:
309           file_name = "Mesh2D.med";
310           break;
311         case TopAbs_EDGE:
312           file_name = "Mesh1D.med";
313           break;
314         case TopAbs_VERTEX:
315           file_name = "Mesh0D.med";
316           break;
317         case TopAbs_SOLID:
318         default:
319           file_name = "";
320           break;
321       }
322       if(file_name != "")
323       {
324         fs::path mesh_file = fs::path(aMesh.tmp_folder) / fs::path(file_name);
325         exportMesh(mesh_file.string(), aMesh, "MESH");
326
327       }
328       //Resetting threaded pool info
329       previousShapeType = shapeType;
330     }
331
332     // check for preview dimension limitations
333     if ( aShapesId && GetShapeDim( shapeType ) > (int)aDim )
334     {
335       // clear compute state not to show previous compute errors
336       //  if preview invoked less dimension less than previous
337       smToCompute->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
338       continue;
339     }
340     boost::asio::post(*(aMesh._pool), std::bind(compute_function, smToCompute, computeEvent,
341                       shapeSM, aShapeOnly, allowedSubShapes,
342                       aShapesId));
343   }
344
345   // Waiting for the thread for Solids to finish
346   aMesh.wait();
347
348   aMesh.GetMeshDS()->Modified();
349
350   return ret;
351 };
352
353
354 //=============================================================================
355 /*
356  * Compute a mesh
357  */
358 //=============================================================================
359
360 bool SMESH_Gen::Compute(SMESH_Mesh &                aMesh,
361                         const TopoDS_Shape &        aShape,
362                         const int                   aFlags /*= COMPACT_MESH*/,
363                         const ::MeshDimension       aDim /*=::MeshDim_3D*/,
364                         TSetOfInt*                  aShapesId /*=0*/,
365                         TopTools_IndexedMapOfShape* anAllowedSubShapes/*=0*/)
366 {
367   MEMOSTAT;
368
369   const bool   aShapeOnly = aFlags & SHAPE_ONLY;
370   const bool     anUpward = aFlags & UPWARD;
371   const bool aCompactMesh = aFlags & COMPACT_MESH;
372
373   bool ret = true;
374
375   SMESH_subMesh *sm, *shapeSM = aMesh.GetSubMesh(aShape);
376
377   const bool includeSelf = true;
378   const bool complexShapeFirst = true;
379   const int  globalAlgoDim = 100;
380
381   SMESH_subMeshIteratorPtr smIt;
382
383   // Fix of Issue 22150. Due to !BLSURF->OnlyUnaryInput(), BLSURF computes edges
384   // that must be computed by Projection 1D-2D while the Projection asks to compute
385   // one face only.
386   SMESH_subMesh::compute_event computeEvent =
387     aShapeOnly ? SMESH_subMesh::COMPUTE_SUBMESH : SMESH_subMesh::COMPUTE;
388   if ( !aMesh.HasShapeToMesh() )
389     computeEvent = SMESH_subMesh::COMPUTE_NOGEOM; // if several algos and no geometry
390
391   TopTools_IndexedMapOfShape *allowedSubShapes = anAllowedSubShapes, allowedSub;
392   if ( aShapeOnly && !allowedSubShapes )
393     allowedSubShapes = &allowedSub;
394
395   if ( anUpward ) // is called from the below code in this method
396   {
397     // ===============================================
398     // Mesh all the sub-shapes starting from vertices
399     // ===============================================
400     if (aMesh.IsParallel())
401       ret = parallelComputeSubMeshes(
402               aMesh, aShape, aDim,
403               aShapesId, allowedSubShapes,
404               computeEvent,
405               includeSelf,
406               complexShapeFirst,
407               aShapeOnly);
408     else
409       ret = sequentialComputeSubMeshes(
410               aMesh, aShape, aDim,
411               aShapesId, allowedSubShapes,
412               computeEvent,
413               includeSelf,
414               complexShapeFirst,
415               aShapeOnly);
416
417     return ret;
418   }
419   else
420   {
421     // ================================================================
422     // Apply algos that do NOT require discretized boundaries
423     // ("all-dimensional") and do NOT support sub-meshes, starting from
424     // the most complex shapes and collect sub-meshes with algos that
425     // DO support sub-meshes
426     // ================================================================
427     list< SMESH_subMesh* > smWithAlgoSupportingSubmeshes[4]; // for each dim
428
429     // map to sort sm with same dim algos according to dim of
430     // the shape the algo assigned to (issue 0021217).
431     // Other issues influenced the algo applying order:
432     // 21406, 21556, 21893, 20206
433     multimap< int, SMESH_subMesh* > shDim2sm;
434     multimap< int, SMESH_subMesh* >::reverse_iterator shDim2smIt;
435     TopoDS_Shape algoShape;
436     int prevShapeDim = -1, aShapeDim;
437
438     smIt = shapeSM->getDependsOnIterator(includeSelf, complexShapeFirst);
439     while ( smIt->more() )
440     {
441       SMESH_subMesh* smToCompute = smIt->next();
442       if ( smToCompute->GetComputeState() != SMESH_subMesh::READY_TO_COMPUTE )
443         continue;
444
445       const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
446       aShapeDim = GetShapeDim( aSubShape );
447       if ( aShapeDim < 1 ) break;
448
449       // check for preview dimension limitations
450       if ( aShapesId && aShapeDim > (int)aDim )
451         continue;
452
453       SMESH_Algo* algo = GetAlgo( smToCompute, &algoShape );
454       if ( algo && !algo->NeedDiscreteBoundary() )
455       {
456         if ( algo->SupportSubmeshes() )
457         {
458           // reload sub-meshes from shDim2sm into smWithAlgoSupportingSubmeshes
459           // so that more local algos to go first
460           if ( prevShapeDim != aShapeDim )
461           {
462             prevShapeDim = aShapeDim;
463             for ( shDim2smIt = shDim2sm.rbegin(); shDim2smIt != shDim2sm.rend(); ++shDim2smIt )
464               if ( shDim2smIt->first == globalAlgoDim )
465                 smWithAlgoSupportingSubmeshes[ aShapeDim ].push_back( shDim2smIt->second );
466               else
467                 smWithAlgoSupportingSubmeshes[ aShapeDim ].push_front( shDim2smIt->second );
468             shDim2sm.clear();
469           }
470           // add smToCompute to shDim2sm map
471           if ( algoShape.IsSame( aMesh.GetShapeToMesh() ))
472           {
473             aShapeDim = globalAlgoDim; // to compute last
474           }
475           else
476           {
477             aShapeDim = GetShapeDim( algoShape );
478             if ( algoShape.ShapeType() == TopAbs_COMPOUND )
479             {
480               TopoDS_Iterator it( algoShape );
481               aShapeDim += GetShapeDim( it.Value() );
482             }
483           }
484           shDim2sm.insert( make_pair( aShapeDim, smToCompute ));
485         }
486         else // Compute w/o support of sub-meshes
487         {
488           if (_compute_canceled)
489             return false;
490           smToCompute->SetAllowedSubShapes( fillAllowed( shapeSM, aShapeOnly, allowedSubShapes ));
491           setCurrentSubMesh( smToCompute );
492           smToCompute->ComputeStateEngine( computeEvent );
493           setCurrentSubMesh( nullptr );
494           smToCompute->SetAllowedSubShapes( nullptr );
495           if ( aShapesId )
496             aShapesId->insert( smToCompute->GetId() );
497         }
498       }
499     }
500     // reload sub-meshes from shDim2sm into smWithAlgoSupportingSubmeshes
501     for ( shDim2smIt = shDim2sm.rbegin(); shDim2smIt != shDim2sm.rend(); ++shDim2smIt )
502       if ( shDim2smIt->first == globalAlgoDim )
503         smWithAlgoSupportingSubmeshes[3].push_back( shDim2smIt->second );
504       else
505         smWithAlgoSupportingSubmeshes[0].push_front( shDim2smIt->second );
506
507     // ======================================================
508     // Apply all-dimensional algorithms supporing sub-meshes
509     // ======================================================
510
511     std::vector< SMESH_subMesh* > smVec;
512     for ( aShapeDim = 0; aShapeDim < 4; ++aShapeDim )
513       smVec.insert( smVec.end(),
514                     smWithAlgoSupportingSubmeshes[aShapeDim].begin(),
515                     smWithAlgoSupportingSubmeshes[aShapeDim].end() );
516
517     // gather sub-shapes with local uni-dimensional algos (bos #29143)
518     // ----------------------------------------------------------------
519     TopTools_MapOfShape uniDimAlgoShapes;
520     if ( !smVec.empty() )
521     {
522       ShapeToHypothesis::Iterator s2hyps( aMesh.GetMeshDS()->GetHypotheses() );
523       for ( ; s2hyps.More(); s2hyps.Next() )
524       {
525         const TopoDS_Shape& s = s2hyps.Key();
526         if ( s.IsSame( aMesh.GetShapeToMesh() ))
527           continue;
528         for ( auto & hyp : s2hyps.Value() )
529         {
530           if ( const SMESH_Algo* algo = dynamic_cast< const SMESH_Algo*>( hyp ))
531             if ( algo->NeedDiscreteBoundary() )
532             {
533               TopAbs_ShapeEnum sType;
534               switch ( algo->GetDim() ) {
535               case 3:  sType = TopAbs_SOLID; break;
536               case 2:  sType = TopAbs_FACE; break;
537               default: sType = TopAbs_EDGE; break;
538               }
539               for ( TopExp_Explorer ex( s2hyps.Key(), sType ); ex.More(); ex.Next() )
540                 uniDimAlgoShapes.Add( ex.Current() );
541             }
542         }
543       }
544     }
545
546     {
547       // ------------------------------------------------
548       // sort list of sub-meshes according to mesh order
549       // ------------------------------------------------
550       aMesh.SortByMeshOrder( smVec );
551
552       // ------------------------------------------------------------
553       // compute sub-meshes with local uni-dimensional algos under
554       // sub-meshes with all-dimensional algos
555       // ------------------------------------------------------------
556       // start from lower shapes
557       for ( size_t i = 0; i < smVec.size(); ++i )
558       {
559         sm = smVec[i];
560         if ( sm->GetComputeState() != SMESH_subMesh::READY_TO_COMPUTE)
561           continue;
562
563         const TopAbs_ShapeEnum shapeType = sm->GetSubShape().ShapeType();
564
565         if ( !uniDimAlgoShapes.IsEmpty() )
566         {
567           // get a shape the algo is assigned to
568           if ( !GetAlgo( sm, & algoShape ))
569             continue; // strange...
570
571           // look for more local algos
572           if ( SMESH_subMesh* algoSM = aMesh.GetSubMesh( algoShape ))
573             smIt = algoSM->getDependsOnIterator(!includeSelf, !complexShapeFirst);
574           else
575             smIt = sm->getDependsOnIterator(!includeSelf, !complexShapeFirst);
576
577           while ( smIt->more() )
578           {
579             SMESH_subMesh* smToCompute = smIt->next();
580
581             const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
582             const           int aShapeDim = GetShapeDim( aSubShape );
583             if ( aShapeDim < 1 || aSubShape.ShapeType() <= shapeType )
584               continue;
585             if ( !uniDimAlgoShapes.Contains( aSubShape ))
586               continue; // [bos #29143] aMesh.GetHypothesis() is too long
587
588             // check for preview dimension limitations
589             if ( aShapesId && GetShapeDim( aSubShape.ShapeType() ) > (int)aDim )
590               continue;
591
592             SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
593             filter
594               .And( SMESH_HypoFilter::IsApplicableTo( aSubShape ))
595               .And( SMESH_HypoFilter::IsMoreLocalThan( algoShape, aMesh ));
596
597             if ( SMESH_Algo* subAlgo = (SMESH_Algo*) aMesh.GetHypothesis( smToCompute, filter, true))
598             {
599               if ( ! subAlgo->NeedDiscreteBoundary() ) continue;
600               TopTools_IndexedMapOfShape* localAllowed = allowedSubShapes;
601               if ( localAllowed && localAllowed->IsEmpty() )
602                 localAllowed = 0; // prevent fillAllowed() with  aSubShape
603
604               SMESH_Hypothesis::Hypothesis_Status status;
605               if ( subAlgo->CheckHypothesis( aMesh, aSubShape, status ))
606                 // mesh a lower smToCompute starting from vertices
607                 Compute( aMesh, aSubShape, aFlags | SHAPE_ONLY_UPWARD, aDim, aShapesId, localAllowed );
608             }
609           }
610         }
611         // --------------------------------
612         // apply the all-dimensional algo
613         // --------------------------------
614         {
615           if (_compute_canceled)
616             return false;
617           // check for preview dimension limitations
618           if ( aShapesId && GetShapeDim( shapeType ) > (int)aDim )
619             continue;
620           sm->SetAllowedSubShapes( fillAllowed( shapeSM, aShapeOnly, allowedSubShapes ));
621           setCurrentSubMesh( sm );
622           sm->ComputeStateEngine( computeEvent );
623
624           setCurrentSubMesh( NULL );
625           sm->SetAllowedSubShapes( nullptr );
626           if ( aShapesId )
627             aShapesId->insert( sm->GetId() );
628         }
629       }
630     }
631
632     // -----------------------------------------------
633     // mesh the rest sub-shapes starting from vertices
634     // -----------------------------------------------
635     ret = Compute( aMesh, aShape, aFlags | UPWARD, aDim, aShapesId, allowedSubShapes );
636
637   }
638
639   MEMOSTAT;
640
641   // fix quadratic mesh by bending iternal links near concave boundary
642   if ( aCompactMesh && // a final compute
643        aShape.IsSame( aMesh.GetShapeToMesh() ) &&
644        !aShapesId && // not preview
645        ret ) // everything is OK
646   {
647     SMESH_MesherHelper aHelper( aMesh );
648     if ( aHelper.IsQuadraticMesh() != SMESH_MesherHelper::LINEAR )
649     {
650       aHelper.FixQuadraticElements( shapeSM->GetComputeError() );
651     }
652   }
653
654   if ( aCompactMesh )
655   {
656     aMesh.GetMeshDS()->Modified();
657     aMesh.GetMeshDS()->CompactMesh();
658   }
659   return ret;
660 }
661
662 //=============================================================================
663 /*!
664  * Prepare Compute a mesh
665  */
666 //=============================================================================
667 void SMESH_Gen::PrepareCompute(SMESH_Mesh &          /*aMesh*/,
668                                const TopoDS_Shape &  /*aShape*/)
669 {
670   _compute_canceled = false;
671   resetCurrentSubMesh();
672 }
673
674 //=============================================================================
675 /*!
676  * Cancel Compute a mesh
677  */
678 //=============================================================================
679 void SMESH_Gen::CancelCompute(SMESH_Mesh &          /*aMesh*/,
680                               const TopoDS_Shape &  /*aShape*/)
681 {
682   _compute_canceled = true;
683   if ( const SMESH_subMesh* sm = GetCurrentSubMesh() )
684   {
685     const_cast< SMESH_subMesh* >( sm )->ComputeStateEngine( SMESH_subMesh::COMPUTE_CANCELED );
686   }
687   resetCurrentSubMesh();
688 }
689
690 //================================================================================
691 /*!
692  * \brief Returns a sub-mesh being currently computed
693  */
694 //================================================================================
695
696 const SMESH_subMesh* SMESH_Gen::GetCurrentSubMesh() const
697 {
698   return _sm_current.empty() ? 0 : _sm_current.back();
699 }
700
701 //================================================================================
702 /*!
703  * \brief Sets a sub-mesh being currently computed.
704  *
705  * An algorithm can call Compute() for a sub-shape, hence we keep a stack of sub-meshes
706  */
707 //================================================================================
708
709 void SMESH_Gen::setCurrentSubMesh(SMESH_subMesh* sm)
710 {
711   if ( sm )
712     _sm_current.push_back( sm );
713
714   else if ( !_sm_current.empty() )
715     _sm_current.pop_back();
716 }
717
718 void SMESH_Gen::resetCurrentSubMesh()
719 {
720   _sm_current.clear();
721 }
722
723 //=============================================================================
724 /*!
725  * Evaluate a mesh
726  */
727 //=============================================================================
728
729 bool SMESH_Gen::Evaluate(SMESH_Mesh &          aMesh,
730                          const TopoDS_Shape &  aShape,
731                          MapShapeNbElems&      aResMap,
732                          const bool            anUpward,
733                          TSetOfInt*            aShapesId)
734 {
735   bool ret = true;
736
737   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
738
739   const bool includeSelf = true;
740   const bool complexShapeFirst = true;
741   SMESH_subMeshIteratorPtr smIt;
742
743   if ( anUpward ) { // is called from below code here
744     // -----------------------------------------------
745     // mesh all the sub-shapes starting from vertices
746     // -----------------------------------------------
747     smIt = sm->getDependsOnIterator(includeSelf, !complexShapeFirst);
748     while ( smIt->more() ) {
749       SMESH_subMesh* smToCompute = smIt->next();
750
751       // do not mesh vertices of a pseudo shape
752       const TopAbs_ShapeEnum shapeType = smToCompute->GetSubShape().ShapeType();
753       //if ( !aMesh.HasShapeToMesh() && shapeType == TopAbs_VERTEX )
754       //  continue;
755       if ( !aMesh.HasShapeToMesh() ) {
756         if( shapeType == TopAbs_VERTEX || shapeType == TopAbs_WIRE ||
757             shapeType == TopAbs_SHELL )
758           continue;
759       }
760
761       smToCompute->Evaluate(aResMap);
762       if( aShapesId )
763         aShapesId->insert( smToCompute->GetId() );
764     }
765     return ret;
766   }
767   else {
768     // -----------------------------------------------------------------
769     // apply algos that DO NOT require Discreteized boundaries and DO NOT
770     // support sub-meshes, starting from the most complex shapes
771     // and collect sub-meshes with algos that DO support sub-meshes
772     // -----------------------------------------------------------------
773     list< SMESH_subMesh* > smWithAlgoSupportingSubmeshes;
774     smIt = sm->getDependsOnIterator(includeSelf, complexShapeFirst);
775     while ( smIt->more() ) {
776       SMESH_subMesh* smToCompute = smIt->next();
777       const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
778       const int aShapeDim = GetShapeDim( aSubShape );
779       if ( aShapeDim < 1 ) break;
780
781       SMESH_Algo* algo = GetAlgo( smToCompute );
782       if ( algo && !algo->NeedDiscreteBoundary() ) {
783         if ( algo->SupportSubmeshes() ) {
784           smWithAlgoSupportingSubmeshes.push_front( smToCompute );
785         }
786         else {
787           smToCompute->Evaluate(aResMap);
788           if ( aShapesId )
789             aShapesId->insert( smToCompute->GetId() );
790         }
791       }
792     }
793
794     // ------------------------------------------------------------
795     // sort list of meshes according to mesh order
796     // ------------------------------------------------------------
797     std::vector< SMESH_subMesh* > smVec( smWithAlgoSupportingSubmeshes.begin(),
798                                          smWithAlgoSupportingSubmeshes.end() );
799     aMesh.SortByMeshOrder( smVec );
800
801     // ------------------------------------------------------------
802     // compute sub-meshes under shapes with algos that DO NOT require
803     // Discreteized boundaries and DO support sub-meshes
804     // ------------------------------------------------------------
805     // start from lower shapes
806     for ( size_t i = 0; i < smVec.size(); ++i )
807     {
808       sm = smVec[i];
809
810       // get a shape the algo is assigned to
811       TopoDS_Shape algoShape;
812       if ( !GetAlgo( sm, & algoShape ))
813         continue; // strange...
814
815       // look for more local algos
816       smIt = sm->getDependsOnIterator(!includeSelf, !complexShapeFirst);
817       while ( smIt->more() ) {
818         SMESH_subMesh* smToCompute = smIt->next();
819
820         const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
821         const int aShapeDim = GetShapeDim( aSubShape );
822         if ( aShapeDim < 1 ) continue;
823
824         SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
825         filter
826           .And( SMESH_HypoFilter::IsApplicableTo( aSubShape ))
827           .And( SMESH_HypoFilter::IsMoreLocalThan( algoShape, aMesh ));
828
829         if ( SMESH_Algo* subAlgo = (SMESH_Algo*) aMesh.GetHypothesis( smToCompute, filter, true ))
830         {
831           if ( ! subAlgo->NeedDiscreteBoundary() ) continue;
832           SMESH_Hypothesis::Hypothesis_Status status;
833           if ( subAlgo->CheckHypothesis( aMesh, aSubShape, status ))
834             // mesh a lower smToCompute starting from vertices
835             Evaluate( aMesh, aSubShape, aResMap, /*anUpward=*/true, aShapesId );
836         }
837       }
838     }
839     // ----------------------------------------------------------
840     // apply the algos that do not require Discreteized boundaries
841     // ----------------------------------------------------------
842     for ( size_t i = 0; i < smVec.size(); ++i )
843     {
844       sm = smVec[i];
845       sm->Evaluate(aResMap);
846       if ( aShapesId )
847         aShapesId->insert( sm->GetId() );
848     }
849
850     // -----------------------------------------------
851     // mesh the rest sub-shapes starting from vertices
852     // -----------------------------------------------
853     ret = Evaluate( aMesh, aShape, aResMap, /*anUpward=*/true, aShapesId );
854   }
855
856   return ret;
857 }
858
859
860 //=======================================================================
861 //function : checkConformIgnoredAlgos
862 //purpose  :
863 //=======================================================================
864
865 static bool checkConformIgnoredAlgos(SMESH_Mesh&               aMesh,
866                                      SMESH_subMesh*            aSubMesh,
867                                      const SMESH_Algo*         aGlobIgnoAlgo,
868                                      const SMESH_Algo*         aLocIgnoAlgo,
869                                      bool &                    checkConform,
870                                      set<SMESH_subMesh*>&      aCheckedMap,
871                                      list< SMESH_Gen::TAlgoStateError > & theErrors)
872 {
873   ASSERT( aSubMesh );
874   if ( aSubMesh->GetSubShape().ShapeType() == TopAbs_VERTEX)
875     return true;
876
877
878   bool ret = true;
879
880   const list<const SMESHDS_Hypothesis*>& listHyp =
881     aMesh.GetMeshDS()->GetHypothesis( aSubMesh->GetSubShape() );
882   list<const SMESHDS_Hypothesis*>::const_iterator it=listHyp.begin();
883   for ( ; it != listHyp.end(); it++)
884   {
885     const SMESHDS_Hypothesis * aHyp = *it;
886     if (aHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO)
887       continue;
888
889     const SMESH_Algo* algo = dynamic_cast<const SMESH_Algo*> (aHyp);
890     ASSERT ( algo );
891
892     if ( aLocIgnoAlgo ) // algo is hidden by a local algo of upper dim
893     {
894       theErrors.push_back( SMESH_Gen::TAlgoStateError() );
895       theErrors.back().Set( SMESH_Hypothesis::HYP_HIDDEN_ALGO, algo, false );
896       INFOS( "Local <" << algo->GetName() << "> is hidden by local <"
897             << aLocIgnoAlgo->GetName() << ">");
898     }
899     else
900     {
901       bool       isGlobal = (aMesh.IsMainShape( aSubMesh->GetSubShape() ));
902       int             dim = algo->GetDim();
903       int aMaxGlobIgnoDim = ( aGlobIgnoAlgo ? aGlobIgnoAlgo->GetDim() : -1 );
904       bool    isNeededDim = ( aGlobIgnoAlgo ? aGlobIgnoAlgo->NeedLowerHyps( dim ) : false );
905
906       if (( dim < aMaxGlobIgnoDim && !isNeededDim ) &&
907           ( isGlobal || !aGlobIgnoAlgo->SupportSubmeshes() ))
908       {
909         // algo is hidden by a global algo
910         theErrors.push_back( SMESH_Gen::TAlgoStateError() );
911         theErrors.back().Set( SMESH_Hypothesis::HYP_HIDDEN_ALGO, algo, true );
912         INFOS( ( isGlobal ? "Global" : "Local" )
913               << " <" << algo->GetName() << "> is hidden by global <"
914               << aGlobIgnoAlgo->GetName() << ">");
915       }
916       else if ( !algo->NeedDiscreteBoundary() && !isGlobal)
917       {
918         // local algo is not hidden and hides algos on sub-shapes
919         if (checkConform && !aSubMesh->IsConform( algo ))
920         {
921           ret = false;
922           checkConform = false; // no more check conformity
923           INFOS( "ERROR: Local <" << algo->GetName() <<
924                 "> would produce not conform mesh: "
925                 "<Not Conform Mesh Allowed> hypothesis is missing");
926           theErrors.push_back( SMESH_Gen::TAlgoStateError() );
927           theErrors.back().Set( SMESH_Hypothesis::HYP_NOTCONFORM, algo, false );
928         }
929
930         // sub-algos will be hidden by a local <algo> if <algo> does not support sub-meshes
931         if ( algo->SupportSubmeshes() )
932           algo = 0;
933         SMESH_subMeshIteratorPtr revItSub =
934           aSubMesh->getDependsOnIterator( /*includeSelf=*/false, /*complexShapeFirst=*/true);
935         bool checkConform2 = false;
936         while ( revItSub->more() )
937         {
938           SMESH_subMesh* sm = revItSub->next();
939           checkConformIgnoredAlgos (aMesh, sm, aGlobIgnoAlgo,
940                                     algo, checkConform2, aCheckedMap, theErrors);
941           aCheckedMap.insert( sm );
942         }
943       }
944     }
945   }
946
947   return ret;
948 }
949
950 //=======================================================================
951 //function : checkMissing
952 //purpose  : notify on missing hypothesis
953 //           Return false if algo or hipothesis is missing
954 //=======================================================================
955
956 static bool checkMissing(SMESH_Gen*                aGen,
957                          SMESH_Mesh&               aMesh,
958                          SMESH_subMesh*            aSubMesh,
959                          const int                 aTopAlgoDim,
960                          bool*                     globalChecked,
961                          const bool                checkNoAlgo,
962                          set<SMESH_subMesh*>&      aCheckedMap,
963                          list< SMESH_Gen::TAlgoStateError > & theErrors)
964 {
965   switch ( aSubMesh->GetSubShape().ShapeType() )
966   {
967   case TopAbs_EDGE:
968   case TopAbs_FACE:
969   case TopAbs_SOLID: break; // check this sub-mesh, it can be meshed
970   default:
971     return true; // not meshable sub-mesh
972   }
973   if ( aCheckedMap.count( aSubMesh ))
974     return true;
975
976   int ret = true;
977   SMESH_Algo* algo = 0;
978
979   switch (aSubMesh->GetAlgoState())
980   {
981   case SMESH_subMesh::NO_ALGO: {
982     if (checkNoAlgo)
983     {
984       // should there be any algo?
985       int shapeDim = SMESH_Gen::GetShapeDim( aSubMesh->GetSubShape() );
986       if (aTopAlgoDim > shapeDim)
987       {
988         MESSAGE( "ERROR: " << shapeDim << "D algorithm is missing" );
989         ret = false;
990         theErrors.push_back( SMESH_Gen::TAlgoStateError() );
991         theErrors.back().Set( SMESH_Hypothesis::HYP_MISSING, shapeDim, true );
992       }
993     }
994     return ret;
995   }
996   case SMESH_subMesh::MISSING_HYP: {
997     // notify if an algo missing hyp is attached to aSubMesh
998     algo = aSubMesh->GetAlgo();
999     ASSERT( algo );
1000     bool IsGlobalHypothesis = aGen->IsGlobalHypothesis( algo, aMesh );
1001     if (!IsGlobalHypothesis || !globalChecked[ algo->GetDim() ])
1002     {
1003       TAlgoStateErrorName errName = SMESH_Hypothesis::HYP_MISSING;
1004       SMESH_Hypothesis::Hypothesis_Status status;
1005       algo->CheckHypothesis( aMesh, aSubMesh->GetSubShape(), status );
1006       if ( status == SMESH_Hypothesis::HYP_BAD_PARAMETER ) {
1007         MESSAGE( "ERROR: hypothesis of " << (IsGlobalHypothesis ? "Global " : "Local ")
1008                  << "<" << algo->GetName() << "> has a bad parameter value");
1009         errName = status;
1010       } else if ( status == SMESH_Hypothesis::HYP_BAD_GEOMETRY ) {
1011         MESSAGE( "ERROR: " << (IsGlobalHypothesis ? "Global " : "Local ")
1012                  << "<" << algo->GetName() << "> assigned to mismatching geometry");
1013         errName = status;
1014       } else {
1015         MESSAGE( "ERROR: " << (IsGlobalHypothesis ? "Global " : "Local ")
1016                  << "<" << algo->GetName() << "> misses some hypothesis");
1017       }
1018       if (IsGlobalHypothesis)
1019         globalChecked[ algo->GetDim() ] = true;
1020       theErrors.push_back( SMESH_Gen::TAlgoStateError() );
1021       theErrors.back().Set( errName, algo, IsGlobalHypothesis );
1022     }
1023     ret = false;
1024     break;
1025   }
1026   case SMESH_subMesh::HYP_OK:
1027     algo = aSubMesh->GetAlgo();
1028     ret = true;
1029     if (!algo->NeedDiscreteBoundary())
1030     {
1031       SMESH_subMeshIteratorPtr itsub = aSubMesh->getDependsOnIterator( /*includeSelf=*/false,
1032                                                                        /*complexShapeFirst=*/false);
1033       while ( itsub->more() )
1034         aCheckedMap.insert( itsub->next() );
1035     }
1036     break;
1037   default: ASSERT(0);
1038   }
1039
1040   // do not check under algo that hides sub-algos or
1041   // re-start checking NO_ALGO state
1042   ASSERT (algo);
1043   bool isTopLocalAlgo =
1044     ( aTopAlgoDim <= algo->GetDim() && !aGen->IsGlobalHypothesis( algo, aMesh ));
1045   if (!algo->NeedDiscreteBoundary() || isTopLocalAlgo)
1046   {
1047     bool checkNoAlgo2 = ( algo->NeedDiscreteBoundary() );
1048     SMESH_subMeshIteratorPtr itsub = aSubMesh->getDependsOnIterator( /*includeSelf=*/false,
1049                                                                      /*complexShapeFirst=*/true);
1050     while ( itsub->more() )
1051     {
1052       // sub-meshes should not be checked further more
1053       SMESH_subMesh* sm = itsub->next();
1054
1055       if (isTopLocalAlgo)
1056       {
1057         //check algo on sub-meshes
1058         int aTopAlgoDim2 = algo->GetDim();
1059         if (!checkMissing (aGen, aMesh, sm, aTopAlgoDim2,
1060                            globalChecked, checkNoAlgo2, aCheckedMap, theErrors))
1061         {
1062           ret = false;
1063           if (sm->GetAlgoState() == SMESH_subMesh::NO_ALGO )
1064             checkNoAlgo2 = false;
1065         }
1066       }
1067       aCheckedMap.insert( sm );
1068     }
1069   }
1070   return ret;
1071 }
1072
1073 //=======================================================================
1074 //function : CheckAlgoState
1075 //purpose  : notify on bad state of attached algos, return false
1076 //           if Compute() would fail because of some algo bad state
1077 //=======================================================================
1078
1079 bool SMESH_Gen::CheckAlgoState(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape)
1080 {
1081   list< TAlgoStateError > errors;
1082   return GetAlgoState( aMesh, aShape, errors );
1083 }
1084
1085 //=======================================================================
1086 //function : GetAlgoState
1087 //purpose  : notify on bad state of attached algos, return false
1088 //           if Compute() would fail because of some algo bad state
1089 //           theErrors list contains problems description
1090 //=======================================================================
1091
1092 bool SMESH_Gen::GetAlgoState(SMESH_Mesh&               theMesh,
1093                              const TopoDS_Shape&       theShape,
1094                              list< TAlgoStateError > & theErrors)
1095 {
1096   bool ret = true;
1097   bool hasAlgo = false;
1098
1099   SMESH_subMesh*          sm = theMesh.GetSubMesh(theShape);
1100   const SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
1101   TopoDS_Shape     mainShape = meshDS->ShapeToMesh();
1102
1103   // -----------------
1104   // get global algos
1105   // -----------------
1106
1107   const SMESH_Algo* aGlobAlgoArr[] = {0,0,0,0};
1108
1109   const list<const SMESHDS_Hypothesis*>& listHyp = meshDS->GetHypothesis( mainShape );
1110   list<const SMESHDS_Hypothesis*>::const_iterator it=listHyp.begin();
1111   for ( ; it != listHyp.end(); it++)
1112   {
1113     const SMESHDS_Hypothesis * aHyp = *it;
1114     if (aHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO)
1115       continue;
1116
1117     const SMESH_Algo* algo = dynamic_cast<const SMESH_Algo*> (aHyp);
1118     ASSERT ( algo );
1119
1120     int dim = algo->GetDim();
1121     aGlobAlgoArr[ dim ] = algo;
1122
1123     hasAlgo = true;
1124   }
1125
1126   // --------------------------------------------------------
1127   // info on algos that will be ignored because of ones that
1128   // don't NeedDiscreteBoundary() attached to super-shapes,
1129   // check that a conform mesh will be produced
1130   // --------------------------------------------------------
1131
1132
1133   // find a global algo possibly hiding sub-algos
1134   int dim;
1135   const SMESH_Algo* aGlobIgnoAlgo = 0;
1136   for (dim = 3; dim > 0; dim--)
1137   {
1138     if (aGlobAlgoArr[ dim ] &&
1139         !aGlobAlgoArr[ dim ]->NeedDiscreteBoundary() /*&&
1140         !aGlobAlgoArr[ dim ]->SupportSubmeshes()*/ )
1141     {
1142       aGlobIgnoAlgo = aGlobAlgoArr[ dim ];
1143       break;
1144     }
1145   }
1146
1147   set<SMESH_subMesh*> aCheckedSubs;
1148   bool checkConform = ( !theMesh.IsNotConformAllowed() );
1149
1150   // loop on theShape and its sub-shapes
1151   SMESH_subMeshIteratorPtr revItSub = sm->getDependsOnIterator( /*includeSelf=*/true,
1152                                                                 /*complexShapeFirst=*/true);
1153   while ( revItSub->more() )
1154   {
1155     SMESH_subMesh* smToCheck = revItSub->next();
1156     if ( smToCheck->GetSubShape().ShapeType() == TopAbs_VERTEX)
1157       break;
1158
1159     if ( aCheckedSubs.insert( smToCheck ).second ) // not yet checked
1160       if (!checkConformIgnoredAlgos (theMesh, smToCheck, aGlobIgnoAlgo,
1161                                      0, checkConform, aCheckedSubs, theErrors))
1162         ret = false;
1163
1164     if ( smToCheck->GetAlgoState() != SMESH_subMesh::NO_ALGO )
1165       hasAlgo = true;
1166   }
1167
1168   // ----------------------------------------------------------------
1169   // info on missing hypothesis and find out if all needed algos are
1170   // well defined
1171   // ----------------------------------------------------------------
1172
1173   // find max dim of global algo
1174   int aTopAlgoDim = 0;
1175   for (dim = 3; dim > 0; dim--)
1176   {
1177     if (aGlobAlgoArr[ dim ])
1178     {
1179       aTopAlgoDim = dim;
1180       break;
1181     }
1182   }
1183   bool checkNoAlgo = theMesh.HasShapeToMesh() ? bool( aTopAlgoDim ) : false;
1184   bool globalChecked[] = { false, false, false, false };
1185
1186   // loop on theShape and its sub-shapes
1187   aCheckedSubs.clear();
1188   revItSub = sm->getDependsOnIterator( /*includeSelf=*/true, /*complexShapeFirst=*/true);
1189   while ( revItSub->more() )
1190   {
1191     SMESH_subMesh* smToCheck = revItSub->next();
1192     if ( smToCheck->GetSubShape().ShapeType() == TopAbs_VERTEX)
1193       break;
1194
1195     if (!checkMissing (this, theMesh, smToCheck, aTopAlgoDim,
1196                        globalChecked, checkNoAlgo, aCheckedSubs, theErrors))
1197     {
1198       ret = false;
1199       if (smToCheck->GetAlgoState() == SMESH_subMesh::NO_ALGO )
1200         checkNoAlgo = false;
1201     }
1202   }
1203
1204   if ( !hasAlgo ) {
1205     ret = false;
1206     theErrors.push_back( TAlgoStateError() );
1207     theErrors.back().Set( SMESH_Hypothesis::HYP_MISSING, theMesh.HasShapeToMesh() ? 1 : 3, true );
1208   }
1209
1210   return ret;
1211 }
1212
1213 //=======================================================================
1214 //function : IsGlobalHypothesis
1215 //purpose  : check if theAlgo is attached to the main shape
1216 //=======================================================================
1217
1218 bool SMESH_Gen::IsGlobalHypothesis(const SMESH_Hypothesis* theHyp, SMESH_Mesh& aMesh)
1219 {
1220   SMESH_HypoFilter filter( SMESH_HypoFilter::Is( theHyp ));
1221   return aMesh.GetHypothesis( aMesh.GetMeshDS()->ShapeToMesh(), filter, false );
1222 }
1223
1224 //================================================================================
1225 /*!
1226  * \brief Return paths to xml files of plugins
1227  */
1228 //================================================================================
1229
1230 std::vector< std::string > SMESH_Gen::GetPluginXMLPaths()
1231 {
1232   // Get paths to xml files of plugins
1233   vector< string > xmlPaths;
1234   string sep;
1235   if ( const char* meshersList = getenv("SMESH_MeshersList") )
1236   {
1237     string meshers = meshersList, plugin;
1238     string::size_type from = 0, pos;
1239     while ( from < meshers.size() )
1240     {
1241       // cut off plugin name
1242       pos = meshers.find( env_sep, from );
1243       if ( pos != string::npos )
1244         plugin = meshers.substr( from, pos-from );
1245       else
1246         plugin = meshers.substr( from ), pos = meshers.size();
1247       from = pos + 1;
1248
1249       // get PLUGIN_ROOT_DIR path
1250       string rootDirVar, pluginSubDir = plugin;
1251       if ( plugin == "StdMeshers" )
1252         rootDirVar = "SMESH", pluginSubDir = "smesh";
1253       else
1254         for ( pos = 0; pos < plugin.size(); ++pos )
1255           rootDirVar += toupper( plugin[pos] );
1256       rootDirVar += "_ROOT_DIR";
1257
1258       const char* rootDir = getenv( rootDirVar.c_str() );
1259       if ( !rootDir || strlen(rootDir) == 0 )
1260       {
1261         rootDirVar = plugin + "_ROOT_DIR"; // HexoticPLUGIN_ROOT_DIR
1262         rootDir = getenv( rootDirVar.c_str() );
1263         if ( !rootDir || strlen(rootDir) == 0 ) continue;
1264       }
1265
1266       // get a separator from rootDir
1267       for ( int i = strlen( rootDir )-1; i >= 0 && sep.empty(); --i )
1268         if ( rootDir[i] == '/' || rootDir[i] == '\\' )
1269         {
1270           sep = rootDir[i];
1271           break;
1272         }
1273 #ifdef WIN32
1274       if (sep.empty() ) sep = "\\";
1275 #else
1276       if (sep.empty() ) sep = "/";
1277 #endif
1278
1279       // get a path to resource file
1280       string xmlPath = rootDir;
1281       if ( xmlPath[ xmlPath.size()-1 ] != sep[0] )
1282         xmlPath += sep;
1283       xmlPath += "share" + sep + "salome" + sep + "resources" + sep;
1284       for ( pos = 0; pos < pluginSubDir.size(); ++pos )
1285         xmlPath += tolower( pluginSubDir[pos] );
1286       xmlPath += sep + plugin + ".xml";
1287       bool fileOK;
1288 #ifdef WIN32
1289 #  ifdef UNICODE
1290       const wchar_t* path = Kernel_Utils::decode_s(xmlPath);
1291       SMESHUtils::ArrayDeleter<const wchar_t> deleter( path );
1292 #  else
1293       const char* path = xmlPath.c_str();
1294 #  endif
1295       fileOK = (GetFileAttributes(path) != INVALID_FILE_ATTRIBUTES);
1296
1297 #else
1298       fileOK = (access(xmlPath.c_str(), F_OK) == 0);
1299 #endif
1300       if ( fileOK )
1301         xmlPaths.push_back( xmlPath );
1302     }
1303   }
1304
1305   return xmlPaths;
1306 }
1307
1308 //=============================================================================
1309 /*!
1310  * Finds algo to mesh a shape. Optionally returns a shape the found algo is bound to
1311  */
1312 //=============================================================================
1313
1314 SMESH_Algo *SMESH_Gen::GetAlgo(SMESH_Mesh &         aMesh,
1315                                const TopoDS_Shape & aShape,
1316                                TopoDS_Shape*        assignedTo)
1317 {
1318   return GetAlgo( aMesh.GetSubMesh( aShape ), assignedTo );
1319 }
1320
1321 //=============================================================================
1322 /*!
1323  * Finds algo to mesh a sub-mesh. Optionally returns a shape the found algo is bound to
1324  */
1325 //=============================================================================
1326
1327 SMESH_Algo *SMESH_Gen::GetAlgo(SMESH_subMesh * aSubMesh,
1328                                TopoDS_Shape*   assignedTo)
1329 {
1330   if ( !aSubMesh ) return 0;
1331
1332   const TopoDS_Shape & aShape = aSubMesh->GetSubShape();
1333   SMESH_Mesh&          aMesh  = *aSubMesh->GetFather();
1334
1335   SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
1336   if ( aMesh.HasShapeToMesh() )
1337     filter.And( filter.IsApplicableTo( aShape ));
1338
1339   typedef SMESH_Algo::Features AlgoData;
1340
1341   TopoDS_Shape assignedToShape;
1342   SMESH_Algo* algo =
1343     (SMESH_Algo*) aMesh.GetHypothesis( aSubMesh, filter, true, &assignedToShape );
1344
1345   if ( algo &&
1346        aShape.ShapeType() == TopAbs_FACE &&
1347        !aShape.IsSame( assignedToShape ) &&
1348        SMESH_MesherHelper::NbAncestors( aShape, aMesh, TopAbs_SOLID ) > 1 )
1349   {
1350     // Issue 0021559. If there is another 2D algo with different types of output
1351     // elements that can be used to mesh aShape, and 3D algos on adjacent SOLIDs
1352     // have different types of input elements, we choose a most appropriate 2D algo.
1353
1354     // try to find a concurrent 2D algo
1355     filter.AndNot( filter.Is( algo ));
1356     TopoDS_Shape assignedToShape2;
1357     SMESH_Algo* algo2 =
1358       (SMESH_Algo*) aMesh.GetHypothesis( aSubMesh, filter, true, &assignedToShape2 );
1359     if ( algo2 &&                                                  // algo found
1360          !assignedToShape2.IsSame( aMesh.GetShapeToMesh() ) &&     // algo is local
1361          ( SMESH_MesherHelper::GetGroupType( assignedToShape2 ) == // algo of the same level
1362            SMESH_MesherHelper::GetGroupType( assignedToShape )) &&
1363          aMesh.IsOrderOK( aMesh.GetSubMesh( assignedToShape2 ),    // no forced order
1364                           aMesh.GetSubMesh( assignedToShape  )))
1365     {
1366       // get algos on the adjacent SOLIDs
1367       filter.Init( filter.IsAlgo() ).And( filter.HasDim( 3 ));
1368       vector< SMESH_Algo* > algos3D;
1369       PShapeIteratorPtr solidIt = SMESH_MesherHelper::GetAncestors( aShape, aMesh,
1370                                                                     TopAbs_SOLID );
1371       while ( const TopoDS_Shape* solid = solidIt->next() )
1372         if ( SMESH_Algo* algo3D = (SMESH_Algo*) aMesh.GetHypothesis( *solid, filter, true ))
1373         {
1374           algos3D.push_back( algo3D );
1375           filter.AndNot( filter.HasName( algo3D->GetName() ));
1376         }
1377       // check compatibility of algos
1378       if ( algos3D.size() > 1 )
1379       {
1380         const AlgoData& algoData    = algo->SMESH_Algo::GetFeatures();
1381         const AlgoData& algoData2   = algo2->SMESH_Algo::GetFeatures();
1382         const AlgoData& algoData3d0 = algos3D[0]->SMESH_Algo::GetFeatures();
1383         const AlgoData& algoData3d1 = algos3D[1]->SMESH_Algo::GetFeatures();
1384         if (( algoData2.IsCompatible( algoData3d0 ) &&
1385               algoData2.IsCompatible( algoData3d1 ))
1386             &&
1387             !(algoData.IsCompatible( algoData3d0 ) &&
1388               algoData.IsCompatible( algoData3d1 )))
1389           algo = algo2;
1390       }
1391     }
1392   }
1393
1394   if ( assignedTo && algo )
1395     * assignedTo = assignedToShape;
1396
1397   return algo;
1398 }
1399
1400 //=============================================================================
1401 /*!
1402  * Returns StudyContextStruct for a study
1403  */
1404 //=============================================================================
1405
1406 StudyContextStruct *SMESH_Gen::GetStudyContext()
1407 {
1408   return _studyContext;
1409 }
1410
1411 //================================================================================
1412 /*!
1413  * \brief Return shape dimension by TopAbs_ShapeEnum
1414  */
1415 //================================================================================
1416
1417 int SMESH_Gen::GetShapeDim(const TopAbs_ShapeEnum & aShapeType)
1418 {
1419   static vector<int> dim;
1420   if ( dim.empty() )
1421   {
1422     dim.resize( TopAbs_SHAPE, -1 );
1423     dim[ TopAbs_COMPOUND ]  = MeshDim_3D;
1424     dim[ TopAbs_COMPSOLID ] = MeshDim_3D;
1425     dim[ TopAbs_SOLID ]     = MeshDim_3D;
1426     dim[ TopAbs_SHELL ]     = MeshDim_2D;
1427     dim[ TopAbs_FACE  ]     = MeshDim_2D;
1428     dim[ TopAbs_WIRE ]      = MeshDim_1D;
1429     dim[ TopAbs_EDGE ]      = MeshDim_1D;
1430     dim[ TopAbs_VERTEX ]    = MeshDim_0D;
1431   }
1432   return dim[ aShapeType ];
1433 }
1434
1435 //================================================================================
1436 /*!
1437  * \brief Return shape dimension by exploding compounds
1438  */
1439 //================================================================================
1440
1441 int SMESH_Gen::GetFlatShapeDim(const TopoDS_Shape &aShape)
1442 {
1443   int aShapeDim;
1444   if ( aShape.ShapeType() == TopAbs_COMPOUND ||
1445        aShape.ShapeType() == TopAbs_COMPSOLID )
1446   {
1447     TopoDS_Iterator it( aShape );
1448     aShapeDim = GetFlatShapeDim( it.Value() );
1449   }
1450   else
1451     aShapeDim = GetShapeDim( aShape );
1452   return aShapeDim;
1453 }
1454
1455 //=============================================================================
1456 /*!
1457  * Generate a new id unique within this Gen
1458  */
1459 //=============================================================================
1460
1461 int SMESH_Gen::GetANewId()
1462 {
1463   return _hypId++;
1464 }