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