Salome HOME
Porting documentation on the Doxygen-1.8.0
[modules/smesh.git] / src / SMESH / SMESH_subMesh.cxx
1 // Copyright (C) 2007-2011  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 //  SMESH SMESH : implementaion of SMESH idl descriptions
23 //  File   : SMESH_subMesh.cxx
24 //  Author : Paul RASCLE, EDF
25 //  Module : SMESH
26
27 #include "SMESH_subMesh.hxx"
28
29 #include "SMESH_Algo.hxx"
30 #include "SMESH_Gen.hxx"
31 #include "SMESH_HypoFilter.hxx"
32 #include "SMESH_Hypothesis.hxx"
33 #include "SMESH_Mesh.hxx"
34 #include "SMESH_MesherHelper.hxx"
35 #include "SMESH_subMeshEventListener.hxx"
36 #include "SMESH_Comment.hxx"
37 #include "SMDS_SetIterator.hxx"
38 #include "SMDSAbs_ElementType.hxx"
39
40 #include <Basics_OCCTVersion.hxx>
41
42 #include "utilities.h"
43 #include "OpUtil.hxx"
44 #include "Basics_Utils.hxx"
45
46 #include <BRep_Builder.hxx>
47 #include <BRep_Tool.hxx>
48 #include <TopExp.hxx>
49 #include <TopTools_IndexedMapOfShape.hxx>
50 #include <TopTools_ListIteratorOfListOfShape.hxx>
51 #include <TopoDS.hxx>
52 #include <TopoDS_Compound.hxx>
53 #include <gp_Pnt.hxx>
54 #include <TopExp_Explorer.hxx>
55 #include <TopoDS_Iterator.hxx>
56
57 #include <Standard_OutOfMemory.hxx>
58 #include <Standard_ErrorHandler.hxx>
59
60 #include <numeric>
61
62 using namespace std;
63
64 //=============================================================================
65 /*!
66  * \brief Allocate some memory at construction and release it at destruction.
67  * Is used to be able to continue working after mesh generation breaks due to
68  * lack of memory
69  */
70 //=============================================================================
71
72 struct MemoryReserve
73 {
74   char* myBuf;
75   MemoryReserve(): myBuf( new char[1024*1024*2] ){}
76   ~MemoryReserve() { delete [] myBuf; }
77 };
78
79 //=============================================================================
80 /*!
81  *  default constructor:
82  */
83 //=============================================================================
84
85 SMESH_subMesh::SMESH_subMesh(int                  Id,
86                              SMESH_Mesh *         father,
87                              SMESHDS_Mesh *       meshDS,
88                              const TopoDS_Shape & aSubShape)
89 {
90         _subShape = aSubShape;
91         _subMeshDS = meshDS->MeshElements(_subShape);   // may be null ...
92         _father = father;
93         _Id = Id;
94         _dependenceAnalysed = _alwaysComputed = false;
95
96         if (_subShape.ShapeType() == TopAbs_VERTEX)
97         {
98                 _algoState = HYP_OK;
99                 _computeState = READY_TO_COMPUTE;
100         }
101         else
102         {
103           _algoState = NO_ALGO;
104           _computeState = NOT_READY;
105         }
106 }
107
108 //=============================================================================
109 /*!
110  *
111  */
112 //=============================================================================
113
114 SMESH_subMesh::~SMESH_subMesh()
115 {
116   MESSAGE("SMESH_subMesh::~SMESH_subMesh");
117   // ****
118   deleteOwnListeners();
119 }
120
121 //=============================================================================
122 /*!
123  *
124  */
125 //=============================================================================
126
127 int SMESH_subMesh::GetId() const
128 {
129   //MESSAGE("SMESH_subMesh::GetId");
130   return _Id;
131 }
132
133 //=============================================================================
134 /*!
135  *
136  */
137 //=============================================================================
138
139 SMESHDS_SubMesh * SMESH_subMesh::GetSubMeshDS()
140 {
141   // submesh appears in DS only when a mesher set nodes and elements on a shape
142   return _subMeshDS ? _subMeshDS : _subMeshDS = _father->GetMeshDS()->MeshElements(_subShape); // may be null
143 }
144
145 //=============================================================================
146 /*!
147  *
148  */
149 //=============================================================================
150
151 SMESHDS_SubMesh* SMESH_subMesh::CreateSubMeshDS()
152 {
153   if ( !GetSubMeshDS() ) {
154     SMESHDS_Mesh* meshDS = _father->GetMeshDS();
155     meshDS->NewSubMesh( meshDS->ShapeToIndex( _subShape ) );
156   }
157   return GetSubMeshDS();
158 }
159
160 //=============================================================================
161 /*!
162  *
163  */
164 //=============================================================================
165
166 SMESH_subMesh *SMESH_subMesh::GetFirstToCompute()
167 {
168   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(true,false);
169   while ( smIt->more() ) {
170     SMESH_subMesh *sm = smIt->next();
171     if ( sm->GetComputeState() == READY_TO_COMPUTE )
172       return sm;
173   }
174   return 0;                     // nothing to compute
175 }
176
177 //================================================================================
178 /*!
179  * \brief Returns a current algorithm
180  */
181 //================================================================================
182
183 SMESH_Algo* SMESH_subMesh::GetAlgo() const
184 {
185   return _father->GetGen()->GetAlgo(*_father, _subShape);
186 }
187
188 //================================================================================
189 /*!
190  * \brief Allow algo->Compute() if a sub-shape of lower dim is meshed but
191  *        none mesh entity is bound to it (PAL13615, 2nd part)
192  */
193 //================================================================================
194
195 void SMESH_subMesh::SetIsAlwaysComputed(bool isAlCo)
196 {
197   _alwaysComputed = isAlCo;
198   if ( _alwaysComputed )
199     _computeState = COMPUTE_OK;
200   else
201     ComputeStateEngine( CHECK_COMPUTE_STATE );
202 }
203
204 //=======================================================================
205 /*!
206  * \brief Return true if no mesh entities is bound to the submesh
207  */
208 //=======================================================================
209
210 bool SMESH_subMesh::IsEmpty() const
211 {
212   if (SMESHDS_SubMesh * subMeshDS = ((SMESH_subMesh*)this)->GetSubMeshDS())
213     return (!subMeshDS->NbElements() && !subMeshDS->NbNodes());
214   return true;
215 }
216
217 //=======================================================================
218 //function : IsMeshComputed
219 //purpose  : check if _subMeshDS contains mesh elements
220 //=======================================================================
221
222 bool SMESH_subMesh::IsMeshComputed() const
223 {
224   if ( _alwaysComputed )
225     return true;
226   // algo may bind a submesh not to _subShape, eg 3D algo
227   // sets nodes on SHELL while _subShape may be SOLID
228
229   SMESHDS_Mesh* meshDS = _father->GetMeshDS();
230   int dim = SMESH_Gen::GetShapeDim( _subShape );
231   int type = _subShape.ShapeType();
232   for ( ; type <= TopAbs_VERTEX; type++) {
233     if ( dim == SMESH_Gen::GetShapeDim( (TopAbs_ShapeEnum) type ))
234     {
235       TopExp_Explorer exp( _subShape, (TopAbs_ShapeEnum) type );
236       for ( ; exp.More(); exp.Next() )
237       {
238         if ( SMESHDS_SubMesh * smDS = meshDS->MeshElements( exp.Current() ))
239         {
240           bool computed = (dim > 0) ? smDS->NbElements() : smDS->NbNodes();
241           if ( computed )
242             return true;
243         }
244       }
245     }
246     else
247       break;
248   }
249
250   return false;
251 }
252
253 //=============================================================================
254 /*!
255  *
256  */
257 //=============================================================================
258
259 bool SMESH_subMesh::subMeshesComputed()
260 {
261   int myDim = SMESH_Gen::GetShapeDim( _subShape );
262   int dimToCheck = myDim - 1;
263   bool subMeshesComputed = true;
264   // check subMeshes with upper dimension => reverse iteration
265   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,true);
266   while ( smIt->more() )
267   {
268     SMESH_subMesh *sm = smIt->next();
269     if ( sm->_alwaysComputed )
270       continue;
271     const TopoDS_Shape & ss = sm->GetSubShape();
272     // MSV 07.04.2006: restrict checking to myDim-1 only. Ex., there is no sense
273     // in checking of existence of edges if the algo needs only faces. Moreover,
274     // degenerated edges may have no submesh, as after computing NETGEN_2D.
275     int dim = SMESH_Gen::GetShapeDim( ss );
276     if (dim < dimToCheck)
277       break; // the rest subMeshes are all of less dimension
278     SMESHDS_SubMesh * ds = sm->GetSubMeshDS();
279     bool computeOk = (sm->GetComputeState() == COMPUTE_OK ||
280                       (ds && ( dimToCheck ? ds->NbElements() : ds->NbNodes()  )));
281     if (!computeOk)
282     {
283       int type = ss.ShapeType();
284
285       subMeshesComputed = false;
286
287       switch (type)
288       {
289       case TopAbs_COMPOUND:
290         {
291           MESSAGE("The not computed sub mesh is a COMPOUND");
292           break;
293         }
294       case TopAbs_COMPSOLID:
295         {
296           MESSAGE("The not computed sub mesh is a COMPSOLID");
297           break;
298         }
299       case TopAbs_SHELL:
300         {
301           MESSAGE("The not computed sub mesh is a SHEL");
302           break;
303         }
304       case TopAbs_WIRE:
305         {
306           MESSAGE("The not computed sub mesh is a WIRE");
307           break;
308         }
309       case TopAbs_SOLID:
310         {
311           MESSAGE("The not computed sub mesh is a SOLID");
312           break;
313         }
314       case TopAbs_FACE:
315         {
316           MESSAGE("The not computed sub mesh is a FACE");
317           break;
318         }
319       case TopAbs_EDGE:
320         {
321           MESSAGE("The not computed sub mesh is a EDGE");
322           break;
323         }
324       default:
325         {
326           MESSAGE("The not computed sub mesh is of unknown type");
327           break;
328         }
329       }
330
331       break;
332     }
333   }
334   return subMeshesComputed;
335 }
336
337 //=============================================================================
338 /*!
339  *
340  */
341 //=============================================================================
342
343 // bool SMESH_subMesh::SubMeshesReady()
344 // {
345 //   bool subMeshesReady = true;
346 //   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,true);
347 //   while ( smIt->more() ) {
348 //     SMESH_subMesh *sm = smIt->next();
349 //     bool computeOk = (sm->GetComputeState() == COMPUTE_OK ||
350 //                       sm->GetComputeState() == READY_TO_COMPUTE);
351 //     if (!computeOk)
352 //     {
353 //       subMeshesReady = false;
354 //       SCRUTE(sm->GetId());
355 //       break;
356 //     }
357 //   }
358 //   return subMeshesReady;
359 // }
360
361 //=============================================================================
362 /*!
363  * Construct dependence on first level subMeshes. complex shapes (compsolid,
364  * shell, wire) are not analysed the same way as simple shapes (solid, face,
365  * edge).
366  * For collection shapes (compsolid, shell, wire) prepare a list of submeshes
367  * with possible multiples occurences. Multiples occurences corresponds to
368  * internal frontiers within shapes of the collection and must not be keeped.
369  * See FinalizeDependence.
370  */
371 //=============================================================================
372
373 const map < int, SMESH_subMesh * >& SMESH_subMesh::DependsOn()
374 {
375   if (_dependenceAnalysed)
376     return _mapDepend;
377
378   //MESSAGE("SMESH_subMesh::DependsOn");
379
380   int type = _subShape.ShapeType();
381   //SCRUTE(type);
382   switch (type)
383   {
384   case TopAbs_COMPOUND:
385     {
386       //MESSAGE("compound");
387       for (TopExp_Explorer exp(_subShape, TopAbs_SOLID); exp.More();exp.Next())
388       {
389         insertDependence(exp.Current());
390       }
391       for (TopExp_Explorer exp(_subShape, TopAbs_SHELL, TopAbs_SOLID); exp.More(); exp.Next())
392       {
393         if ( BRep_Tool::IsClosed(exp.Current() ))
394           insertDependence(exp.Current());      //only shell not in solid
395         else
396           for (TopExp_Explorer expF(exp.Current(), TopAbs_FACE); expF.More();expF.Next())
397             insertDependence(expF.Current());    // issue 0020959: HEXA_3D fails on shell
398
399       }
400       for (TopExp_Explorer exp(_subShape, TopAbs_FACE, TopAbs_SHELL); exp.More();exp.Next())
401       {
402         insertDependence(exp.Current());
403       }
404       for (TopExp_Explorer exp(_subShape, TopAbs_EDGE, TopAbs_FACE); exp.More();exp.Next())
405       {
406         insertDependence(exp.Current());
407       }
408       break;
409     }
410   case TopAbs_COMPSOLID:
411     {
412       //MESSAGE("compsolid");
413       for (TopExp_Explorer exp(_subShape, TopAbs_SOLID); exp.More(); exp.Next())
414       {
415         insertDependence(exp.Current());
416       }
417       break;
418     }
419   case TopAbs_SHELL:
420     {
421       //MESSAGE("shell");
422       for (TopExp_Explorer exp(_subShape, TopAbs_FACE); exp.More(); exp.Next())
423       {
424         insertDependence(exp.Current());
425       }
426       break;
427     }
428   case TopAbs_WIRE:
429     {
430       //MESSAGE("wire");
431       for (TopExp_Explorer exp(_subShape, TopAbs_EDGE); exp.More(); exp.Next())
432       {
433         insertDependence(exp.Current());
434       }
435       break;
436     }
437   case TopAbs_SOLID:
438     {
439       //MESSAGE("solid");
440       if(_father->HasShapeToMesh()) {
441         for (TopExp_Explorer exp(_subShape, TopAbs_FACE); exp.More();exp.Next())
442         {
443           insertDependence(exp.Current());
444         }
445       }
446       break;
447     }
448   case TopAbs_FACE:
449     {
450       //MESSAGE("face");
451       for (TopExp_Explorer exp(_subShape, TopAbs_EDGE); exp.More();exp.Next())
452       {
453         insertDependence(exp.Current());
454       }
455       break;
456     }
457   case TopAbs_EDGE:
458     {
459       //MESSAGE("edge");
460       for (TopExp_Explorer exp(_subShape, TopAbs_VERTEX); exp.More(); exp.Next())
461       {
462         insertDependence(exp.Current());
463       }
464       break;
465     }
466   case TopAbs_VERTEX:
467     {
468       break;
469     }
470   default:
471     {
472       break;
473     }
474   }
475   _dependenceAnalysed = true;
476   return _mapDepend;
477 }
478
479 //=============================================================================
480 /*!
481  * For simple Shapes (solid, face, edge): add subMesh into dependence list.
482  */
483 //=============================================================================
484
485 void SMESH_subMesh::insertDependence(const TopoDS_Shape aSubShape)
486 {
487   SMESH_subMesh *aSubMesh = _father->GetSubMesh(aSubShape);
488   int type = aSubShape.ShapeType();
489   int ordType = 9 - type;               // 2 = Vertex, 8 = CompSolid
490   int cle = aSubMesh->GetId();
491   cle += 10000000 * ordType;    // sort map by ordType then index
492   if ( _mapDepend.find( cle ) == _mapDepend.end())
493   {
494     _mapDepend[cle] = aSubMesh;
495     const map < int, SMESH_subMesh * > & subMap = aSubMesh->DependsOn();
496     _mapDepend.insert( subMap.begin(), subMap.end() );
497   }
498 }
499
500 //=============================================================================
501 /*!
502  *
503  */
504 //=============================================================================
505
506 const TopoDS_Shape & SMESH_subMesh::GetSubShape() const
507 {
508         //MESSAGE("SMESH_subMesh::GetSubShape");
509         return _subShape;
510 }
511
512
513 //=======================================================================
514 //function : CanAddHypothesis
515 //purpose  : return true if theHypothesis can be attached to me:
516 //           its dimention is checked
517 //=======================================================================
518
519 bool SMESH_subMesh::CanAddHypothesis(const SMESH_Hypothesis* theHypothesis) const
520 {
521   int aHypDim   = theHypothesis->GetDim();
522   int aShapeDim = SMESH_Gen::GetShapeDim(_subShape);
523   // issue 21106. Forbid 3D mesh on the SHELL
524   // if (aHypDim == 3 && aShapeDim == 3) {
525   //   // check case of open shell
526   //   //if (_subShape.ShapeType() == TopAbs_SHELL && !_subShape.Closed())
527   //   if (_subShape.ShapeType() == TopAbs_SHELL && !BRep_Tool::IsClosed(_subShape))
528   //     return false;
529   // }
530   if ( aHypDim <= aShapeDim )
531     return true;
532
533   return false;
534 }
535
536 //=======================================================================
537 //function : IsApplicableHypotesis
538 //purpose  :
539 //=======================================================================
540
541 bool SMESH_subMesh::IsApplicableHypotesis(const SMESH_Hypothesis* theHypothesis,
542                                           const TopAbs_ShapeEnum  theShapeType)
543 {
544   if ( theHypothesis->GetType() > SMESHDS_Hypothesis::PARAM_ALGO)
545   {
546     // algorithm
547     if ( theHypothesis->GetShapeType() & (1<< theShapeType))
548       // issue 21106. Forbid 3D mesh on the SHELL
549       return !( theHypothesis->GetDim() == 3 && theShapeType == TopAbs_SHELL );
550     else
551       return false;
552   }
553
554   // hypothesis
555   switch ( theShapeType ) {
556   case TopAbs_VERTEX:
557   case TopAbs_EDGE:
558   case TopAbs_FACE:
559   case TopAbs_SOLID:
560     return SMESH_Gen::GetShapeDim( theShapeType ) == theHypothesis->GetDim();
561
562   case TopAbs_SHELL:
563     // Special case for algorithms, building 2D mesh on a whole shell.
564     // Before this fix there was a problem after restoring from study,
565     // because in that case algorithm is assigned before hypothesis
566     // (on shell in problem case) and hypothesis is checked on faces
567     // (because it is 2D), where we have NO_ALGO state.
568     // Now 2D hypothesis is also applicable to shells.
569     return (theHypothesis->GetDim() == 2 || theHypothesis->GetDim() == 3);
570
571 //   case TopAbs_WIRE:
572 //   case TopAbs_COMPSOLID:
573 //   case TopAbs_COMPOUND:
574   default:;
575   }
576   return false;
577 }
578
579 //=============================================================================
580 /*!
581  *
582  */
583 //=============================================================================
584
585 SMESH_Hypothesis::Hypothesis_Status
586   SMESH_subMesh::AlgoStateEngine(int event, SMESH_Hypothesis * anHyp)
587 {
588   //  MESSAGE("SMESH_subMesh::AlgoStateEngine");
589   //SCRUTE(_algoState);
590   //SCRUTE(event);
591
592   // **** les retour des evenement shape sont significatifs
593   // (add ou remove fait ou non)
594   // le retour des evenement father n'indiquent pas que add ou remove fait
595
596   SMESH_Hypothesis::Hypothesis_Status aux_ret, ret = SMESH_Hypothesis::HYP_OK;
597
598   SMESHDS_Mesh* meshDS =_father->GetMeshDS();
599   //SMESH_Gen*    gen    =_father->GetGen();
600   SMESH_Algo*   algo   = 0;
601
602   if (_subShape.ShapeType() == TopAbs_VERTEX )
603   {
604     if ( anHyp->GetDim() != 0) {
605       if (event == ADD_HYP || event == ADD_ALGO)
606         return SMESH_Hypothesis::HYP_BAD_DIM;
607       else
608         return SMESH_Hypothesis::HYP_OK;
609     }
610     // 0D hypothesis
611     else if ( _algoState == HYP_OK ) {
612       // update default _algoState
613       if ( event != REMOVE_FATHER_ALGO )
614       {
615         _algoState = NO_ALGO;
616         algo = GetAlgo();
617         if ( algo ) {
618           _algoState = MISSING_HYP;
619           if ( event == REMOVE_FATHER_HYP ||
620                algo->CheckHypothesis(*_father,_subShape, aux_ret))
621             _algoState = HYP_OK;
622         }
623       }
624     }
625   }
626
627   int oldAlgoState = _algoState;
628   bool modifiedHyp = (event == MODIF_HYP);  // if set to true, force event MODIF_ALGO_STATE
629   bool needFullClean = false;
630
631   bool isApplicableHyp = IsApplicableHypotesis( anHyp );
632
633   if (event == ADD_ALGO || event == ADD_FATHER_ALGO)
634   {
635     // -------------------------------------------
636     // check if a shape needed by algo is present
637     // -------------------------------------------
638     algo = static_cast< SMESH_Algo* >( anHyp );
639     if ( !_father->HasShapeToMesh() && algo->NeedShape() )
640       return SMESH_Hypothesis::HYP_NEED_SHAPE;
641     // ----------------------
642     // check mesh conformity
643     // ----------------------
644     if (isApplicableHyp && !_father->IsNotConformAllowed() && !IsConform( algo ))
645       return SMESH_Hypothesis::HYP_NOTCONFORM;
646
647     // check if all-dimensional algo is hidden by other local one
648     if ( event == ADD_ALGO ) {
649       SMESH_HypoFilter filter( SMESH_HypoFilter::HasType( algo->GetType() ));
650       filter.Or( SMESH_HypoFilter::HasType( algo->GetType()+1 ));
651       filter.Or( SMESH_HypoFilter::HasType( algo->GetType()+2 ));
652       if ( SMESH_Algo * curAlgo = (SMESH_Algo*) _father->GetHypothesis( _subShape, filter, true ))
653         needFullClean = ( !curAlgo->NeedDiscreteBoundary() );
654     }
655   }
656
657   // ----------------------------------
658   // add a hypothesis to DS if possible
659   // ----------------------------------
660   if (event == ADD_HYP || event == ADD_ALGO)
661   {
662     if ( ! CanAddHypothesis( anHyp )) // check dimension
663       return SMESH_Hypothesis::HYP_BAD_DIM;
664
665     if ( /*!anHyp->IsAuxiliary() &&*/ getSimilarAttached( _subShape, anHyp ) )
666       return SMESH_Hypothesis::HYP_ALREADY_EXIST;
667
668     if ( !meshDS->AddHypothesis(_subShape, anHyp))
669       return SMESH_Hypothesis::HYP_ALREADY_EXIST;
670   }
671
672   // --------------------------
673   // remove a hypothesis from DS
674   // --------------------------
675   if (event == REMOVE_HYP || event == REMOVE_ALGO)
676   {
677     if (!meshDS->RemoveHypothesis(_subShape, anHyp))
678       return SMESH_Hypothesis::HYP_OK; // nothing changes
679
680     if (event == REMOVE_ALGO)
681     {
682       algo = dynamic_cast<SMESH_Algo*> (anHyp);
683       if (!algo->NeedDiscreteBoundary())
684       {
685         // clean all mesh in the tree of the current submesh;
686         // we must perform it now because later
687         // we will have no information about the type of the removed algo
688         needFullClean = true;
689       }
690     }
691   }
692
693   // ------------------
694   // analyse algo state
695   // ------------------
696   if (!isApplicableHyp)
697     return ret; // not applicable hypotheses do not change algo state
698
699   switch (_algoState)
700   {
701
702     // ----------------------------------------------------------------------
703
704   case NO_ALGO:
705     switch (event) {
706     case ADD_HYP:
707       break;
708     case ADD_ALGO: {
709       algo = GetAlgo();
710       ASSERT(algo);
711       if (algo->CheckHypothesis((*_father),_subShape, aux_ret))
712         setAlgoState(HYP_OK);
713       else if ( algo->IsStatusFatal( aux_ret )) {
714         meshDS->RemoveHypothesis(_subShape, anHyp);
715         ret = aux_ret;
716       }
717       else
718         setAlgoState(MISSING_HYP);
719       break;
720     }
721     case REMOVE_HYP:
722     case REMOVE_ALGO:
723     case ADD_FATHER_HYP:
724       break;
725     case ADD_FATHER_ALGO: {    // Algo just added in father
726       algo = GetAlgo();
727       ASSERT(algo);
728       if ( algo == anHyp ) {
729         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret))
730           setAlgoState(HYP_OK);
731         else
732           setAlgoState(MISSING_HYP);
733       }
734       break;
735     }
736     case REMOVE_FATHER_HYP:
737       break;
738     case REMOVE_FATHER_ALGO: {
739       algo = GetAlgo();
740       if (algo)
741       {
742         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret ))
743             setAlgoState(HYP_OK);
744         else
745           setAlgoState(MISSING_HYP);
746       }
747       break;
748     }
749     case MODIF_HYP: break;
750     default:
751       ASSERT(0);
752       break;
753     }
754     break;
755
756     // ----------------------------------------------------------------------
757
758   case MISSING_HYP:
759     switch (event)
760     {
761     case ADD_HYP: {
762       algo = GetAlgo();
763       ASSERT(algo);
764       if ( algo->CheckHypothesis((*_father),_subShape, ret ))
765         setAlgoState(HYP_OK);
766       if (SMESH_Hypothesis::IsStatusFatal( ret ))
767         meshDS->RemoveHypothesis(_subShape, anHyp);
768       else if (!_father->IsUsedHypothesis( anHyp, this ))
769       {
770         meshDS->RemoveHypothesis(_subShape, anHyp);
771         ret = SMESH_Hypothesis::HYP_INCOMPATIBLE;
772       }
773       break;
774     }
775     case ADD_ALGO: {           //already existing algo : on father ?
776       algo = GetAlgo();
777       ASSERT(algo);
778       if ( algo->CheckHypothesis((*_father),_subShape, aux_ret ))// ignore hyp status
779         setAlgoState(HYP_OK);
780       else if ( algo->IsStatusFatal( aux_ret )) {
781         meshDS->RemoveHypothesis(_subShape, anHyp);
782         ret = aux_ret;
783       }
784       else
785         setAlgoState(MISSING_HYP);
786       break;
787     }
788     case REMOVE_HYP:
789       break;
790     case REMOVE_ALGO: {        // perhaps a father algo applies ?
791       algo = GetAlgo();
792       if (algo == NULL)  // no more algo applying on sub-shape...
793       {
794         setAlgoState(NO_ALGO);
795       }
796       else
797       {
798         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret ))
799           setAlgoState(HYP_OK);
800         else
801           setAlgoState(MISSING_HYP);
802       }
803       break;
804     }
805     case MODIF_HYP: // assigned hypothesis value may become good
806     case ADD_FATHER_HYP: {
807       algo = GetAlgo();
808       ASSERT(algo);
809       if ( algo->CheckHypothesis((*_father),_subShape, aux_ret ))
810         setAlgoState(HYP_OK);
811       else
812         setAlgoState(MISSING_HYP);
813       break;
814     }
815     case ADD_FATHER_ALGO: { // new father algo
816       algo = GetAlgo();
817       ASSERT( algo );
818       if ( algo == anHyp ) {
819         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret ))
820           setAlgoState(HYP_OK);
821         else
822           setAlgoState(MISSING_HYP);
823       }
824       break;
825     }
826     case REMOVE_FATHER_HYP:    // nothing to do
827       break;
828     case REMOVE_FATHER_ALGO: {
829       algo = GetAlgo();
830       if (algo == NULL)  // no more applying algo on father
831       {
832         setAlgoState(NO_ALGO);
833       }
834       else
835       {
836         if ( algo->CheckHypothesis((*_father),_subShape , aux_ret ))
837           setAlgoState(HYP_OK);
838         else
839           setAlgoState(MISSING_HYP);
840       }
841       break;
842     }
843     default:
844       ASSERT(0);
845       break;
846     }
847     break;
848
849     // ----------------------------------------------------------------------
850
851   case HYP_OK:
852     switch (event)
853     {
854     case ADD_HYP: {
855       algo = GetAlgo();
856       ASSERT(algo);
857       if (!algo->CheckHypothesis((*_father),_subShape, ret ))
858       {
859         if ( !SMESH_Hypothesis::IsStatusFatal( ret ))
860           // ret should be fatal: anHyp was not added
861           ret = SMESH_Hypothesis::HYP_INCOMPATIBLE;
862       }
863       else if (!_father->IsUsedHypothesis(  anHyp, this ))
864         ret = SMESH_Hypothesis::HYP_INCOMPATIBLE;
865
866       if (SMESH_Hypothesis::IsStatusFatal( ret ))
867       {
868         MESSAGE("do not add extra hypothesis");
869         meshDS->RemoveHypothesis(_subShape, anHyp);
870       }
871       else
872       {
873         modifiedHyp = true;
874       }
875       break;
876     }
877     case ADD_ALGO: {           //already existing algo : on father ?
878       algo = GetAlgo();
879       if ( algo->CheckHypothesis((*_father),_subShape, aux_ret )) {
880         // check if algo changes
881         SMESH_HypoFilter f;
882         f.Init(   SMESH_HypoFilter::IsAlgo() );
883         f.And(    SMESH_HypoFilter::IsApplicableTo( _subShape ));
884         f.AndNot( SMESH_HypoFilter::Is( algo ));
885         const SMESH_Hypothesis * prevAlgo = _father->GetHypothesis( _subShape, f, true );
886         if (prevAlgo &&
887             string(algo->GetName()) != string(prevAlgo->GetName()) )
888           modifiedHyp = true;
889       }
890       else
891         setAlgoState(MISSING_HYP);
892       break;
893     }
894     case REMOVE_HYP: {
895       algo = GetAlgo();
896       ASSERT(algo);
897       if ( algo->CheckHypothesis((*_father),_subShape, aux_ret ))
898         setAlgoState(HYP_OK);
899       else
900         setAlgoState(MISSING_HYP);
901       modifiedHyp = true;
902       break;
903     }
904     case REMOVE_ALGO: {         // perhaps a father algo applies ?
905       algo = GetAlgo();
906       if (algo == NULL)   // no more algo applying on sub-shape...
907       {
908         setAlgoState(NO_ALGO);
909       }
910       else
911       {
912         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret )) {
913           // check if algo remains
914           if ( anHyp != algo && strcmp( anHyp->GetName(), algo->GetName()) )
915             modifiedHyp = true;
916         }
917         else
918           setAlgoState(MISSING_HYP);
919       }
920       break;
921     }
922     case MODIF_HYP: // hypothesis value may become bad
923     case ADD_FATHER_HYP: {  // new father hypothesis ?
924       algo = GetAlgo();
925       ASSERT(algo);
926       if ( algo->CheckHypothesis((*_father),_subShape, aux_ret ))
927       {
928         if (_father->IsUsedHypothesis( anHyp, this )) // new Hyp
929           modifiedHyp = true;
930       }
931       else
932         setAlgoState(MISSING_HYP);
933       break;
934     }
935     case ADD_FATHER_ALGO: {
936       algo = GetAlgo();
937       if ( algo == anHyp ) { // a new algo on father
938         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret )) {
939           // check if algo changes
940           SMESH_HypoFilter f;
941           f.Init(   SMESH_HypoFilter::IsAlgo() );
942           f.And(    SMESH_HypoFilter::IsApplicableTo( _subShape ));
943           f.AndNot( SMESH_HypoFilter::Is( algo ));
944           const SMESH_Hypothesis* prevAlgo = _father->GetHypothesis( _subShape, f, true );
945           if (prevAlgo &&
946               string(algo->GetName()) != string(prevAlgo->GetName()) )
947             modifiedHyp = true;
948         }
949         else
950           setAlgoState(MISSING_HYP);
951       }
952       break;
953     }
954     case REMOVE_FATHER_HYP: {
955       algo = GetAlgo();
956       ASSERT(algo);
957       if ( algo->CheckHypothesis((*_father),_subShape, aux_ret )) {
958         // is there the same local hyp or maybe a new father algo applied?
959         if ( !getSimilarAttached( _subShape, anHyp ) )
960           modifiedHyp = true;
961       }
962       else
963         setAlgoState(MISSING_HYP);
964       break;
965     }
966     case REMOVE_FATHER_ALGO: {
967       // IPAL21346. Edges not removed when Netgen 1d-2d is removed from a SOLID.
968       // CLEAN was not called at event REMOVE_ALGO because the algo is not applicable to SOLID.
969       algo = dynamic_cast<SMESH_Algo*> (anHyp);
970       if (!algo->NeedDiscreteBoundary())
971         needFullClean = true;
972
973       algo = GetAlgo();
974       if (algo == NULL)  // no more applying algo on father
975       {
976         setAlgoState(NO_ALGO);
977       }
978       else
979       {
980         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret )) {
981           // check if algo changes
982           if ( string(algo->GetName()) != string( anHyp->GetName()) )
983             modifiedHyp = true;
984         }
985         else
986           setAlgoState(MISSING_HYP);
987       }
988       break;
989     }
990     default:
991       ASSERT(0);
992       break;
993     }
994     break;
995
996     // ----------------------------------------------------------------------
997
998   default:
999     ASSERT(0);
1000     break;
1001   }
1002
1003   // detect algorithm hiding
1004   //
1005   if ( ret == SMESH_Hypothesis::HYP_OK &&
1006        ( event == ADD_ALGO || event == ADD_FATHER_ALGO ) &&
1007        algo->GetName() == anHyp->GetName() )
1008   {
1009     // is algo hidden?
1010     SMESH_Gen* gen = _father->GetGen();
1011     TopTools_ListIteratorOfListOfShape it( _father->GetAncestors( _subShape ));
1012     for ( ; ( ret == SMESH_Hypothesis::HYP_OK && it.More()); it.Next() ) {
1013       if ( SMESH_Algo* upperAlgo = gen->GetAlgo( *_father, it.Value() ))
1014         if ( !upperAlgo->NeedDiscreteBoundary() && !upperAlgo->SupportSubmeshes())
1015           ret = SMESH_Hypothesis::HYP_HIDDEN_ALGO;
1016     }
1017     // is algo hiding?
1018     if ( ret == SMESH_Hypothesis::HYP_OK &&
1019          !algo->NeedDiscreteBoundary()    &&
1020          !algo->SupportSubmeshes()) {
1021       TopoDS_Shape algoAssignedTo, otherAssignedTo;
1022       gen->GetAlgo( *_father, _subShape, &algoAssignedTo );
1023       map<int, SMESH_subMesh*>::reverse_iterator i_sm = _mapDepend.rbegin();
1024       for ( ; ( ret == SMESH_Hypothesis::HYP_OK && i_sm != _mapDepend.rend()) ; ++i_sm )
1025         if ( gen->GetAlgo( *_father, i_sm->second->_subShape, &otherAssignedTo ) &&
1026              SMESH_MesherHelper::IsSubShape( /*sub=*/otherAssignedTo, /*main=*/algoAssignedTo ))
1027           ret = SMESH_Hypothesis::HYP_HIDING_ALGO;
1028     }
1029   }
1030
1031   bool stateChange = ( _algoState != oldAlgoState );
1032
1033   if ( stateChange && _algoState == HYP_OK ) // hyp becomes OK
1034     algo->SetEventListener( this );
1035
1036   notifyListenersOnEvent( event, ALGO_EVENT, anHyp );
1037
1038   if ( stateChange && oldAlgoState == HYP_OK ) { // hyp becomes KO
1039     deleteOwnListeners();
1040     SetIsAlwaysComputed( false );
1041     if (_subShape.ShapeType() == TopAbs_VERTEX ) {
1042       // restore default states
1043       _algoState = HYP_OK;
1044       _computeState = READY_TO_COMPUTE;
1045     }
1046   }
1047
1048   if ( needFullClean ) {
1049     // added or removed algo is all-dimensional
1050     ComputeStateEngine( CLEAN );
1051     cleanDependsOn();
1052     ComputeSubMeshStateEngine( CHECK_COMPUTE_STATE );
1053   }
1054
1055   if (stateChange || modifiedHyp)
1056     ComputeStateEngine(MODIF_ALGO_STATE);
1057
1058   return ret;
1059 }
1060
1061 //=======================================================================
1062 //function : IsConform
1063 //purpose  : check if a conform mesh will be produced by the Algo
1064 //=======================================================================
1065
1066 bool SMESH_subMesh::IsConform(const SMESH_Algo* theAlgo)
1067 {
1068 //  MESSAGE( "SMESH_subMesh::IsConform" );
1069   if ( !theAlgo ) return false;
1070
1071   // Suppose that theAlgo is applicable to _subShape, do not check it here
1072   //if ( !IsApplicableHypotesis( theAlgo )) return false;
1073
1074   // check only algo that doesn't NeedDiscreteBoundary(): because mesh made
1075   // on a sub-shape will be ignored by theAlgo
1076   if ( theAlgo->NeedDiscreteBoundary() ||
1077        !theAlgo->OnlyUnaryInput() ) // all adjacent shapes will be meshed by this algo?
1078     return true;
1079
1080   SMESH_Gen* gen =_father->GetGen();
1081
1082   // only local algo is to be checked
1083   //if ( gen->IsGlobalHypothesis( theAlgo, *_father ))
1084   if ( _subShape.ShapeType() == _father->GetMeshDS()->ShapeToMesh().ShapeType() )
1085     return true;
1086
1087   // check algo attached to adjacent shapes
1088
1089   // loop on one level down sub-meshes
1090   TopoDS_Iterator itsub( _subShape );
1091   for (; itsub.More(); itsub.Next())
1092   {
1093     // loop on adjacent subShapes
1094     TopTools_ListIteratorOfListOfShape it( _father->GetAncestors( itsub.Value() ));
1095     for (; it.More(); it.Next())
1096     {
1097       const TopoDS_Shape& adjacent = it.Value();
1098       if ( _subShape.IsSame( adjacent )) continue;
1099       if ( adjacent.ShapeType() != _subShape.ShapeType())
1100         break;
1101
1102       // check algo attached to smAdjacent
1103       SMESH_Algo * algo = gen->GetAlgo((*_father), adjacent);
1104       if (algo &&
1105           !algo->NeedDiscreteBoundary() &&
1106           algo->OnlyUnaryInput())
1107         return false; // NOT CONFORM MESH WILL BE PRODUCED
1108     }
1109   }
1110
1111   return true;
1112 }
1113
1114 //=============================================================================
1115 /*!
1116  *
1117  */
1118 //=============================================================================
1119
1120 void SMESH_subMesh::setAlgoState(int state)
1121 {
1122   _algoState = state;
1123 }
1124
1125 //=============================================================================
1126 /*!
1127  *
1128  */
1129 //=============================================================================
1130 SMESH_Hypothesis::Hypothesis_Status
1131   SMESH_subMesh::SubMeshesAlgoStateEngine(int event,
1132                                           SMESH_Hypothesis * anHyp)
1133 {
1134   SMESH_Hypothesis::Hypothesis_Status ret = SMESH_Hypothesis::HYP_OK;
1135   //EAP: a wire (dim==1) should notify edges (dim==1)
1136   //EAP: int dim = SMESH_Gen::GetShapeDim(_subShape);
1137   //if (_subShape.ShapeType() < TopAbs_EDGE ) // wire,face etc
1138   {
1139     SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
1140     while ( smIt->more() ) {
1141       SMESH_Hypothesis::Hypothesis_Status ret2 =
1142         smIt->next()->AlgoStateEngine(event, anHyp);
1143       if ( ret2 > ret )
1144         ret = ret2;
1145     }
1146   }
1147   return ret;
1148 }
1149
1150 //=============================================================================
1151 /*!
1152  *
1153  */
1154 //=============================================================================
1155
1156 void SMESH_subMesh::cleanDependsOn()
1157 {
1158   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
1159   while ( smIt->more() )
1160     smIt->next()->ComputeStateEngine(CLEAN);
1161 }
1162
1163 //=============================================================================
1164 /*!
1165  *
1166  */
1167 //=============================================================================
1168
1169 void SMESH_subMesh::DumpAlgoState(bool isMain)
1170 {
1171         int dim = SMESH_Gen::GetShapeDim(_subShape);
1172 //   if (dim < 1) return;
1173         if (isMain)
1174         {
1175                 const map < int, SMESH_subMesh * >&subMeshes = DependsOn();
1176
1177                 map < int, SMESH_subMesh * >::const_iterator itsub;
1178                 for (itsub = subMeshes.begin(); itsub != subMeshes.end(); itsub++)
1179                 {
1180                         SMESH_subMesh *sm = (*itsub).second;
1181                         sm->DumpAlgoState(false);
1182                 }
1183         }
1184         int type = _subShape.ShapeType();
1185         MESSAGE("dim = " << dim << " type of shape " << type);
1186         switch (_algoState)
1187         {
1188         case NO_ALGO:
1189                 MESSAGE(" AlgoState = NO_ALGO");
1190                 break;
1191         case MISSING_HYP:
1192                 MESSAGE(" AlgoState = MISSING_HYP");
1193                 break;
1194         case HYP_OK:
1195                 MESSAGE(" AlgoState = HYP_OK");
1196                 break;
1197         }
1198         switch (_computeState)
1199         {
1200         case NOT_READY:
1201                 MESSAGE(" ComputeState = NOT_READY");
1202                 break;
1203         case READY_TO_COMPUTE:
1204                 MESSAGE(" ComputeState = READY_TO_COMPUTE");
1205                 break;
1206         case COMPUTE_OK:
1207                 MESSAGE(" ComputeState = COMPUTE_OK");
1208                 break;
1209         case FAILED_TO_COMPUTE:
1210                 MESSAGE(" ComputeState = FAILED_TO_COMPUTE");
1211                 break;
1212         }
1213 }
1214
1215 //================================================================================
1216 /*!
1217  * \brief Remove nodes and elements bound to submesh
1218   * \param subMesh - submesh containing nodes and elements
1219  */
1220 //================================================================================
1221
1222 static void cleanSubMesh( SMESH_subMesh * subMesh )
1223 {
1224   if (subMesh) {
1225     if (SMESHDS_SubMesh * subMeshDS = subMesh->GetSubMeshDS()) {
1226       SMESHDS_Mesh * meshDS = subMesh->GetFather()->GetMeshDS();
1227       SMDS_ElemIteratorPtr ite = subMeshDS->GetElements();
1228       while (ite->more()) {
1229         const SMDS_MeshElement * elt = ite->next();
1230         //MESSAGE( " RM elt: "<<elt->GetID()<<" ( "<<elt->NbNodes()<<" )" );
1231         //meshDS->RemoveElement(elt);
1232         meshDS->RemoveFreeElement(elt, subMeshDS);
1233       }
1234
1235       SMDS_NodeIteratorPtr itn = subMeshDS->GetNodes();
1236       while (itn->more()) {
1237         const SMDS_MeshNode * node = itn->next();
1238         //MESSAGE( " RM node: "<<node->GetID());
1239         if ( node->NbInverseElements() == 0 )
1240           meshDS->RemoveFreeNode(node, subMeshDS);
1241         else // for StdMeshers_CompositeSegment_1D: node in one submesh, edge in another
1242           meshDS->RemoveNode(node);
1243       }
1244     }
1245   }
1246 }
1247
1248 //=============================================================================
1249 /*!
1250  *
1251  */
1252 //=============================================================================
1253
1254 bool SMESH_subMesh::ComputeStateEngine(int event)
1255 {
1256   _computeError.reset();
1257
1258   //MESSAGE("SMESH_subMesh::ComputeStateEngine");
1259   //SCRUTE(_computeState);
1260   //SCRUTE(event);
1261
1262   if (_subShape.ShapeType() == TopAbs_VERTEX)
1263   {
1264     _computeState = READY_TO_COMPUTE;
1265     SMESHDS_SubMesh* smDS = GetSubMeshDS();
1266     if ( smDS && smDS->NbNodes() ) {
1267       if ( event == CLEAN ) {
1268         cleanDependants();
1269         cleanSubMesh( this );
1270       }
1271       else
1272         _computeState = COMPUTE_OK;
1273     }
1274     else if ( event == COMPUTE && !_alwaysComputed ) {
1275       const TopoDS_Vertex & V = TopoDS::Vertex( _subShape );
1276       gp_Pnt P = BRep_Tool::Pnt(V);
1277       if ( SMDS_MeshNode * n = _father->GetMeshDS()->AddNode(P.X(), P.Y(), P.Z()) ) {
1278         _father->GetMeshDS()->SetNodeOnVertex(n,_Id);
1279         _computeState = COMPUTE_OK;
1280       }
1281     }
1282     if ( event == MODIF_ALGO_STATE )
1283       cleanDependants();
1284     return true;
1285   }
1286   SMESH_Gen *gen = _father->GetGen();
1287   SMESH_Algo *algo = 0;
1288   bool ret = true;
1289   SMESH_Hypothesis::Hypothesis_Status hyp_status;
1290   //algo_state oldAlgoState = (algo_state) GetAlgoState();
1291
1292   switch (_computeState)
1293   {
1294
1295     // ----------------------------------------------------------------------
1296
1297   case NOT_READY:
1298     switch (event)
1299     {
1300     case MODIF_ALGO_STATE:
1301       algo = GetAlgo();
1302       if (algo && !algo->NeedDiscreteBoundary())
1303         cleanDependsOn(); // clean sub-meshes with event CLEAN
1304       if ( _algoState == HYP_OK )
1305         _computeState = READY_TO_COMPUTE;
1306       break;
1307     case COMPUTE:               // nothing to do
1308       break;
1309 #ifdef WITH_SMESH_CANCEL_COMPUTE
1310     case COMPUTE_CANCELED:               // nothing to do
1311       break;
1312 #endif
1313     case CLEAN:
1314       cleanDependants();
1315       removeSubMeshElementsAndNodes();
1316       break;
1317     case SUBMESH_COMPUTED:      // nothing to do
1318       break;
1319     case SUBMESH_RESTORED:
1320       ComputeSubMeshStateEngine( SUBMESH_RESTORED );
1321       break;
1322     case MESH_ENTITY_REMOVED:
1323       break;
1324     case SUBMESH_LOADED:
1325       loadDependentMeshes();
1326       ComputeSubMeshStateEngine( SUBMESH_LOADED );
1327       //break;
1328     case CHECK_COMPUTE_STATE:
1329       if ( IsMeshComputed() )
1330         _computeState = COMPUTE_OK;
1331       break;
1332     default:
1333       ASSERT(0);
1334       break;
1335     }
1336     break;
1337
1338     // ----------------------------------------------------------------------
1339
1340   case READY_TO_COMPUTE:
1341     switch (event)
1342     {
1343     case MODIF_ALGO_STATE:
1344       _computeState = NOT_READY;
1345       algo = GetAlgo();
1346       if (algo)
1347       {
1348         if (!algo->NeedDiscreteBoundary())
1349           cleanDependsOn(); // clean sub-meshes with event CLEAN
1350         if ( _algoState == HYP_OK )
1351           _computeState = READY_TO_COMPUTE;
1352       }
1353       break;
1354     case COMPUTE:
1355       {
1356         algo = GetAlgo();
1357         ASSERT(algo);
1358         ret = algo->CheckHypothesis((*_father), _subShape, hyp_status);
1359         if (!ret)
1360         {
1361           MESSAGE("***** verify compute state *****");
1362           _computeState = NOT_READY;
1363           setAlgoState(MISSING_HYP);
1364           break;
1365         }
1366         TopoDS_Shape shape = _subShape;
1367         // check submeshes needed
1368         if (_father->HasShapeToMesh() ) {
1369           bool subComputed = false;
1370           if (!algo->OnlyUnaryInput())
1371             shape = getCollection( gen, algo, subComputed );
1372           else
1373             subComputed = subMeshesComputed();
1374           ret = ( algo->NeedDiscreteBoundary() ? subComputed :
1375                   algo->SupportSubmeshes() ? true :
1376                   ( !subComputed || _father->IsNotConformAllowed() ));
1377           if (!ret) {
1378             _computeState = FAILED_TO_COMPUTE;
1379             if ( !algo->NeedDiscreteBoundary() )
1380               _computeError =
1381                 SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
1382                                         "Unexpected computed submesh",algo);
1383             break;
1384           }
1385         }
1386         // Compute
1387
1388         //cleanDependants(); for "UseExisting_*D" algos
1389         //removeSubMeshElementsAndNodes();
1390         loadDependentMeshes();
1391         ret = false;
1392         _computeState = FAILED_TO_COMPUTE;
1393         _computeError = SMESH_ComputeError::New(COMPERR_OK,"",algo);
1394         try {
1395 #if OCC_VERSION_LARGE > 0x06010000
1396           OCC_CATCH_SIGNALS;
1397 #endif
1398           algo->InitComputeError();
1399           MemoryReserve aMemoryReserve;
1400           SMDS_Mesh::CheckMemory();
1401           Kernel_Utils::Localizer loc;
1402           if ( !_father->HasShapeToMesh() ) // no shape
1403           {
1404             SMESH_MesherHelper helper( *_father );
1405             helper.SetSubShape( shape );
1406             helper.SetElementsOnShape( true );
1407             ret = algo->Compute(*_father, &helper );
1408           }
1409           else
1410           {
1411             ret = algo->Compute((*_father), shape);
1412           }
1413           if ( !_computeError || ( !ret && _computeError->IsOK() ) ) // algo can set _computeError of submesh
1414             _computeError = algo->GetComputeError();
1415         }
1416         catch ( ::SMESH_ComputeError& comperr ) {
1417           cout << " SMESH_ComputeError caught" << endl;
1418           if ( !_computeError ) _computeError = SMESH_ComputeError::New();
1419           *_computeError = comperr;
1420         }
1421         catch ( std::bad_alloc& exc ) {
1422           MESSAGE("std::bad_alloc thrown inside algo->Compute()");
1423           if ( _computeError ) {
1424             _computeError->myName = COMPERR_MEMORY_PB;
1425             //_computeError->myComment = exc.what();
1426           }
1427           cleanSubMesh( this );
1428           throw exc;
1429         }
1430         catch ( Standard_OutOfMemory& exc ) {
1431           MESSAGE("Standard_OutOfMemory thrown inside algo->Compute()");
1432           if ( _computeError ) {
1433             _computeError->myName = COMPERR_MEMORY_PB;
1434             //_computeError->myComment = exc.what();
1435           }
1436           cleanSubMesh( this );
1437           throw std::bad_alloc();
1438         }
1439         catch (Standard_Failure& ex) {
1440           if ( !_computeError ) _computeError = SMESH_ComputeError::New();
1441           _computeError->myName    = COMPERR_OCC_EXCEPTION;
1442           _computeError->myComment += ex.DynamicType()->Name();
1443           if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
1444             _computeError->myComment += ": ";
1445             _computeError->myComment += ex.GetMessageString();
1446           }
1447         }
1448         catch ( SALOME_Exception& S_ex ) {
1449           if ( !_computeError ) _computeError = SMESH_ComputeError::New();
1450           _computeError->myName    = COMPERR_SLM_EXCEPTION;
1451           _computeError->myComment = S_ex.what();
1452         }
1453         catch ( std::exception& exc ) {
1454           if ( !_computeError ) _computeError = SMESH_ComputeError::New();
1455           _computeError->myName    = COMPERR_STD_EXCEPTION;
1456           _computeError->myComment = exc.what();
1457         }
1458         catch ( ... ) {
1459           if ( _computeError )
1460             _computeError->myName = COMPERR_EXCEPTION;
1461           else
1462             ret = false;
1463         }
1464         TopExp_Explorer subS(shape, _subShape.ShapeType());
1465         if (ret) // check if anything was built
1466         {
1467           for (; ret && subS.More(); subS.Next())
1468             ret = _father->GetSubMesh( subS.Current() )->IsMeshComputed();
1469         }
1470         bool isComputeErrorSet = !checkComputeError( algo, shape );
1471         if (!ret && !isComputeErrorSet)
1472         {
1473           // Set _computeError
1474           for (subS.ReInit(); subS.More(); subS.Next())
1475           {
1476             SMESH_subMesh* sm = _father->GetSubMesh( subS.Current() );
1477             if ( !sm->IsMeshComputed() )
1478             {
1479               if ( !sm->_computeError )
1480                 sm->_computeError = SMESH_ComputeError::New();
1481               if ( sm->_computeError->IsOK() )
1482                 sm->_computeError->myName = COMPERR_ALGO_FAILED;
1483               sm->_computeState = FAILED_TO_COMPUTE;
1484               sm->_computeError->myAlgo = algo;
1485             }
1486           }
1487         }
1488         if (ret && _computeError && _computeError->myName != COMPERR_WARNING )
1489         {
1490           _computeError.reset();
1491         }
1492         updateDependantsState( SUBMESH_COMPUTED ); // send event SUBMESH_COMPUTED
1493       }
1494       break;
1495 #ifdef WITH_SMESH_CANCEL_COMPUTE
1496     case COMPUTE_CANCELED:               // nothing to do
1497       break;
1498 #endif
1499     case CLEAN:
1500       cleanDependants();
1501       removeSubMeshElementsAndNodes();
1502       _computeState = NOT_READY;
1503       algo = GetAlgo();
1504       if (algo)
1505       {
1506         ret = algo->CheckHypothesis((*_father), _subShape, hyp_status);
1507         if (ret)
1508           _computeState = READY_TO_COMPUTE;
1509         else
1510           setAlgoState(MISSING_HYP);
1511       }
1512       break;
1513     case SUBMESH_COMPUTED:      // nothing to do
1514       break;
1515     case SUBMESH_RESTORED:
1516       // check if a mesh is already computed that may
1517       // happen after retrieval from a file
1518       ComputeStateEngine( CHECK_COMPUTE_STATE );
1519       ComputeSubMeshStateEngine( SUBMESH_RESTORED );
1520       algo = GetAlgo();
1521       if (algo) algo->SubmeshRestored( this );
1522       break;
1523     case MESH_ENTITY_REMOVED:
1524       break;
1525     case SUBMESH_LOADED:
1526       loadDependentMeshes();
1527       ComputeSubMeshStateEngine( SUBMESH_LOADED );
1528       //break;
1529     case CHECK_COMPUTE_STATE:
1530       if ( IsMeshComputed() )
1531         _computeState = COMPUTE_OK;
1532       break;
1533     default:
1534       ASSERT(0);
1535       break;
1536     }
1537     break;
1538
1539     // ----------------------------------------------------------------------
1540
1541   case COMPUTE_OK:
1542     switch (event)
1543     {
1544     case MODIF_ALGO_STATE:
1545       ComputeStateEngine( CLEAN );
1546       algo = GetAlgo();
1547       if (algo && !algo->NeedDiscreteBoundary())
1548         cleanDependsOn(); // clean sub-meshes with event CLEAN
1549       break;
1550     case COMPUTE:               // nothing to do
1551       break;
1552 #ifdef WITH_SMESH_CANCEL_COMPUTE
1553     case COMPUTE_CANCELED:               // nothing to do
1554       break;
1555 #endif
1556     case CLEAN:
1557       cleanDependants();  // clean sub-meshes, dependant on this one, with event CLEAN
1558       removeSubMeshElementsAndNodes();
1559       _computeState = NOT_READY;
1560       if ( _algoState == HYP_OK )
1561         _computeState = READY_TO_COMPUTE;
1562       break;
1563     case SUBMESH_COMPUTED:      // nothing to do
1564       break;
1565     case SUBMESH_RESTORED:
1566       ComputeStateEngine( CHECK_COMPUTE_STATE );
1567       ComputeSubMeshStateEngine( SUBMESH_RESTORED );
1568       algo = GetAlgo();
1569       if (algo) algo->SubmeshRestored( this );
1570       break;
1571     case MESH_ENTITY_REMOVED:
1572       updateDependantsState    ( CHECK_COMPUTE_STATE );
1573       ComputeStateEngine       ( CHECK_COMPUTE_STATE );
1574       ComputeSubMeshStateEngine( CHECK_COMPUTE_STATE );
1575       break;
1576     case CHECK_COMPUTE_STATE:
1577       if ( !IsMeshComputed() ) {
1578         if (_algoState == HYP_OK)
1579           _computeState = READY_TO_COMPUTE;
1580         else
1581           _computeState = NOT_READY;
1582       }
1583       break;
1584     case SUBMESH_LOADED:
1585       // already treated event, thanks to which _computeState == COMPUTE_OK
1586       break;
1587     default:
1588       ASSERT(0);
1589       break;
1590     }
1591     break;
1592
1593     // ----------------------------------------------------------------------
1594
1595   case FAILED_TO_COMPUTE:
1596     switch (event)
1597     {
1598     case MODIF_ALGO_STATE:
1599       if ( !IsEmpty() )
1600         ComputeStateEngine( CLEAN );
1601       algo = GetAlgo();
1602       if (algo && !algo->NeedDiscreteBoundary())
1603         cleanDependsOn(); // clean sub-meshes with event CLEAN
1604       if (_algoState == HYP_OK)
1605         _computeState = READY_TO_COMPUTE;
1606       else
1607         _computeState = NOT_READY;
1608       break;
1609     case COMPUTE:      // nothing to do
1610       break;
1611 #ifdef WITH_SMESH_CANCEL_COMPUTE
1612     case COMPUTE_CANCELED:
1613       {
1614         algo = GetAlgo();
1615         algo->CancelCompute();
1616       }
1617       break;
1618 #endif
1619     case CLEAN:
1620       cleanDependants(); // submeshes dependent on me should be cleaned as well
1621       removeSubMeshElementsAndNodes();
1622       break;
1623     case SUBMESH_COMPUTED:      // allow retry compute
1624       if (_algoState == HYP_OK)
1625         _computeState = READY_TO_COMPUTE;
1626       else
1627         _computeState = NOT_READY;
1628       break;
1629     case SUBMESH_RESTORED:
1630       ComputeSubMeshStateEngine( SUBMESH_RESTORED );
1631       break;
1632     case MESH_ENTITY_REMOVED:
1633       break;
1634     case CHECK_COMPUTE_STATE:
1635       if ( IsMeshComputed() )
1636         _computeState = COMPUTE_OK;
1637       else
1638         if (_algoState == HYP_OK)
1639           _computeState = READY_TO_COMPUTE;
1640         else
1641           _computeState = NOT_READY;
1642       break;
1643     // case SUBMESH_LOADED:
1644     //   break;
1645     default:
1646       ASSERT(0);
1647       break;
1648     }
1649     break;
1650
1651     // ----------------------------------------------------------------------
1652   default:
1653     ASSERT(0);
1654     break;
1655   }
1656
1657   notifyListenersOnEvent( event, COMPUTE_EVENT );
1658
1659   return ret;
1660 }
1661
1662
1663 //=============================================================================
1664 /*!
1665  *
1666  */
1667 //=============================================================================
1668
1669 bool SMESH_subMesh::Evaluate(MapShapeNbElems& aResMap)
1670 {
1671   _computeError.reset();
1672
1673   bool ret = true;
1674
1675   if (_subShape.ShapeType() == TopAbs_VERTEX) {
1676     vector<int> aVec(SMDSEntity_Last,0);
1677     aVec[SMDSEntity_Node] = 1;
1678     aResMap.insert(make_pair(this,aVec));
1679     return ret;
1680   }
1681
1682   //SMESH_Gen *gen = _father->GetGen();
1683   SMESH_Algo *algo = 0;
1684   SMESH_Hypothesis::Hypothesis_Status hyp_status;
1685
1686   algo = GetAlgo();
1687   if(algo && !aResMap.count(this) )
1688   {
1689     ret = algo->CheckHypothesis((*_father), _subShape, hyp_status);
1690     if (!ret) return false;
1691
1692     if (_father->HasShapeToMesh() && algo->NeedDiscreteBoundary())
1693     {
1694       // check submeshes needed
1695       bool subMeshEvaluated = true;
1696       int dimToCheck = SMESH_Gen::GetShapeDim( _subShape ) - 1;
1697       SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,/*complexShapeFirst=*/true);
1698       while ( smIt->more() && subMeshEvaluated )
1699       {
1700         SMESH_subMesh* sm = smIt->next();
1701         int dim = SMESH_Gen::GetShapeDim( sm->GetSubShape() );
1702         if (dim < dimToCheck) break; // the rest subMeshes are all of less dimension
1703         const vector<int> & nbs = aResMap[ sm ];
1704         subMeshEvaluated = (std::accumulate( nbs.begin(), nbs.end(), 0 ) > 0 );
1705       }
1706       if ( !subMeshEvaluated )
1707         return false;
1708     }
1709     _computeError = SMESH_ComputeError::New(COMPERR_OK,"",algo);
1710     ret = algo->Evaluate((*_father), _subShape, aResMap);
1711
1712     aResMap.insert( make_pair( this,vector<int>(0)));
1713   }
1714
1715   return ret;
1716 }
1717
1718
1719 //=======================================================================
1720 /*!
1721  * \brief Update compute_state by _computeError and send proper events to
1722  * dependent submeshes
1723   * \retval bool - true if _computeError is NOT set
1724  */
1725 //=======================================================================
1726
1727 bool SMESH_subMesh::checkComputeError(SMESH_Algo* theAlgo, const TopoDS_Shape& theShape)
1728 {
1729   bool noErrors = true;
1730
1731   if ( !theShape.IsNull() )
1732   {
1733     // Check state of submeshes
1734     if ( !theAlgo->NeedDiscreteBoundary())
1735     {
1736       SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
1737       while ( smIt->more() )
1738         if ( !smIt->next()->checkComputeError( theAlgo ))
1739           noErrors = false;
1740     }
1741
1742     // Check state of neighbours
1743     if ( !theAlgo->OnlyUnaryInput() &&
1744          theShape.ShapeType() == TopAbs_COMPOUND &&
1745          !theShape.IsSame( _subShape ))
1746     {
1747       for (TopoDS_Iterator subIt( theShape ); subIt.More(); subIt.Next()) {
1748         SMESH_subMesh* sm = _father->GetSubMesh( subIt.Value() );
1749         if ( sm != this ) {
1750           if ( !sm->checkComputeError( theAlgo, sm->GetSubShape() ))
1751             noErrors = false;
1752           updateDependantsState( SUBMESH_COMPUTED ); // send event SUBMESH_COMPUTED
1753         }
1754       }
1755     }
1756   }
1757   {
1758     // Check my state
1759     if ( !_computeError || _computeError->IsOK() )
1760     {
1761       // no error description is set to this sub-mesh, check if any mesh is computed
1762       _computeState = IsMeshComputed() ? COMPUTE_OK : FAILED_TO_COMPUTE;
1763     }
1764     else
1765     {
1766       if ( !_computeError->myAlgo )
1767         _computeError->myAlgo = theAlgo;
1768
1769       // Show error
1770       SMESH_Comment text;
1771       text << theAlgo->GetName() << " failed on sub-shape #" << _Id << " with error ";
1772       if (_computeError->IsCommon() )
1773         text << _computeError->CommonName();
1774       else
1775         text << _computeError->myName;
1776       if ( _computeError->myComment.size() > 0 )
1777         text << " \"" << _computeError->myComment << "\"";
1778
1779       INFOS( text );
1780
1781       _computeState = _computeError->IsKO() ? FAILED_TO_COMPUTE : COMPUTE_OK;
1782
1783       noErrors = false;
1784     }
1785   }
1786   return noErrors;
1787 }
1788
1789 //=======================================================================
1790 //function : updateSubMeshState
1791 //purpose  :
1792 //=======================================================================
1793
1794 void SMESH_subMesh::updateSubMeshState(const compute_state theState)
1795 {
1796   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
1797   while ( smIt->more() )
1798     smIt->next()->_computeState = theState;
1799 }
1800
1801 //=======================================================================
1802 //function : ComputeSubMeshStateEngine
1803 //purpose  :
1804 //=======================================================================
1805
1806 void SMESH_subMesh::ComputeSubMeshStateEngine(int event)
1807 {
1808   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
1809   while ( smIt->more() )
1810     smIt->next()->ComputeStateEngine(event);
1811 }
1812
1813 //=======================================================================
1814 //function : updateDependantsState
1815 //purpose  :
1816 //=======================================================================
1817
1818 void SMESH_subMesh::updateDependantsState(const compute_event theEvent)
1819 {
1820   TopTools_ListIteratorOfListOfShape it( _father->GetAncestors( _subShape ));
1821   for (; it.More(); it.Next())
1822   {
1823     const TopoDS_Shape& ancestor = it.Value();
1824     SMESH_subMesh *aSubMesh =
1825       _father->GetSubMeshContaining(ancestor);
1826     if (aSubMesh)
1827       aSubMesh->ComputeStateEngine( theEvent );
1828   }
1829 }
1830
1831 //=============================================================================
1832 /*!
1833  *
1834  */
1835 //=============================================================================
1836
1837 void SMESH_subMesh::cleanDependants()
1838 {
1839   int dimToClean = SMESH_Gen::GetShapeDim( _subShape ) + 1;
1840
1841   TopTools_ListIteratorOfListOfShape it( _father->GetAncestors( _subShape ));
1842   for (; it.More(); it.Next())
1843   {
1844     const TopoDS_Shape& ancestor = it.Value();
1845     if ( SMESH_Gen::GetShapeDim( ancestor ) == dimToClean ) {
1846       // PAL8021. do not go upper than SOLID, else ComputeStateEngine(CLEAN)
1847       // will erase mesh on other shapes in a compound
1848       if ( ancestor.ShapeType() >= TopAbs_SOLID ) {
1849         SMESH_subMesh *aSubMesh = _father->GetSubMeshContaining(ancestor);
1850         if (aSubMesh &&
1851             !aSubMesh->IsEmpty() ) // prevent infinite CLEAN via event lesteners
1852           aSubMesh->ComputeStateEngine(CLEAN);
1853       }
1854     }
1855   }
1856 }
1857
1858 //=============================================================================
1859 /*!
1860  *
1861  */
1862 //=============================================================================
1863
1864 void SMESH_subMesh::removeSubMeshElementsAndNodes()
1865 {
1866   cleanSubMesh( this );
1867
1868   // algo may bind a submesh not to _subShape, eg 3D algo
1869   // sets nodes on SHELL while _subShape may be SOLID
1870
1871   int dim = SMESH_Gen::GetShapeDim( _subShape );
1872   int type = _subShape.ShapeType() + 1;
1873   for ( ; type <= TopAbs_EDGE; type++) {
1874     if ( dim == SMESH_Gen::GetShapeDim( (TopAbs_ShapeEnum) type ))
1875     {
1876       TopExp_Explorer exp( _subShape, (TopAbs_ShapeEnum) type );
1877       for ( ; exp.More(); exp.Next() )
1878         cleanSubMesh( _father->GetSubMeshContaining( exp.Current() ));
1879     }
1880     else
1881       break;
1882   }
1883 }
1884
1885 //=======================================================================
1886 //function : getCollection
1887 //purpose  : return a shape containing all sub-shapes of the MainShape that can be
1888 //           meshed at once along with _subShape
1889 //=======================================================================
1890
1891 TopoDS_Shape SMESH_subMesh::getCollection(SMESH_Gen * theGen,
1892                                           SMESH_Algo* theAlgo,
1893                                           bool &      theSubComputed)
1894 {
1895   theSubComputed = subMeshesComputed();
1896
1897   TopoDS_Shape mainShape = _father->GetMeshDS()->ShapeToMesh();
1898
1899   if ( mainShape.IsSame( _subShape ))
1900     return _subShape;
1901
1902   const bool ignoreAuxiliaryHyps = false;
1903   list<const SMESHDS_Hypothesis*> aUsedHyp =
1904     theAlgo->GetUsedHypothesis( *_father, _subShape, ignoreAuxiliaryHyps ); // copy
1905
1906   // put in a compound all shapes with the same hypothesis assigned
1907   // and a good ComputState
1908
1909   TopoDS_Compound aCompound;
1910   BRep_Builder aBuilder;
1911   aBuilder.MakeCompound( aCompound );
1912
1913   TopExp_Explorer anExplorer( mainShape, _subShape.ShapeType() );
1914   for ( ; anExplorer.More(); anExplorer.Next() )
1915   {
1916     const TopoDS_Shape& S = anExplorer.Current();
1917     SMESH_subMesh* subMesh = _father->GetSubMesh( S );
1918     if ( subMesh == this )
1919     {
1920       aBuilder.Add( aCompound, S );
1921     }
1922     else if ( subMesh->GetComputeState() == READY_TO_COMPUTE )
1923     {
1924       SMESH_Algo* anAlgo = theGen->GetAlgo( *_father, S );
1925       if (strcmp( anAlgo->GetName(), theAlgo->GetName()) == 0 && // same algo
1926           anAlgo->GetUsedHypothesis( *_father, S, ignoreAuxiliaryHyps ) == aUsedHyp) // same hyps
1927         aBuilder.Add( aCompound, S );
1928       if ( !subMesh->subMeshesComputed() )
1929         theSubComputed = false;
1930     }
1931   }
1932
1933   return aCompound;
1934 }
1935
1936 //=======================================================================
1937 //function : getSimilarAttached
1938 //purpose  : return a hypothesis attached to theShape.
1939 //           If theHyp is provided, similar but not same hypotheses
1940 //           is returned; else only applicable ones having theHypType
1941 //           is returned
1942 //=======================================================================
1943
1944 const SMESH_Hypothesis* SMESH_subMesh::getSimilarAttached(const TopoDS_Shape&      theShape,
1945                                                           const SMESH_Hypothesis * theHyp,
1946                                                           const int                theHypType)
1947 {
1948   SMESH_HypoFilter hypoKind;
1949   hypoKind.Init( hypoKind.HasType( theHyp ? theHyp->GetType() : theHypType ));
1950   if ( theHyp ) {
1951     hypoKind.And   ( hypoKind.HasDim( theHyp->GetDim() ));
1952     hypoKind.AndNot( hypoKind.Is( theHyp ));
1953     if ( theHyp->IsAuxiliary() )
1954       hypoKind.And( hypoKind.HasName( theHyp->GetName() ));
1955     else
1956       hypoKind.AndNot( hypoKind.IsAuxiliary());
1957   }
1958   else {
1959     hypoKind.And( hypoKind.IsApplicableTo( theShape ));
1960   }
1961
1962   return _father->GetHypothesis( theShape, hypoKind, false );
1963 }
1964
1965 //=======================================================================
1966 //function : CheckConcurentHypothesis
1967 //purpose  : check if there are several applicable hypothesis attached to
1968 //           ancestors
1969 //=======================================================================
1970
1971 SMESH_Hypothesis::Hypothesis_Status
1972   SMESH_subMesh::CheckConcurentHypothesis (const int theHypType)
1973 {
1974   MESSAGE ("SMESH_subMesh::CheckConcurentHypothesis");
1975
1976   // is there local hypothesis on me?
1977   if ( getSimilarAttached( _subShape, 0, theHypType ) )
1978     return SMESH_Hypothesis::HYP_OK;
1979
1980
1981   TopoDS_Shape aPrevWithHyp;
1982   const SMESH_Hypothesis* aPrevHyp = 0;
1983   TopTools_ListIteratorOfListOfShape it( _father->GetAncestors( _subShape ));
1984   for (; it.More(); it.Next())
1985   {
1986     const TopoDS_Shape& ancestor = it.Value();
1987     const SMESH_Hypothesis* hyp = getSimilarAttached( ancestor, 0, theHypType );
1988     if ( hyp )
1989     {
1990       if ( aPrevWithHyp.IsNull() || aPrevWithHyp.IsSame( ancestor ))
1991       {
1992         aPrevWithHyp = ancestor;
1993         aPrevHyp     = hyp;
1994       }
1995       else if ( aPrevWithHyp.ShapeType() == ancestor.ShapeType() && aPrevHyp != hyp )
1996         return SMESH_Hypothesis::HYP_CONCURENT;
1997       else
1998         return SMESH_Hypothesis::HYP_OK;
1999     }
2000   }
2001   return SMESH_Hypothesis::HYP_OK;
2002 }
2003
2004 //================================================================================
2005 /*!
2006  * \brief Constructor of OwnListenerData
2007  */
2008 //================================================================================
2009
2010 SMESH_subMesh::OwnListenerData::OwnListenerData( SMESH_subMesh* sm, EventListener* el):
2011   mySubMesh( sm ),
2012   myMeshID( sm ? sm->GetFather()->GetId() : -1 ),
2013   mySubMeshID( sm ? sm->GetId() : -1 ),
2014   myListener( el )
2015 {
2016 }
2017
2018 //================================================================================
2019 /*!
2020  * \brief Sets an event listener and its data to a submesh
2021  * \param listener - the listener to store
2022  * \param data - the listener data to store
2023  * \param where - the submesh to store the listener and it's data
2024  * 
2025  * It remembers the submesh where it puts the listener in order to delete
2026  * them when HYP_OK algo_state is lost
2027  * After being set, event listener is notified on each event of where submesh.
2028  */
2029 //================================================================================
2030
2031 void SMESH_subMesh::SetEventListener(EventListener*     listener,
2032                                      EventListenerData* data,
2033                                      SMESH_subMesh*     where)
2034 {
2035   if ( listener && where ) {
2036     where->setEventListener( listener, data );
2037     _ownListeners.push_back( OwnListenerData( where, listener ));
2038   }
2039 }
2040
2041 //================================================================================
2042 /*!
2043  * \brief Sets an event listener and its data to a submesh
2044  * \param listener - the listener to store
2045  * \param data - the listener data to store
2046  * 
2047  * After being set, event listener is notified on each event of a submesh.
2048  */
2049 //================================================================================
2050
2051 void SMESH_subMesh::setEventListener(EventListener* listener, EventListenerData* data)
2052 {
2053   map< EventListener*, EventListenerData* >::iterator l_d =
2054     _eventListeners.find( listener );
2055   if ( l_d != _eventListeners.end() ) {
2056     EventListenerData* curData = l_d->second;
2057     if ( curData && curData != data && curData->IsDeletable() )
2058       delete curData;
2059     l_d->second = data;
2060   }
2061   else 
2062     _eventListeners.insert( make_pair( listener, data ));
2063 }
2064
2065 //================================================================================
2066 /*!
2067  * \brief Return an event listener data
2068  * \param listener - the listener whose data is
2069  * \retval EventListenerData* - found data, maybe NULL
2070  */
2071 //================================================================================
2072
2073 EventListenerData* SMESH_subMesh::GetEventListenerData(EventListener* listener) const
2074 {
2075   map< EventListener*, EventListenerData* >::const_iterator l_d =
2076     _eventListeners.find( listener );
2077   if ( l_d != _eventListeners.end() )
2078     return l_d->second;
2079   return 0;
2080 }
2081
2082 //================================================================================
2083 /*!
2084  * \brief Notify stored event listeners on the occured event
2085  * \param event - algo_event or compute_event itself
2086  * \param eventType - algo_event or compute_event
2087  * \param hyp - hypothesis, if eventType is algo_event
2088  */
2089 //================================================================================
2090
2091 void SMESH_subMesh::notifyListenersOnEvent( const int         event,
2092                                             const event_type  eventType,
2093                                             SMESH_Hypothesis* hyp)
2094 {
2095   map< EventListener*, EventListenerData* >::iterator l_d = _eventListeners.begin();
2096   for ( ; l_d != _eventListeners.end(); ++l_d )
2097   {
2098     std::pair< EventListener*, EventListenerData* > li_da = *l_d; /* copy to enable removal
2099                                                                      of a listener from
2100                                                                      _eventListeners by
2101                                                                      its ProcessEvent() */
2102     if ( li_da.first->myBusySM.insert( this ).second )
2103     {
2104       li_da.first->ProcessEvent( event, eventType, this, li_da.second, hyp );
2105       li_da.first->myBusySM.erase( this );
2106     }
2107   }
2108 }
2109
2110 //================================================================================
2111 /*!
2112  * \brief Unregister the listener and delete listener's data
2113  * \param listener - the event listener
2114  */
2115 //================================================================================
2116
2117 void SMESH_subMesh::DeleteEventListener(EventListener* listener)
2118 {
2119   map< EventListener*, EventListenerData* >::iterator l_d =
2120     _eventListeners.find( listener );
2121   if ( l_d != _eventListeners.end() ) {
2122     if ( l_d->first  && l_d->first->IsDeletable() )  delete l_d->first;
2123     if ( l_d->second && l_d->second->IsDeletable() ) delete l_d->second;
2124     _eventListeners.erase( l_d );
2125   }
2126 }
2127
2128 //================================================================================
2129 /*!
2130  * \brief Delete event listeners depending on algo of this submesh
2131  */
2132 //================================================================================
2133
2134 void SMESH_subMesh::deleteOwnListeners()
2135 {
2136   list< OwnListenerData >::iterator d;
2137   for ( d = _ownListeners.begin(); d != _ownListeners.end(); ++d )
2138   {
2139     if ( !_father->MeshExists( d->myMeshID ))
2140       continue;
2141     if ( _father->GetId() == d->myMeshID && !_father->GetSubMeshContaining( d->mySubMeshID ))
2142       continue;
2143     d->mySubMesh->DeleteEventListener( d->myListener );
2144   }
2145   _ownListeners.clear();
2146 }
2147
2148 //=======================================================================
2149 //function : loadDependentMeshes
2150 //purpose  : loads dependent meshes on SUBMESH_LOADED event
2151 //=======================================================================
2152
2153 void SMESH_subMesh::loadDependentMeshes()
2154 {
2155   list< OwnListenerData >::iterator d;
2156   for ( d = _ownListeners.begin(); d != _ownListeners.end(); ++d )
2157     if ( _father != d->mySubMesh->_father )
2158       d->mySubMesh->_father->Load();
2159
2160   // map< EventListener*, EventListenerData* >::iterator l_d = _eventListeners.begin();
2161   // for ( ; l_d != _eventListeners.end(); ++l_d )
2162   //   if ( l_d->second )
2163   //   {
2164   //     const list<SMESH_subMesh*>& smList = l_d->second->mySubMeshes;
2165   //     list<SMESH_subMesh*>::const_iterator sm = smList.begin();
2166   //     for ( ; sm != smList.end(); ++sm )
2167   //       if ( _father != (*sm)->_father )
2168   //         (*sm)->_father->Load();
2169   //   }
2170 }
2171
2172 //================================================================================
2173 /*!
2174  * \brief Do something on a certain event
2175  * \param event - algo_event or compute_event itself
2176  * \param eventType - algo_event or compute_event
2177  * \param subMesh - the submesh where the event occures
2178  * \param data - listener data stored in the subMesh
2179  * \param hyp - hypothesis, if eventType is algo_event
2180  * 
2181  * The base implementation translates CLEAN event to the subMesh
2182  * stored in listener data. Also it sends SUBMESH_COMPUTED event in case of
2183  * successful COMPUTE event.
2184  */
2185 //================================================================================
2186
2187 void SMESH_subMeshEventListener::ProcessEvent(const int          event,
2188                                               const int          eventType,
2189                                               SMESH_subMesh*     subMesh,
2190                                               EventListenerData* data,
2191                                               const SMESH_Hypothesis*  /*hyp*/)
2192 {
2193   if ( data && !data->mySubMeshes.empty() &&
2194        eventType == SMESH_subMesh::COMPUTE_EVENT)
2195   {
2196     ASSERT( data->mySubMeshes.front() != subMesh );
2197     list<SMESH_subMesh*>::iterator smIt = data->mySubMeshes.begin();
2198     list<SMESH_subMesh*>::iterator smEnd = data->mySubMeshes.end();
2199     switch ( event ) {
2200     case SMESH_subMesh::CLEAN:
2201       for ( ; smIt != smEnd; ++ smIt)
2202         (*smIt)->ComputeStateEngine( event );
2203       break;
2204     case SMESH_subMesh::COMPUTE:
2205       if ( subMesh->GetComputeState() == SMESH_subMesh::COMPUTE_OK )
2206         for ( ; smIt != smEnd; ++ smIt)
2207           (*smIt)->ComputeStateEngine( SMESH_subMesh::SUBMESH_COMPUTED );
2208       break;
2209     default:;
2210     }
2211   }
2212 }
2213
2214 namespace {
2215
2216   //================================================================================
2217   /*!
2218    * \brief Iterator over submeshes and optionally prepended or appended one
2219    */
2220   //================================================================================
2221
2222   struct _Iterator : public SMDS_Iterator<SMESH_subMesh*>
2223   {
2224     _Iterator(SMDS_Iterator<SMESH_subMesh*>* subIt,
2225               SMESH_subMesh*                 prepend,
2226               SMESH_subMesh*                 append): myIt(subIt),myAppend(append)
2227     {
2228       myCur = prepend ? prepend : myIt->more() ? myIt->next() : append;
2229       if ( myCur == append ) append = 0;
2230     }
2231     /// Return true if and only if there are other object in this iterator
2232     virtual bool more()
2233     {
2234       return myCur;
2235     }
2236     /// Return the current object and step to the next one
2237     virtual SMESH_subMesh* next()
2238     {
2239       SMESH_subMesh* res = myCur;
2240       if ( myIt->more() ) { myCur = myIt->next(); }
2241       else                { myCur = myAppend; myAppend = 0; }
2242       return res;
2243     }
2244     /// ~
2245     ~_Iterator()
2246     { delete myIt; }
2247     ///
2248     SMESH_subMesh                 *myAppend, *myCur;
2249     SMDS_Iterator<SMESH_subMesh*> *myIt;
2250   };
2251 }
2252
2253 //================================================================================
2254 /*!
2255  * \brief  Return iterator on the submeshes this one depends on
2256   * \param includeSelf - this submesh to be returned also
2257   * \param reverse - if true, complex shape submeshes go first
2258  */
2259 //================================================================================
2260
2261 SMESH_subMeshIteratorPtr SMESH_subMesh::getDependsOnIterator(const bool includeSelf,
2262                                                              const bool reverse)
2263 {
2264   SMESH_subMesh *prepend=0, *append=0;
2265   if ( includeSelf ) {
2266     if ( reverse ) prepend = this;
2267     else            append = this;
2268   }
2269   typedef map < int, SMESH_subMesh * > TMap;
2270   if ( reverse )
2271   {
2272     return SMESH_subMeshIteratorPtr
2273       ( new _Iterator( new SMDS_mapReverseIterator<TMap>( DependsOn() ), prepend, append ));
2274   }
2275   {
2276     return SMESH_subMeshIteratorPtr
2277       ( new _Iterator( new SMDS_mapIterator<TMap>( DependsOn() ), prepend, append ));
2278   }
2279 }
2280
2281 //================================================================================
2282 /*!
2283  * \brief  Find common submeshes (based on shared sub-shapes with other
2284   * \param theOther submesh to check
2285   * \param theSetOfCommon set of common submesh
2286  */
2287 //================================================================================
2288
2289 bool SMESH_subMesh::FindIntersection(const SMESH_subMesh* theOther,
2290                                      std::set<const SMESH_subMesh*>& theSetOfCommon ) const
2291 {
2292   int oldNb = theSetOfCommon.size();
2293   // check main submeshes
2294   const map <int, SMESH_subMesh*>::const_iterator otherEnd = theOther->_mapDepend.end();
2295   if ( theOther->_mapDepend.find(this->GetId()) != otherEnd )
2296     theSetOfCommon.insert( this );
2297   if ( _mapDepend.find(theOther->GetId()) != _mapDepend.end() )
2298     theSetOfCommon.insert( theOther );
2299   // check common submeshes
2300   map <int, SMESH_subMesh*>::const_iterator mapIt = _mapDepend.begin();
2301   for( ; mapIt != _mapDepend.end(); mapIt++ )
2302     if ( theOther->_mapDepend.find((*mapIt).first) != otherEnd )
2303       theSetOfCommon.insert( (*mapIt).second );
2304   return oldNb < theSetOfCommon.size();
2305 }