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