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