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