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