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