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