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