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