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