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