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