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