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