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