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