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