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