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