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