Salome HOME
dae945eec5e6b328942f1f362a686f9df6e1184b
[modules/smesh.git] / src / SMESH / SMESH_Gen.cxx
1 // Copyright (C) 2007-2012  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 using namespace std;
50
51 //=============================================================================
52 /*!
53  *  Constructor
54  */
55 //=============================================================================
56
57 SMESH_Gen::SMESH_Gen()
58 {
59         MESSAGE("SMESH_Gen::SMESH_Gen");
60         _localId = 0;
61         _hypId = 0;
62         _segmentation = _nbSegments = 10;
63         SMDS_Mesh::_meshList.clear();
64         MESSAGE(SMDS_Mesh::_meshList.size());
65         _counters = new counters(100);
66 #ifdef WITH_SMESH_CANCEL_COMPUTE
67         _compute_canceled = false;
68         _sm_current = NULL;
69 #endif
70 }
71
72 //=============================================================================
73 /*!
74  * Destructor
75  */
76 //=============================================================================
77
78 SMESH_Gen::~SMESH_Gen()
79 {
80   MESSAGE("SMESH_Gen::~SMESH_Gen");
81 }
82
83 //=============================================================================
84 /*!
85  * Creates a mesh in a study.
86  * if (theIsEmbeddedMode) { mesh modification commands are not logged }
87  */
88 //=============================================================================
89
90 SMESH_Mesh* SMESH_Gen::CreateMesh(int theStudyId, bool theIsEmbeddedMode)
91   throw(SALOME_Exception)
92 {
93   Unexpect aCatch(SalomeException);
94   MESSAGE("SMESH_Gen::CreateMesh");
95
96   // Get studyContext, create it if it does'nt exist, with a SMESHDS_Document
97   StudyContextStruct *aStudyContext = GetStudyContext(theStudyId);
98
99   // create a new SMESH_mesh object
100   SMESH_Mesh *aMesh = new SMESH_Mesh(_localId++,
101                                      theStudyId,
102                                      this,
103                                      theIsEmbeddedMode,
104                                      aStudyContext->myDocument);
105   aStudyContext->mapMesh[_localId-1] = aMesh;
106
107   return aMesh;
108 }
109
110 //=============================================================================
111 /*!
112  * Compute a mesh
113  */
114 //=============================================================================
115
116 bool SMESH_Gen::Compute(SMESH_Mesh &          aMesh,
117                         const TopoDS_Shape &  aShape,
118                         const bool            anUpward,
119                         const ::MeshDimension aDim,
120                         TSetOfInt*            aShapesId)
121 {
122   MESSAGE("SMESH_Gen::Compute");
123   MEMOSTAT;
124
125   bool ret = true;
126
127   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
128
129   const bool includeSelf = true;
130   const bool complexShapeFirst = true;
131   const int  globalAlgoDim = 100;
132
133   SMESH_subMeshIteratorPtr smIt;
134
135   if ( anUpward ) // is called from below code here
136   {
137     // -----------------------------------------------
138     // mesh all the sub-shapes starting from vertices
139     // -----------------------------------------------
140     smIt = sm->getDependsOnIterator(includeSelf, !complexShapeFirst);
141     while ( smIt->more() )
142     {
143       SMESH_subMesh* smToCompute = smIt->next();
144
145       // do not mesh vertices of a pseudo shape
146       const TopAbs_ShapeEnum aShType = smToCompute->GetSubShape().ShapeType();
147       if ( !aMesh.HasShapeToMesh() && aShType == TopAbs_VERTEX )
148         continue;
149
150       // check for preview dimension limitations
151       if ( aShapesId && GetShapeDim( aShType ) > (int)aDim )
152       {
153         // clear compute state to not show previous compute errors
154         //  if preview invoked less dimension less than previous
155         smToCompute->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
156         continue;
157       }
158
159       if (smToCompute->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE)
160       {
161 #ifdef WITH_SMESH_CANCEL_COMPUTE
162         if (_compute_canceled)
163           return false;
164         _sm_current = smToCompute;
165 #endif
166         smToCompute->ComputeStateEngine( SMESH_subMesh::COMPUTE );
167 #ifdef WITH_SMESH_CANCEL_COMPUTE
168         _sm_current = NULL;
169 #endif
170       }
171
172       // we check all the submeshes here and detect if any of them failed to compute
173       if (smToCompute->GetComputeState() == SMESH_subMesh::FAILED_TO_COMPUTE)
174         ret = false;
175       else if ( aShapesId )
176         aShapesId->insert( smToCompute->GetId() );
177     }
178     //aMesh.GetMeshDS()->Modified();
179     return ret;
180   }
181   else
182   {
183     // -----------------------------------------------------------------
184     // apply algos that DO NOT require Discreteized boundaries and DO NOT
185     // support submeshes, starting from the most complex shapes
186     // and collect submeshes with algos that DO support submeshes
187     // -----------------------------------------------------------------
188     list< SMESH_subMesh* > smWithAlgoSupportingSubmeshes;
189
190     // map to sort sm with same dim algos according to dim of
191     // the shape the algo assigned to (issue 0021217)
192     multimap< int, SMESH_subMesh* > shDim2sm;
193     multimap< int, SMESH_subMesh* >::reverse_iterator shDim2smIt;
194     TopoDS_Shape algoShape;
195     int prevShapeDim = -1;
196
197     smIt = sm->getDependsOnIterator(includeSelf, complexShapeFirst);
198     while ( smIt->more() )
199     {
200       SMESH_subMesh* smToCompute = smIt->next();
201       if ( smToCompute->GetComputeState() != SMESH_subMesh::READY_TO_COMPUTE )
202         continue;
203
204       const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
205       int aShapeDim = GetShapeDim( aSubShape );
206       if ( aShapeDim < 1 ) break;
207       
208       // check for preview dimension limitations
209       if ( aShapesId && aShapeDim > (int)aDim )
210         continue;
211
212       SMESH_Algo* algo = GetAlgo( aMesh, aSubShape, &algoShape );
213       if ( algo && !algo->NeedDiscreteBoundary() )
214       {
215         if ( algo->SupportSubmeshes() )
216         {
217           // reload sub-meshes from shDim2sm into smWithAlgoSupportingSubmeshes
218           // so that more local algos to go first
219           if ( prevShapeDim != aShapeDim )
220           {
221             prevShapeDim = aShapeDim;
222             for ( shDim2smIt = shDim2sm.rbegin(); shDim2smIt != shDim2sm.rend(); ++shDim2smIt )
223               if ( shDim2smIt->first == globalAlgoDim )
224                 smWithAlgoSupportingSubmeshes.push_back( shDim2smIt->second );
225               else
226                 smWithAlgoSupportingSubmeshes.push_front( shDim2smIt->second );
227             shDim2sm.clear();
228           }
229           // add smToCompute to shDim2sm map
230           if ( algoShape.IsSame( aMesh.GetShapeToMesh() ))
231           {
232             aShapeDim = globalAlgoDim; // to compute last
233           }
234           else
235           {
236             aShapeDim = GetShapeDim( algoShape );
237             if ( algoShape.ShapeType() == TopAbs_COMPOUND )
238             {
239               TopoDS_Iterator it( algoShape );
240               aShapeDim += GetShapeDim( it.Value() );
241             }
242           }
243           shDim2sm.insert( make_pair( aShapeDim, smToCompute ));
244         }
245         else
246         {
247 #ifdef WITH_SMESH_CANCEL_COMPUTE
248           if (_compute_canceled)
249             return false;
250           _sm_current = smToCompute;
251 #endif
252           smToCompute->ComputeStateEngine( SMESH_subMesh::COMPUTE );
253 #ifdef WITH_SMESH_CANCEL_COMPUTE
254           _sm_current = NULL;
255 #endif
256           if ( aShapesId )
257             aShapesId->insert( smToCompute->GetId() );
258         }
259       }
260     }
261     // reload sub-meshes from shDim2sm into smWithAlgoSupportingSubmeshes
262     for ( shDim2smIt = shDim2sm.rbegin(); shDim2smIt != shDim2sm.rend(); ++shDim2smIt )
263       if ( shDim2smIt->first == globalAlgoDim )
264         smWithAlgoSupportingSubmeshes.push_back( shDim2smIt->second );
265       else
266         smWithAlgoSupportingSubmeshes.push_front( shDim2smIt->second );
267
268     // ------------------------------------------------------------
269     // sort list of submeshes according to mesh order
270     // ------------------------------------------------------------
271     aMesh.SortByMeshOrder( smWithAlgoSupportingSubmeshes );
272
273     // ------------------------------------------------------------
274     // compute submeshes under shapes with algos that DO NOT require
275     // Discreteized boundaries and DO support submeshes
276     // ------------------------------------------------------------
277     list< SMESH_subMesh* >::iterator subIt, subEnd;
278     subIt  = smWithAlgoSupportingSubmeshes.begin();
279     subEnd = smWithAlgoSupportingSubmeshes.end();
280     // start from lower shapes
281     for ( ; subIt != subEnd; ++subIt )
282     {
283       sm = *subIt;
284
285       // get a shape the algo is assigned to
286       if ( !GetAlgo( aMesh, sm->GetSubShape(), & algoShape ))
287         continue; // strange...
288
289       // look for more local algos
290       smIt = sm->getDependsOnIterator(!includeSelf, !complexShapeFirst);
291       while ( smIt->more() )
292       {
293         SMESH_subMesh* smToCompute = smIt->next();
294
295         const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
296         const int aShapeDim = GetShapeDim( aSubShape );
297         //if ( aSubShape.ShapeType() == TopAbs_VERTEX ) continue;
298         if ( aShapeDim < 1 ) continue;
299
300         // check for preview dimension limitations
301         if ( aShapesId && GetShapeDim( aSubShape.ShapeType() ) > (int)aDim )
302           continue;
303         
304         SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
305         filter
306           .And( SMESH_HypoFilter::IsApplicableTo( aSubShape ))
307           .And( SMESH_HypoFilter::IsMoreLocalThan( algoShape, aMesh ));
308
309         if ( SMESH_Algo* subAlgo = (SMESH_Algo*) aMesh.GetHypothesis( aSubShape, filter, true )) {
310           SMESH_Hypothesis::Hypothesis_Status status;
311           if ( subAlgo->CheckHypothesis( aMesh, aSubShape, status ))
312             // mesh a lower smToCompute starting from vertices
313             Compute( aMesh, aSubShape, /*anUpward=*/true, aDim, aShapesId );
314         }
315       }
316     }
317     // ----------------------------------------------------------
318     // apply the algos that do not require Discreteized boundaries
319     // ----------------------------------------------------------
320     for ( subIt = smWithAlgoSupportingSubmeshes.begin(); subIt != subEnd; ++subIt )
321     {
322       sm = *subIt;
323       if ( sm->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE)
324       {
325         const TopAbs_ShapeEnum aShType = sm->GetSubShape().ShapeType();
326         // check for preview dimension limitations
327         if ( aShapesId && GetShapeDim( aShType ) > (int)aDim )
328           continue;
329
330 #ifdef WITH_SMESH_CANCEL_COMPUTE
331         if (_compute_canceled)
332           return false;
333         _sm_current = sm;
334 #endif
335         sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
336 #ifdef WITH_SMESH_CANCEL_COMPUTE
337         _sm_current = NULL;
338 #endif
339         if ( aShapesId )
340           aShapesId->insert( sm->GetId() );
341       }
342     }
343     // -----------------------------------------------
344     // mesh the rest sub-shapes starting from vertices
345     // -----------------------------------------------
346     ret = Compute( aMesh, aShape, /*anUpward=*/true, aDim, aShapesId );
347   }
348
349   MESSAGE( "VSR - SMESH_Gen::Compute() finished, OK = " << ret);
350   MEMOSTAT;
351
352   SMESHDS_Mesh *myMesh = aMesh.GetMeshDS();
353   myMesh->adjustStructure();
354   MESSAGE("*** compactMesh after compute");
355   myMesh->compactMesh();
356   //myMesh->adjustStructure();
357   list<int> listind = myMesh->SubMeshIndices();
358   list<int>::iterator it = listind.begin();
359   int total = 0;
360   for(; it != listind.end(); ++it)
361     {
362       ::SMESHDS_SubMesh *subMesh = myMesh->MeshElements(*it);
363       total +=  subMesh->getSize();
364     }
365   MESSAGE("total elements and nodes in submesh sets:" << total);
366   MESSAGE("Number of node objects " << SMDS_MeshNode::nbNodes);
367   MESSAGE("Number of cell objects " << SMDS_MeshCell::nbCells);
368   //myMesh->dumpGrid();
369   //aMesh.GetMeshDS()->Modified();
370
371   // fix quadratic mesh by bending iternal links near concave boundary
372   if ( aShape.IsSame( aMesh.GetShapeToMesh() ) &&
373        !aShapesId ) // not preview
374   {
375     SMESH_MesherHelper aHelper( aMesh );
376     if ( aHelper.IsQuadraticMesh() != SMESH_MesherHelper::LINEAR )
377       aHelper.FixQuadraticElements();
378   }
379   return ret;
380 }
381
382
383 #ifdef WITH_SMESH_CANCEL_COMPUTE
384 //=============================================================================
385 /*!
386  * Prepare Compute a mesh
387  */
388 //=============================================================================
389 void SMESH_Gen::PrepareCompute(SMESH_Mesh &          aMesh,
390                                const TopoDS_Shape &  aShape)
391 {
392   _compute_canceled = false;
393   _sm_current = NULL;
394 }
395 //=============================================================================
396 /*!
397  * Cancel Compute a mesh
398  */
399 //=============================================================================
400 void SMESH_Gen::CancelCompute(SMESH_Mesh &          aMesh,
401                               const TopoDS_Shape &  aShape)
402 {
403   _compute_canceled = true;
404   if(_sm_current)
405     {
406       _sm_current->ComputeStateEngine( SMESH_subMesh::COMPUTE_CANCELED );
407     }
408 }
409 #endif
410
411 //=============================================================================
412 /*!
413  * Evaluate a mesh
414  */
415 //=============================================================================
416
417 bool SMESH_Gen::Evaluate(SMESH_Mesh &          aMesh,
418                          const TopoDS_Shape &  aShape,
419                          MapShapeNbElems&      aResMap,
420                          const bool            anUpward,
421                          TSetOfInt*            aShapesId)
422 {
423   MESSAGE("SMESH_Gen::Evaluate");
424
425   bool ret = true;
426
427   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
428
429   const bool includeSelf = true;
430   const bool complexShapeFirst = true;
431   SMESH_subMeshIteratorPtr smIt;
432
433   if ( anUpward ) { // is called from below code here
434     // -----------------------------------------------
435     // mesh all the sub-shapes starting from vertices
436     // -----------------------------------------------
437     smIt = sm->getDependsOnIterator(includeSelf, !complexShapeFirst);
438     while ( smIt->more() ) {
439       SMESH_subMesh* smToCompute = smIt->next();
440
441       // do not mesh vertices of a pseudo shape
442       const TopAbs_ShapeEnum aShType = smToCompute->GetSubShape().ShapeType();
443       //if ( !aMesh.HasShapeToMesh() && aShType == TopAbs_VERTEX )
444       //  continue;
445       if ( !aMesh.HasShapeToMesh() ) {
446         if( aShType == TopAbs_VERTEX || aShType == TopAbs_WIRE ||
447             aShType == TopAbs_SHELL )
448           continue;
449       }
450
451       smToCompute->Evaluate(aResMap);
452       if( aShapesId )
453         aShapesId->insert( smToCompute->GetId() );
454     }
455     return ret;
456   }
457   else {
458     // -----------------------------------------------------------------
459     // apply algos that DO NOT require Discreteized boundaries and DO NOT
460     // support submeshes, starting from the most complex shapes
461     // and collect submeshes with algos that DO support submeshes
462     // -----------------------------------------------------------------
463     list< SMESH_subMesh* > smWithAlgoSupportingSubmeshes;
464     smIt = sm->getDependsOnIterator(includeSelf, complexShapeFirst);
465     while ( smIt->more() ) {
466       SMESH_subMesh* smToCompute = smIt->next();
467       const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
468       const int aShapeDim = GetShapeDim( aSubShape );
469       if ( aShapeDim < 1 ) break;
470       
471       SMESH_Algo* algo = GetAlgo( aMesh, aSubShape );
472       if ( algo && !algo->NeedDiscreteBoundary() ) {
473         if ( algo->SupportSubmeshes() ) {
474           smWithAlgoSupportingSubmeshes.push_front( smToCompute );
475         }
476         else {
477           smToCompute->Evaluate(aResMap);
478           if ( aShapesId )
479             aShapesId->insert( smToCompute->GetId() );
480         }
481       }
482     }
483
484     // ------------------------------------------------------------
485     // sort list of meshes according to mesh order
486     // ------------------------------------------------------------
487     aMesh.SortByMeshOrder( smWithAlgoSupportingSubmeshes );
488
489     // ------------------------------------------------------------
490     // compute submeshes under shapes with algos that DO NOT require
491     // Discreteized boundaries and DO support submeshes
492     // ------------------------------------------------------------
493     list< SMESH_subMesh* >::iterator subIt, subEnd;
494     subIt  = smWithAlgoSupportingSubmeshes.begin();
495     subEnd = smWithAlgoSupportingSubmeshes.end();
496     // start from lower shapes
497     for ( ; subIt != subEnd; ++subIt ) {
498       sm = *subIt;
499
500       // get a shape the algo is assigned to
501       TopoDS_Shape algoShape;
502       if ( !GetAlgo( aMesh, sm->GetSubShape(), & algoShape ))
503         continue; // strange...
504
505       // look for more local algos
506       smIt = sm->getDependsOnIterator(!includeSelf, !complexShapeFirst);
507       while ( smIt->more() ) {
508         SMESH_subMesh* smToCompute = smIt->next();
509
510         const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
511         const int aShapeDim = GetShapeDim( aSubShape );
512         if ( aShapeDim < 1 ) continue;
513
514         //const TopAbs_ShapeEnum aShType = smToCompute->GetSubShape().ShapeType();
515
516         SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
517         filter
518           .And( SMESH_HypoFilter::IsApplicableTo( aSubShape ))
519           .And( SMESH_HypoFilter::IsMoreLocalThan( algoShape, aMesh ));
520
521         if ( SMESH_Algo* subAlgo = (SMESH_Algo*) aMesh.GetHypothesis( aSubShape, filter, true )) {
522           SMESH_Hypothesis::Hypothesis_Status status;
523           if ( subAlgo->CheckHypothesis( aMesh, aSubShape, status ))
524             // mesh a lower smToCompute starting from vertices
525             Evaluate( aMesh, aSubShape, aResMap, /*anUpward=*/true, aShapesId );
526         }
527       }
528     }
529     // ----------------------------------------------------------
530     // apply the algos that do not require Discreteized boundaries
531     // ----------------------------------------------------------
532     for ( subIt = smWithAlgoSupportingSubmeshes.begin(); subIt != subEnd; ++subIt )
533     {
534       sm = *subIt;
535       sm->Evaluate(aResMap);
536       if ( aShapesId )
537         aShapesId->insert( sm->GetId() );
538     }
539
540     // -----------------------------------------------
541     // mesh the rest sub-shapes starting from vertices
542     // -----------------------------------------------
543     ret = Evaluate( aMesh, aShape, aResMap, /*anUpward=*/true, aShapesId );
544   }
545
546   MESSAGE( "VSR - SMESH_Gen::Evaluate() finished, OK = " << ret);
547   return ret;
548 }
549
550
551 //=======================================================================
552 //function : checkConformIgnoredAlgos
553 //purpose  :
554 //=======================================================================
555
556 static bool checkConformIgnoredAlgos(SMESH_Mesh&               aMesh,
557                                      SMESH_subMesh*            aSubMesh,
558                                      const SMESH_Algo*         aGlobIgnoAlgo,
559                                      const SMESH_Algo*         aLocIgnoAlgo,
560                                      bool &                    checkConform,
561                                      set<SMESH_subMesh*>&      aCheckedMap,
562                                      list< SMESH_Gen::TAlgoStateError > & theErrors)
563 {
564   ASSERT( aSubMesh );
565   if ( aSubMesh->GetSubShape().ShapeType() == TopAbs_VERTEX)
566     return true;
567
568
569   bool ret = true;
570
571   const list<const SMESHDS_Hypothesis*>& listHyp =
572     aMesh.GetMeshDS()->GetHypothesis( aSubMesh->GetSubShape() );
573   list<const SMESHDS_Hypothesis*>::const_iterator it=listHyp.begin();
574   for ( ; it != listHyp.end(); it++)
575   {
576     const SMESHDS_Hypothesis * aHyp = *it;
577     if (aHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO)
578       continue;
579
580     const SMESH_Algo* algo = dynamic_cast<const SMESH_Algo*> (aHyp);
581     ASSERT ( algo );
582
583     if ( aLocIgnoAlgo ) // algo is hidden by a local algo of upper dim
584     {
585       INFOS( "Local <" << algo->GetName() << "> is hidden by local <"
586             << aLocIgnoAlgo->GetName() << ">");
587     }
588     else
589     {
590       bool isGlobal = (aMesh.IsMainShape( aSubMesh->GetSubShape() ));
591       int dim = algo->GetDim();
592       int aMaxGlobIgnoDim = ( aGlobIgnoAlgo ? aGlobIgnoAlgo->GetDim() : -1 );
593
594       if ( dim < aMaxGlobIgnoDim )
595       {
596         // algo is hidden by a global algo
597         INFOS( ( isGlobal ? "Global" : "Local" )
598               << " <" << algo->GetName() << "> is hidden by global <"
599               << aGlobIgnoAlgo->GetName() << ">");
600       }
601       else if ( !algo->NeedDiscreteBoundary() && !isGlobal)
602       {
603         // local algo is not hidden and hides algos on sub-shapes
604         if (checkConform && !aSubMesh->IsConform( algo ))
605         {
606           ret = false;
607           checkConform = false; // no more check conformity
608           INFOS( "ERROR: Local <" << algo->GetName() <<
609                 "> would produce not conform mesh: "
610                 "<Not Conform Mesh Allowed> hypotesis is missing");
611           theErrors.push_back( SMESH_Gen::TAlgoStateError() );
612           theErrors.back().Set( SMESH_Hypothesis::HYP_NOTCONFORM, algo, false );
613         }
614
615         // sub-algos will be hidden by a local <algo>
616         SMESH_subMeshIteratorPtr revItSub =
617           aSubMesh->getDependsOnIterator( /*includeSelf=*/false, /*complexShapeFirst=*/true);
618         bool checkConform2 = false;
619         while ( revItSub->more() )
620         {
621           SMESH_subMesh* sm = revItSub->next();
622           checkConformIgnoredAlgos (aMesh, sm, aGlobIgnoAlgo,
623                                     algo, checkConform2, aCheckedMap, theErrors);
624           aCheckedMap.insert( sm );
625         }
626       }
627     }
628   }
629
630   return ret;
631 }
632
633 //=======================================================================
634 //function : checkMissing
635 //purpose  : notify on missing hypothesis
636 //           Return false if algo or hipothesis is missing
637 //=======================================================================
638
639 static bool checkMissing(SMESH_Gen*                aGen,
640                          SMESH_Mesh&               aMesh,
641                          SMESH_subMesh*            aSubMesh,
642                          const int                 aTopAlgoDim,
643                          bool*                     globalChecked,
644                          const bool                checkNoAlgo,
645                          set<SMESH_subMesh*>&      aCheckedMap,
646                          list< SMESH_Gen::TAlgoStateError > & theErrors)
647 {
648   if ( aSubMesh->GetSubShape().ShapeType() == TopAbs_VERTEX)
649     return true;
650
651   //MESSAGE("=====checkMissing");
652
653   int ret = true;
654   SMESH_Algo* algo = 0;
655
656   switch (aSubMesh->GetAlgoState())
657   {
658   case SMESH_subMesh::NO_ALGO: {
659     if (checkNoAlgo)
660     {
661       // should there be any algo?
662       int shapeDim = SMESH_Gen::GetShapeDim( aSubMesh->GetSubShape() );
663       if (aTopAlgoDim > shapeDim)
664       {
665         MESSAGE( "ERROR: " << shapeDim << "D algorithm is missing" );
666         ret = false;
667         theErrors.push_back( SMESH_Gen::TAlgoStateError() );
668         theErrors.back().Set( SMESH_Hypothesis::HYP_MISSING, shapeDim, true );
669       }
670     }
671     return ret;
672   }
673   case SMESH_subMesh::MISSING_HYP: {
674     // notify if an algo missing hyp is attached to aSubMesh
675     algo = aGen->GetAlgo( aMesh, aSubMesh->GetSubShape() );
676     ASSERT( algo );
677     bool IsGlobalHypothesis = aGen->IsGlobalHypothesis( algo, aMesh );
678     if (!IsGlobalHypothesis || !globalChecked[ algo->GetDim() ])
679     {
680       TAlgoStateErrorName errName = SMESH_Hypothesis::HYP_MISSING;
681       SMESH_Hypothesis::Hypothesis_Status status;
682       algo->CheckHypothesis( aMesh, aSubMesh->GetSubShape(), status );
683       if ( status == SMESH_Hypothesis::HYP_BAD_PARAMETER ) {
684         MESSAGE( "ERROR: hypothesis of " << (IsGlobalHypothesis ? "Global " : "Local ")
685                  << "<" << algo->GetName() << "> has a bad parameter value");
686         errName = status;
687       } else if ( status == SMESH_Hypothesis::HYP_BAD_GEOMETRY ) {
688         MESSAGE( "ERROR: " << (IsGlobalHypothesis ? "Global " : "Local ")
689                  << "<" << algo->GetName() << "> assigned to mismatching geometry");
690         errName = status;
691       } else {
692         MESSAGE( "ERROR: " << (IsGlobalHypothesis ? "Global " : "Local ")
693                  << "<" << algo->GetName() << "> misses some hypothesis");
694       }
695       if (IsGlobalHypothesis)
696         globalChecked[ algo->GetDim() ] = true;
697       theErrors.push_back( SMESH_Gen::TAlgoStateError() );
698       theErrors.back().Set( errName, algo, IsGlobalHypothesis );
699     }
700     ret = false;
701     break;
702   }
703   case SMESH_subMesh::HYP_OK:
704     algo = aGen->GetAlgo( aMesh, aSubMesh->GetSubShape() );
705     ret = true;
706     break;
707   default: ASSERT(0);
708   }
709
710   // do not check under algo that hides sub-algos or
711   // re-start checking NO_ALGO state
712   ASSERT (algo);
713   bool isTopLocalAlgo =
714     ( aTopAlgoDim <= algo->GetDim() && !aGen->IsGlobalHypothesis( algo, aMesh ));
715   if (!algo->NeedDiscreteBoundary() || isTopLocalAlgo)
716   {
717     bool checkNoAlgo2 = ( algo->NeedDiscreteBoundary() );
718     SMESH_subMeshIteratorPtr itsub = aSubMesh->getDependsOnIterator( /*includeSelf=*/false,
719                                                                      /*complexShapeFirst=*/false);
720     while ( itsub->more() )
721     {
722       // sub-meshes should not be checked further more
723       SMESH_subMesh* sm = itsub->next();
724       aCheckedMap.insert( sm );
725
726       if (isTopLocalAlgo)
727       {
728         //check algo on sub-meshes
729         int aTopAlgoDim2 = algo->GetDim();
730         if (!checkMissing (aGen, aMesh, sm, aTopAlgoDim2,
731                            globalChecked, checkNoAlgo2, aCheckedMap, theErrors))
732         {
733           ret = false;
734           if (sm->GetAlgoState() == SMESH_subMesh::NO_ALGO )
735             checkNoAlgo2 = false;
736         }
737       }
738     }
739   }
740   return ret;
741 }
742
743 //=======================================================================
744 //function : CheckAlgoState
745 //purpose  : notify on bad state of attached algos, return false
746 //           if Compute() would fail because of some algo bad state
747 //=======================================================================
748
749 bool SMESH_Gen::CheckAlgoState(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape)
750 {
751   list< TAlgoStateError > errors;
752   return GetAlgoState( aMesh, aShape, errors );
753 }
754
755 //=======================================================================
756 //function : GetAlgoState
757 //purpose  : notify on bad state of attached algos, return false
758 //           if Compute() would fail because of some algo bad state
759 //           theErrors list contains problems description
760 //=======================================================================
761
762 bool SMESH_Gen::GetAlgoState(SMESH_Mesh&               theMesh,
763                              const TopoDS_Shape&       theShape,
764                              list< TAlgoStateError > & theErrors)
765 {
766   //MESSAGE("SMESH_Gen::CheckAlgoState");
767
768   bool ret = true;
769   bool hasAlgo = false;
770
771   SMESH_subMesh* sm = theMesh.GetSubMesh(theShape);
772   const SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
773   TopoDS_Shape mainShape = meshDS->ShapeToMesh();
774
775   // -----------------
776   // get global algos
777   // -----------------
778
779   const SMESH_Algo* aGlobAlgoArr[] = {0,0,0,0};
780
781   const list<const SMESHDS_Hypothesis*>& listHyp = meshDS->GetHypothesis( mainShape );
782   list<const SMESHDS_Hypothesis*>::const_iterator it=listHyp.begin();
783   for ( ; it != listHyp.end(); it++)
784   {
785     const SMESHDS_Hypothesis * aHyp = *it;
786     if (aHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO)
787       continue;
788
789     const SMESH_Algo* algo = dynamic_cast<const SMESH_Algo*> (aHyp);
790     ASSERT ( algo );
791
792     int dim = algo->GetDim();
793     aGlobAlgoArr[ dim ] = algo;
794
795     hasAlgo = true;
796   }
797
798   // --------------------------------------------------------
799   // info on algos that will be ignored because of ones that
800   // don't NeedDiscreteBoundary() attached to super-shapes,
801   // check that a conform mesh will be produced
802   // --------------------------------------------------------
803
804
805   // find a global algo possibly hiding sub-algos
806   int dim;
807   const SMESH_Algo* aGlobIgnoAlgo = 0;
808   for (dim = 3; dim > 0; dim--)
809   {
810     if (aGlobAlgoArr[ dim ] &&
811         !aGlobAlgoArr[ dim ]->NeedDiscreteBoundary())
812     {
813       aGlobIgnoAlgo = aGlobAlgoArr[ dim ];
814       break;
815     }
816   }
817
818   set<SMESH_subMesh*> aCheckedSubs;
819   bool checkConform = ( !theMesh.IsNotConformAllowed() );
820
821   // loop on theShape and its sub-shapes
822   SMESH_subMeshIteratorPtr revItSub = sm->getDependsOnIterator( /*includeSelf=*/true,
823                                                                 /*complexShapeFirst=*/true);
824   while ( revItSub->more() )
825   {
826     SMESH_subMesh* smToCheck = revItSub->next();
827     if ( smToCheck->GetSubShape().ShapeType() == TopAbs_VERTEX)
828       break;
829
830     if ( aCheckedSubs.insert( smToCheck ).second ) // not yet checked
831       if (!checkConformIgnoredAlgos (theMesh, smToCheck, aGlobIgnoAlgo,
832                                      0, checkConform, aCheckedSubs, theErrors))
833         ret = false;
834
835     if ( smToCheck->GetAlgoState() != SMESH_subMesh::NO_ALGO )
836       hasAlgo = true;
837   }
838
839   // ----------------------------------------------------------------
840   // info on missing hypothesis and find out if all needed algos are
841   // well defined
842   // ----------------------------------------------------------------
843
844   //MESSAGE( "---info on missing hypothesis and find out if all needed algos are");
845
846   // find max dim of global algo
847   int aTopAlgoDim = 0;
848   for (dim = 3; dim > 0; dim--)
849   {
850     if (aGlobAlgoArr[ dim ])
851     {
852       aTopAlgoDim = dim;
853       break;
854     }
855   }
856   bool checkNoAlgo = theMesh.HasShapeToMesh() ? bool( aTopAlgoDim ) : false;
857   bool globalChecked[] = { false, false, false, false };
858
859   // loop on theShape and its sub-shapes
860   aCheckedSubs.clear();
861   revItSub = sm->getDependsOnIterator( /*includeSelf=*/true, /*complexShapeFirst=*/true);
862   while ( revItSub->more() )
863   {
864     SMESH_subMesh* smToCheck = revItSub->next();
865     if ( smToCheck->GetSubShape().ShapeType() == TopAbs_VERTEX)
866       break;
867
868     if ( aCheckedSubs.insert( smToCheck ).second ) // not yet checked
869       if (!checkMissing (this, theMesh, smToCheck, aTopAlgoDim,
870                          globalChecked, checkNoAlgo, aCheckedSubs, theErrors))
871       {
872         ret = false;
873         if (smToCheck->GetAlgoState() == SMESH_subMesh::NO_ALGO )
874           checkNoAlgo = false;
875       }
876   }
877
878   if ( !hasAlgo ) {
879     ret = false;
880     INFOS( "None algorithm attached" );
881     theErrors.push_back( TAlgoStateError() );
882     theErrors.back().Set( SMESH_Hypothesis::HYP_MISSING, 1, true );
883   }
884
885   return ret;
886 }
887
888 //=======================================================================
889 //function : IsGlobalHypothesis
890 //purpose  : check if theAlgo is attached to the main shape
891 //=======================================================================
892
893 bool SMESH_Gen::IsGlobalHypothesis(const SMESH_Hypothesis* theHyp, SMESH_Mesh& aMesh)
894 {
895   SMESH_HypoFilter filter( SMESH_HypoFilter::Is( theHyp ));
896   return aMesh.GetHypothesis( aMesh.GetMeshDS()->ShapeToMesh(), filter, false );
897 }
898
899 //=============================================================================
900 /*!
901  * Finds algo to mesh a shape. Optionally returns a shape the found algo is bound to
902  */
903 //=============================================================================
904
905 SMESH_Algo *SMESH_Gen::GetAlgo(SMESH_Mesh &         aMesh,
906                                const TopoDS_Shape & aShape,
907                                TopoDS_Shape*        assignedTo)
908 {
909   SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
910   filter.And( filter.IsApplicableTo( aShape ));
911
912   return (SMESH_Algo*) aMesh.GetHypothesis( aShape, filter, true, assignedTo );
913 }
914
915 //=============================================================================
916 /*!
917  * Returns StudyContextStruct for a study
918  */
919 //=============================================================================
920
921 StudyContextStruct *SMESH_Gen::GetStudyContext(int studyId)
922 {
923   // Get studyContext, create it if it does'nt exist, with a SMESHDS_Document
924
925   if (_mapStudyContext.find(studyId) == _mapStudyContext.end())
926   {
927     _mapStudyContext[studyId] = new StudyContextStruct;
928     _mapStudyContext[studyId]->myDocument = new SMESHDS_Document(studyId);
929   }
930   StudyContextStruct *myStudyContext = _mapStudyContext[studyId];
931   return myStudyContext;
932 }
933
934 //================================================================================
935 /*!
936  * \brief Return shape dimension by TopAbs_ShapeEnum
937  */
938 //================================================================================
939
940 int SMESH_Gen::GetShapeDim(const TopAbs_ShapeEnum & aShapeType)
941 {
942   static vector<int> dim;
943   if ( dim.empty() )
944   {
945     dim.resize( TopAbs_SHAPE, -1 );
946     dim[ TopAbs_COMPOUND ]  = MeshDim_3D;
947     dim[ TopAbs_COMPSOLID ] = MeshDim_3D;
948     dim[ TopAbs_SOLID ]     = MeshDim_3D;
949     dim[ TopAbs_SHELL ]     = MeshDim_2D;
950     dim[ TopAbs_FACE  ]     = MeshDim_2D;
951     dim[ TopAbs_WIRE ]      = MeshDim_1D;
952     dim[ TopAbs_EDGE ]      = MeshDim_1D;
953     dim[ TopAbs_VERTEX ]    = MeshDim_0D;
954   }
955   return dim[ aShapeType ];
956 }
957
958 //=============================================================================
959 /*!
960  * Genarate a new id unique withing this Gen
961  */
962 //=============================================================================
963
964 int SMESH_Gen::GetANewId()
965 {
966   return _hypId++;
967 }