Salome HOME
18b6c3cdfe9687603d1dea4f8dacc19b5806ea71
[modules/smesh.git] / src / SMESH / SMESH_subMesh.cxx
1 // Copyright (C) 2007-2024  CEA, EDF, 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 #include "SMESH_MeshLocker.hxx"
41
42 #include "utilities.h"
43 #include "Basics_Utils.hxx"
44
45 #include <BRep_Builder.hxx>
46 #include <BRep_Tool.hxx>
47 #include <TopExp.hxx>
48 #include <TopExp_Explorer.hxx>
49 #include <TopTools_IndexedMapOfShape.hxx>
50 #include <TopTools_ListIteratorOfListOfShape.hxx>
51 #include <TopTools_ListOfShape.hxx>
52 #include <TopoDS.hxx>
53 #include <TopoDS_Compound.hxx>
54 #include <TopoDS_Iterator.hxx>
55 #include <gp_Pnt.hxx>
56
57 #include <Standard_OutOfMemory.hxx>
58 #include <Standard_ErrorHandler.hxx>
59
60 #include <numeric>
61
62 using namespace std;
63
64 #ifdef _DEBUG_
65 // enable printing algo + shape id + hypo used while meshing
66 #define PRINT_WHO_COMPUTE_WHAT
67 #endif
68
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       {
895         if ( anHyp->GetDim() == this->GetAlgo()->GetDim() )
896           ret = SMESH_Hypothesis::HYP_INCOMPATIBLE;
897       }
898
899       if (SMESH_Hypothesis::IsStatusFatal( ret ))
900       {
901         MESSAGE("do not add extra hypothesis");
902         meshDS->RemoveHypothesis(_subShape, anHyp);
903       }
904       else
905       {
906         modifiedHyp = true;
907       }
908       break;
909     }
910     case ADD_ALGO: {           //already existing algo : on father ?
911       algo = GetAlgo();
912       if ( algo->CheckHypothesis((*_father),_subShape, aux_ret )) {
913         // check if algo changes
914         SMESH_HypoFilter f;
915         f.Init(   SMESH_HypoFilter::IsAlgo() );
916         f.And(    SMESH_HypoFilter::IsApplicableTo( _subShape ));
917         f.AndNot( SMESH_HypoFilter::Is( algo ));
918         const SMESH_Hypothesis * prevAlgo = _father->GetHypothesis( this, f, true );
919         if (prevAlgo &&
920             string( algo->GetName()) != prevAlgo->GetName())
921         {
922           oldAlgoState = NO_ALGO; // force setting event listener (#16648)
923           modifiedHyp  = true;
924         }
925       }
926       else
927         setAlgoState(MISSING_HYP);
928       break;
929     }
930     case REMOVE_HYP: {
931       algo = GetAlgo();
932       ASSERT(algo);
933       if ( algo->CheckHypothesis((*_father),_subShape, aux_ret ))
934         setAlgoState(HYP_OK);
935       else
936         setAlgoState(MISSING_HYP);
937       modifiedHyp = true;
938       break;
939     }
940     case REMOVE_ALGO: {         // perhaps a father algo applies ?
941       algo = GetAlgo();
942       if (algo == NULL)   // no more algo applying on sub-shape...
943       {
944         setAlgoState(NO_ALGO);
945       }
946       else
947       {
948         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret )) {
949           // check if algo remains
950           if ( anHyp != algo && strcmp( anHyp->GetName(), algo->GetName()) )
951             modifiedHyp = true;
952         }
953         else
954           setAlgoState(MISSING_HYP);
955       }
956       break;
957     }
958     case MODIF_HYP: // hypothesis value may become bad
959     case ADD_FATHER_HYP: {  // new father hypothesis ?
960       algo = GetAlgo();
961       ASSERT(algo);
962       if ( algo->CheckHypothesis((*_father),_subShape, aux_ret ))
963       {
964         if (_father->IsUsedHypothesis( anHyp, this )) // new Hyp
965           modifiedHyp = true;
966       }
967       else
968         setAlgoState(MISSING_HYP);
969       break;
970     }
971     case ADD_FATHER_ALGO: {
972       algo = GetAlgo();
973       if ( algo == anHyp ) { // a new algo on father
974         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret )) {
975           // check if algo changes
976           SMESH_HypoFilter f;
977           f.Init(   SMESH_HypoFilter::IsAlgo() );
978           f.And(    SMESH_HypoFilter::IsApplicableTo( _subShape ));
979           f.AndNot( SMESH_HypoFilter::Is( algo ));
980           const SMESH_Hypothesis* prevAlgo = _father->GetHypothesis( this, f, true );
981           if (prevAlgo &&
982               string(algo->GetName()) != string(prevAlgo->GetName()) )
983             modifiedHyp = true;
984         }
985         else
986           setAlgoState(MISSING_HYP);
987       }
988       break;
989     }
990     case REMOVE_FATHER_HYP: {
991       algo = GetAlgo();
992       ASSERT(algo);
993       if ( algo->CheckHypothesis((*_father),_subShape, aux_ret )) {
994         // is there the same local hyp or maybe a new father algo applied?
995         if ( !getSimilarAttached( _subShape, anHyp ) )
996           modifiedHyp = true;
997       }
998       else
999         setAlgoState(MISSING_HYP);
1000       break;
1001     }
1002     case REMOVE_FATHER_ALGO: {
1003       // IPAL21346. Edges not removed when Netgen 1d-2d is removed from a SOLID.
1004       // CLEAN was not called at event REMOVE_ALGO because the algo is not applicable to SOLID.
1005       algo = dynamic_cast<SMESH_Algo*> (anHyp);
1006       if (!algo->NeedDiscreteBoundary())
1007         algoRequiringCleaning = algo;
1008       algo = GetAlgo();
1009       if (algo == NULL)  // no more applying algo on father
1010       {
1011         setAlgoState(NO_ALGO);
1012       }
1013       else
1014       {
1015         if ( algo->CheckHypothesis((*_father),_subShape, aux_ret )) {
1016           // check if algo changes
1017           if ( string(algo->GetName()) != string( anHyp->GetName()) )
1018             modifiedHyp = true;
1019         }
1020         else
1021           setAlgoState(MISSING_HYP);
1022       }
1023       break;
1024     }
1025     default:
1026       ASSERT(0);
1027       break;
1028     }
1029     break;
1030
1031     // ----------------------------------------------------------------------
1032
1033   default:
1034     ASSERT(0);
1035     break;
1036   }
1037
1038   // detect algorithm hiding
1039   //
1040   if ( ret == SMESH_Hypothesis::HYP_OK &&
1041        ( event == ADD_ALGO || event == ADD_FATHER_ALGO ) && algo &&
1042        algo->GetName() == anHyp->GetName() )
1043   {
1044     // is algo hidden?
1045     SMESH_Gen* gen = _father->GetGen();
1046     const std::vector< SMESH_subMesh * > & ancestors = GetAncestors();
1047     for ( size_t iA = 0; ( ret == SMESH_Hypothesis::HYP_OK && iA < ancestors.size()); ++iA ) {
1048       if ( SMESH_Algo* upperAlgo = ancestors[ iA ]->GetAlgo() )
1049         if ( !upperAlgo->NeedDiscreteBoundary() && !upperAlgo->SupportSubmeshes())
1050           ret = SMESH_Hypothesis::HYP_HIDDEN_ALGO;
1051     }
1052     // is algo hiding?
1053     if ( ret == SMESH_Hypothesis::HYP_OK &&
1054          !algo->NeedDiscreteBoundary()    &&
1055          !algo->SupportSubmeshes())
1056     {
1057       TopoDS_Shape algoAssignedTo, otherAssignedTo;
1058       gen->GetAlgo( this, &algoAssignedTo );
1059       map<int, SMESH_subMesh*>::reverse_iterator i_sm = _mapDepend.rbegin();
1060       for ( ; ( ret == SMESH_Hypothesis::HYP_OK && i_sm != _mapDepend.rend()) ; ++i_sm )
1061         if ( gen->GetAlgo( i_sm->second, &otherAssignedTo ) &&
1062              SMESH_MesherHelper::IsSubShape( /*sub=*/otherAssignedTo, /*main=*/algoAssignedTo ))
1063           ret = SMESH_Hypothesis::HYP_HIDING_ALGO;
1064     }
1065   }
1066
1067   if ( _algo ) { // get an error description set by _algo->CheckHypothesis()
1068     _computeError = _algo->GetComputeError();
1069     _algo->InitComputeError();
1070   }
1071
1072   bool stateChange = ( _algoState != oldAlgoState );
1073
1074   if ( stateChange && _algoState == HYP_OK ) // hyp becomes OK
1075     algo->SetEventListener( this );
1076
1077   if ( event == REMOVE_ALGO || event == REMOVE_FATHER_ALGO )
1078     _algo = 0;
1079
1080   notifyListenersOnEvent( event, ALGO_EVENT, anHyp );
1081
1082   if ( stateChange && oldAlgoState == HYP_OK ) { // hyp becomes KO
1083     deleteOwnListeners();
1084     SetIsAlwaysComputed( false );
1085     if (_subShape.ShapeType() == TopAbs_VERTEX ) {
1086       // restore default states
1087       _algoState = HYP_OK;
1088       _computeState = READY_TO_COMPUTE;
1089     }
1090   }
1091
1092   if ( algoRequiringCleaning ) {
1093     // added or removed algo is all-dimensional
1094     ComputeStateEngine( CLEAN );
1095     cleanDependsOn( algoRequiringCleaning );
1096     ComputeSubMeshStateEngine( CHECK_COMPUTE_STATE );
1097   }
1098
1099   if ( stateChange || modifiedHyp )
1100     ComputeStateEngine( MODIF_ALGO_STATE );
1101
1102   _realComputeCost = ( _algoState == HYP_OK ) ? computeCost() : 0;
1103
1104   return ret;
1105 }
1106
1107 //=======================================================================
1108 //function : IsConform
1109 //purpose  : check if a conform mesh will be produced by the Algo
1110 //=======================================================================
1111
1112 bool SMESH_subMesh::IsConform(const SMESH_Algo* theAlgo)
1113 {
1114 //  MESSAGE( "SMESH_subMesh::IsConform" );
1115   if ( !theAlgo ) return false;
1116
1117   // Suppose that theAlgo is applicable to _subShape, do not check it here
1118   //if ( !IsApplicableHypothesis( theAlgo )) return false;
1119
1120   // check only algo that doesn't NeedDiscreteBoundary(): because mesh made
1121   // on a sub-shape will be ignored by theAlgo
1122   if ( theAlgo->NeedDiscreteBoundary() ||
1123        !theAlgo->OnlyUnaryInput() ) // all adjacent shapes will be meshed by this algo?
1124     return true;
1125
1126   // only local algo is to be checked
1127   //if ( gen->IsGlobalHypothesis( theAlgo, *_father ))
1128   if ( _subShape.ShapeType() == _father->GetMeshDS()->ShapeToMesh().ShapeType() )
1129     return true;
1130
1131   // check algo attached to adjacent shapes
1132
1133   // loop on one level down sub-meshes
1134   TopoDS_Iterator itsub( _subShape );
1135   for (; itsub.More(); itsub.Next())
1136   {
1137     // loop on adjacent subShapes
1138     const std::vector< SMESH_subMesh * > & ancestors = GetAncestors();
1139     for ( size_t iA = 0; iA < ancestors.size(); ++iA )
1140     {
1141       const TopoDS_Shape& adjacent = ancestors[ iA ]->GetSubShape();
1142       if ( _subShape.IsSame( adjacent )) continue;
1143       if ( adjacent.ShapeType() != _subShape.ShapeType())
1144         break;
1145
1146       // check algo attached to smAdjacent
1147       SMESH_Algo * algo = ancestors[ iA ]->GetAlgo();
1148       if (algo &&
1149           !algo->NeedDiscreteBoundary() &&
1150           algo->OnlyUnaryInput())
1151         return false; // NOT CONFORM MESH WILL BE PRODUCED
1152     }
1153   }
1154
1155   return true;
1156 }
1157
1158 //=============================================================================
1159 /*!
1160  *
1161  */
1162 //=============================================================================
1163
1164 void SMESH_subMesh::setAlgoState(algo_state state)
1165 {
1166   _algoState = state;
1167 }
1168
1169 //================================================================================
1170 /*!
1171  * \brief Send an event to sub-meshes
1172  *  \param [in] event - the event
1173  *  \param [in] anHyp - an hypothesis
1174  *  \param [in] exitOnFatal - to stop iteration on sub-meshes if a sub-mesh
1175  *              reports a fatal result
1176  *  \return SMESH_Hypothesis::Hypothesis_Status - the worst result
1177  *
1178  * Optional description of a problematic situation (if any) can be retrieved
1179  * via GetComputeError().
1180  */
1181 //================================================================================
1182
1183 SMESH_Hypothesis::Hypothesis_Status
1184   SMESH_subMesh::SubMeshesAlgoStateEngine(algo_event         event,
1185                                           SMESH_Hypothesis * anHyp,
1186                                           bool               exitOnFatal)
1187 {
1188   SMESH_Hypothesis::Hypothesis_Status ret = SMESH_Hypothesis::HYP_OK;
1189   //EAP: a wire (dim==1) should notify edges (dim==1)
1190   //EAP: int dim = SMESH_Gen::GetShapeDim(_subShape);
1191   //if (_subShape.ShapeType() < TopAbs_EDGE ) // wire,face etc
1192   {
1193     SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
1194     while ( smIt->more() ) {
1195       SMESH_subMesh* sm = smIt->next();
1196       SMESH_Hypothesis::Hypothesis_Status ret2 = sm->AlgoStateEngine(event, anHyp);
1197       if ( ret2 > ret )
1198       {
1199         ret = ret2;
1200         _computeError = sm->_computeError;
1201         sm->_computeError.reset();
1202         if ( exitOnFatal && SMESH_Hypothesis::IsStatusFatal( ret ))
1203           break;
1204       }
1205     }
1206   }
1207   return ret;
1208 }
1209
1210 //================================================================================
1211 /*!
1212  * \brief Remove elements from sub-meshes.
1213  *  \param algoRequiringCleaning - an all-dimensional algorithm whose presence
1214  *         causes the cleaning.
1215  */
1216 //================================================================================
1217
1218 void SMESH_subMesh::cleanDependsOn( SMESH_Algo* algoRequiringCleaning/*=0*/ )
1219 {
1220   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,
1221                                                        /*complexShapeFirst=*/true);
1222   if ( _father->NbNodes() == 0 )
1223   {
1224     while ( smIt->more() )
1225       smIt->next()->ComputeStateEngine(CHECK_COMPUTE_STATE);
1226   }
1227   else if ( !algoRequiringCleaning || !algoRequiringCleaning->SupportSubmeshes() )
1228   {
1229     while ( smIt->more() )
1230       smIt->next()->ComputeStateEngine(CLEAN);
1231   }
1232   else if ( algoRequiringCleaning && algoRequiringCleaning->SupportSubmeshes() )
1233   {
1234     // find sub-meshes to keep elements on
1235     set< SMESH_subMesh* > smToKeep;
1236     TopAbs_ShapeEnum prevShapeType = TopAbs_SHAPE;
1237     bool toKeepPrevShapeType = false;
1238     while ( smIt->more() )
1239     {
1240       SMESH_subMesh* sm = smIt->next();
1241       sm->ComputeStateEngine(CHECK_COMPUTE_STATE);
1242       if ( !sm->IsEmpty() )
1243       {
1244         const bool sameShapeType = ( prevShapeType == sm->GetSubShape().ShapeType() );
1245         bool       keepSubMeshes = ( sameShapeType && toKeepPrevShapeType );
1246         if ( !sameShapeType )
1247         {
1248           // check if the algo allows presence of global algos of dimension the algo
1249           // can generate it-self;
1250           // always keep a node on VERTEX, as this node can be shared by segments
1251           // lying on EDGEs not shared by the VERTEX of sm, due to MergeNodes (PAL23068)
1252           int  shapeDim = SMESH_Gen::GetShapeDim( sm->GetSubShape() );
1253           keepSubMeshes = ( algoRequiringCleaning->NeedLowerHyps( shapeDim ) || shapeDim == 0 );
1254           prevShapeType = sm->GetSubShape().ShapeType();
1255           toKeepPrevShapeType = keepSubMeshes;
1256         }
1257         if ( !keepSubMeshes )
1258         {
1259           // look for a local algo used to mesh sm
1260           TopoDS_Shape algoShape = SMESH_MesherHelper::GetShapeOfHypothesis
1261             ( algoRequiringCleaning, _subShape, _father );
1262           SMESH_HypoFilter moreLocalAlgo;
1263           moreLocalAlgo.Init( SMESH_HypoFilter::IsMoreLocalThan( algoShape, *_father ));
1264           moreLocalAlgo.And ( SMESH_HypoFilter::IsAlgo() );
1265           bool localAlgoFound = _father->GetHypothesis( sm->_subShape, moreLocalAlgo, true );
1266           keepSubMeshes = localAlgoFound;
1267         }
1268         // remember all sub-meshes of sm
1269         if ( keepSubMeshes )
1270         {
1271           SMESH_subMeshIteratorPtr smIt2 = sm->getDependsOnIterator(true);
1272           while ( smIt2->more() )
1273             smToKeep.insert( smIt2->next() );
1274         }
1275       }
1276     }
1277     // remove elements
1278     SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,true);
1279     while ( smIt->more() )
1280     {
1281       SMESH_subMesh* sm = smIt->next();
1282       if ( !smToKeep.count( sm ))
1283         sm->ComputeStateEngine(CLEAN);
1284     }
1285   }
1286 }
1287
1288 //=============================================================================
1289 /*!
1290  *
1291  */
1292 //=============================================================================
1293
1294 void SMESH_subMesh::DumpAlgoState(bool isMain)
1295 {
1296   if (isMain)
1297   {
1298     const map < int, SMESH_subMesh * >&subMeshes = DependsOn();
1299
1300     map < int, SMESH_subMesh * >::const_iterator itsub;
1301     for (itsub = subMeshes.begin(); itsub != subMeshes.end(); itsub++)
1302     {
1303       SMESH_subMesh *sm = (*itsub).second;
1304       sm->DumpAlgoState(false);
1305     }
1306   }
1307   MESSAGE("dim = " << SMESH_Gen::GetShapeDim(_subShape) <<
1308           " type of shape " << _subShape.ShapeType());
1309   switch (_algoState)
1310   {
1311   case NO_ALGO          : MESSAGE(" AlgoState = NO_ALGO"); break;
1312   case MISSING_HYP      : MESSAGE(" AlgoState = MISSING_HYP"); break;
1313   case HYP_OK           : MESSAGE(" AlgoState = HYP_OK");break;
1314   }
1315   switch (_computeState)
1316   {
1317   case NOT_READY        : MESSAGE(" ComputeState = NOT_READY");break;
1318   case READY_TO_COMPUTE : MESSAGE(" ComputeState = READY_TO_COMPUTE");break;
1319   case COMPUTE_OK       : MESSAGE(" ComputeState = COMPUTE_OK");break;
1320   case FAILED_TO_COMPUTE: MESSAGE(" ComputeState = FAILED_TO_COMPUTE");break;
1321   }
1322 }
1323
1324 //================================================================================
1325 /*!
1326  * \brief Remove nodes and elements bound to submesh
1327   * \param subMesh - submesh containing nodes and elements
1328  */
1329 //================================================================================
1330
1331 static void cleanSubMesh( SMESH_subMesh * subMesh )
1332 {
1333   if (subMesh) {
1334     if (SMESHDS_SubMesh * subMeshDS = subMesh->GetSubMeshDS())
1335     {
1336       SMESHDS_Mesh * meshDS = subMesh->GetFather()->GetMeshDS();
1337       smIdType nbElems = subMeshDS->NbElements();
1338       if ( nbElems > 0 )
1339         for ( SMDS_ElemIteratorPtr ite = subMeshDS->GetElements(); ite->more(); )
1340           meshDS->RemoveFreeElement( ite->next(), subMeshDS );
1341
1342       smIdType nbNodes = subMeshDS->NbNodes();
1343       if ( nbNodes > 0 )
1344         for ( SMDS_NodeIteratorPtr itn = subMeshDS->GetNodes(); itn->more() ; )
1345         {
1346           const SMDS_MeshNode * node = itn->next();
1347           if ( node->NbInverseElements() == 0 )
1348             meshDS->RemoveFreeNode( node, subMeshDS );
1349           else // for StdMeshers_CompositeSegment_1D: node in one submesh, edge in another
1350             meshDS->RemoveNode( node );
1351         }
1352       subMeshDS->Clear();
1353     }
1354   }
1355 }
1356
1357 //=============================================================================
1358 /*!
1359  *
1360  */
1361 //=============================================================================
1362
1363 bool SMESH_subMesh::ComputeStateEngine(compute_event event)
1364 {
1365   switch ( event ) {
1366   case MODIF_ALGO_STATE:
1367   case COMPUTE:
1368   case COMPUTE_SUBMESH:
1369     //case COMPUTE_CANCELED:
1370   case CLEAN:
1371     //case SUBMESH_COMPUTED:
1372     //case SUBMESH_RESTORED:
1373     //case SUBMESH_LOADED:
1374     //case MESH_ENTITY_REMOVED:
1375     //case CHECK_COMPUTE_STATE:
1376     _computeError.reset(); break;
1377   default:;
1378   }
1379
1380   if ( event == CLEAN )
1381     _alwaysComputed = false; // Unset 'true' set by MergeNodes() (issue 0022182)
1382
1383   if (_subShape.ShapeType() == TopAbs_VERTEX)
1384   {
1385     _computeState = READY_TO_COMPUTE;
1386     SMESHDS_SubMesh* smDS = GetSubMeshDS();
1387     if ( smDS && smDS->NbNodes() )
1388     {
1389       if ( event == CLEAN ) {
1390         cleanDependants();
1391         cleanSubMesh( this );
1392       }
1393       else
1394         _computeState = COMPUTE_OK;
1395     }
1396     else if (( event == COMPUTE || event == COMPUTE_SUBMESH )
1397              && !_alwaysComputed )
1398     {
1399       SMESH_MeshLocker myLocker(_father);
1400       const TopoDS_Vertex & V = TopoDS::Vertex( _subShape );
1401       gp_Pnt P = BRep_Tool::Pnt(V);
1402       if ( SMDS_MeshNode * n = _father->GetMeshDS()->AddNode(P.X(), P.Y(), P.Z()) ) {
1403         _father->GetMeshDS()->SetNodeOnVertex(n,_Id);
1404         _computeState = COMPUTE_OK;
1405       }
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         ret = algo->CheckHypothesis((*_father), _subShape, hyp_status);
1511         if (!ret)
1512         {
1513           MESSAGE("***** verify compute state *****");
1514           _computeState = NOT_READY;
1515           setAlgoState(MISSING_HYP);
1516           break;
1517         }
1518         TopoDS_Shape shape = _subShape;
1519         algo->setSubMeshesToCompute(this);
1520         // check submeshes needed
1521         // When computing in parallel mode we do not have a additional layer of submesh
1522         // The check should not be done in parallel as that check is not thread-safe
1523         if (_father->HasShapeToMesh() && (!_father->IsParallel() || shape.ShapeType() != _father->GetParallelElement() )) {
1524           bool subComputed = false, subFailed = false;
1525           if (!algo->OnlyUnaryInput()) {
1526             //  --- commented for bos#22320 to compute all sub-shapes at once if possible;
1527             //  --- in case COMPUTE_SUBMESH, set of sub-shapes is limited
1528             //  --- by calling SetAllowedSubShapes()
1529             // if ( event == COMPUTE )
1530             //   shape = getCollection( gen, algo, subComputed, subFailed, algo->SubMeshesToComput;
1531             // else
1532             //   subComputed = SubMeshesComputed( & subFailed );
1533             shape = getCollection( gen, algo, subComputed, subFailed, algo->SubMeshesToCompute());
1534           }
1535           else {
1536             subComputed = SubMeshesComputed();
1537           }
1538           ret = ( algo->NeedDiscreteBoundary() ? subComputed :
1539                   algo->SupportSubmeshes() ? !subFailed :
1540                   ( !subComputed || _father->IsNotConformAllowed() ));
1541           if (!ret)
1542           {
1543             _computeState = FAILED_TO_COMPUTE;
1544             if ( !algo->NeedDiscreteBoundary() && !subFailed )
1545               _computeError =
1546                 SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
1547                                         "Unexpected computed sub-mesh",algo);
1548             break; // goto exit
1549           }
1550         }
1551         // Compute
1552
1553         // to restore cout that may be redirected by algo
1554         std::streambuf* coutBuffer = std::cout.rdbuf();
1555
1556         //cleanDependants(); for "UseExisting_*D" algos
1557         //removeSubMeshElementsAndNodes();
1558         loadDependentMeshes();
1559         ret = false;
1560         _computeState = FAILED_TO_COMPUTE;
1561         _computeError = SMESH_ComputeError::New(COMPERR_OK,"",algo);
1562         try {
1563           OCC_CATCH_SIGNALS;
1564
1565           algo->InitComputeError();
1566
1567           MemoryReserve aMemoryReserve;
1568           SMDS_Mesh::CheckMemory();
1569           Kernel_Utils::Localizer loc;
1570           if ( !_father->HasShapeToMesh() ) // no shape
1571           {
1572             SMESH_MesherHelper helper( *_father );
1573             helper.SetSubShape( shape );
1574             helper.SetElementsOnShape( true );
1575             ret = algo->Compute(*_father, &helper );
1576           }
1577           else
1578           {
1579             ret = algo->Compute((*_father), shape);
1580           }
1581           // algo can set _computeError of submesh
1582           _computeError = SMESH_ComputeError::Worst( _computeError, algo->GetComputeError() );
1583         }
1584         catch ( ::SMESH_ComputeError& comperr ) {
1585           MESSAGE(" SMESH_ComputeError caught");
1586           if ( !_computeError ) _computeError = SMESH_ComputeError::New();
1587           *_computeError = comperr;
1588         }
1589         catch ( std::bad_alloc& exc ) {
1590           MESSAGE("std::bad_alloc thrown inside algo->Compute()");
1591           if ( _computeError ) {
1592             _computeError->myName = COMPERR_MEMORY_PB;
1593           }
1594           cleanSubMesh( this );
1595           throw exc;
1596         }
1597         catch ( Standard_OutOfMemory& exc ) {
1598           MESSAGE("Standard_OutOfMemory thrown inside algo->Compute()");
1599           if ( _computeError ) {
1600             _computeError->myName = COMPERR_MEMORY_PB;
1601           }
1602           cleanSubMesh( this );
1603           throw std::bad_alloc();
1604         }
1605         catch (Standard_Failure& ex) {
1606           if ( !_computeError ) _computeError = SMESH_ComputeError::New();
1607           _computeError->myName    = COMPERR_OCC_EXCEPTION;
1608           _computeError->myComment += ex.DynamicType()->Name();
1609           if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
1610             _computeError->myComment += ": ";
1611             _computeError->myComment += ex.GetMessageString();
1612           }
1613         }
1614         catch ( SALOME_Exception& S_ex ) {
1615           const int skipSalomeShift = 7; /* to skip "Salome " of
1616                                             "Salome Exception" prefix returned
1617                                             by SALOME_Exception::what() */
1618           if ( !_computeError ) _computeError = SMESH_ComputeError::New();
1619           _computeError->myName    = COMPERR_SLM_EXCEPTION;
1620           _computeError->myComment = S_ex.what() + skipSalomeShift;
1621         }
1622         catch ( std::exception& exc ) {
1623           if ( !_computeError ) _computeError = SMESH_ComputeError::New();
1624           _computeError->myName    = COMPERR_STD_EXCEPTION;
1625           _computeError->myComment = exc.what();
1626         }
1627         catch ( ... ) {
1628           if ( _computeError )
1629             _computeError->myName = COMPERR_EXCEPTION;
1630           else
1631             ret = false;
1632         }
1633         std::cout.rdbuf( coutBuffer ); // restore cout that could be redirected by algo
1634
1635         // check if an error reported on any sub-shape
1636         bool isComputeErrorSet = !checkComputeError( algo, ret, shape );
1637         if ( isComputeErrorSet )
1638           ret = false;
1639         // check if anything was built
1640         TopExp_Explorer subS(shape, _subShape.ShapeType());
1641         if ( ret )
1642         {
1643           for (; ret && subS.More(); subS.Next())
1644             if ( !_father->GetSubMesh( subS.Current() )->IsMeshComputed() &&
1645                  ( _subShape.ShapeType() != TopAbs_EDGE ||
1646                    !algo->isDegenerated( TopoDS::Edge( subS.Current() ))))
1647               ret = false;
1648         }
1649 #ifdef PRINT_WHO_COMPUTE_WHAT
1650         for (subS.ReInit(); subS.More(); subS.Next())
1651         {
1652           SMESH_MeshLocker myLocker(_father);
1653           const std::list <const SMESHDS_Hypothesis *> & hyps =
1654               _algo->GetUsedHypothesis( *_father, _subShape );
1655           SMESH_Comment hypStr;
1656           if ( !hyps.empty() )
1657           {
1658             hypStr << hyps.front()->GetName() << " ";
1659             ((SMESHDS_Hypothesis*)hyps.front())->SaveTo( hypStr.Stream() );
1660             hypStr << " ";
1661           }
1662           cout << _father->GetSubMesh( subS.Current() )->GetId()
1663                << " " << ( ret ? "OK" : "FAIL" )
1664                << " " << _algo->GetName()
1665                << " " << hypStr << endl;
1666         }
1667 #endif
1668         // Set _computeError
1669         if ( !ret && !isComputeErrorSet )
1670         {
1671           for ( subS.ReInit(); subS.More(); subS.Next() )
1672           {
1673             SMESH_subMesh* sm = _father->GetSubMesh( subS.Current() );
1674             if ( !sm->IsMeshComputed() )
1675             {
1676               if ( !sm->_computeError )
1677                 sm->_computeError = SMESH_ComputeError::New();
1678               if ( sm->_computeError->IsOK() )
1679                 sm->_computeError->myName = COMPERR_ALGO_FAILED;
1680               sm->_computeState = FAILED_TO_COMPUTE;
1681               sm->_computeError->myAlgo = algo;
1682             }
1683           }
1684         }
1685         if ( ret && _computeError && _computeError->myName != COMPERR_WARNING )
1686         {
1687           _computeError.reset();
1688         }
1689
1690         // transform errors into warnings if it is caused by mesh edition (imp 0023068)
1691         if (!ret && _father->GetIsModified() )
1692         {
1693           for (subS.ReInit(); subS.More(); subS.Next())
1694           {
1695             SMESH_subMesh* sm = _father->GetSubMesh( subS.Current() );
1696             if ( !sm->IsMeshComputed() && sm->_computeError )
1697             {
1698               // check if there is a VERTEX w/o nodes
1699               // with READY_TO_COMPUTE state (after MergeNodes())
1700               SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,false);
1701               while ( smIt->more() )
1702               {
1703                 SMESH_subMesh * vertSM = smIt->next();
1704                 if ( vertSM->_subShape.ShapeType() != TopAbs_VERTEX ) break;
1705                 if ( vertSM->GetComputeState() == READY_TO_COMPUTE )
1706                 {
1707                   SMESHDS_SubMesh * ds = vertSM->GetSubMeshDS();
1708                   if ( !ds || ds->NbNodes() == 0 )
1709                   {
1710                     sm->_computeState = READY_TO_COMPUTE;
1711                     sm->_computeError->myName = COMPERR_WARNING;
1712                     break;
1713                   }
1714                 }
1715               }
1716             }
1717           }
1718         }
1719
1720         // send event SUBMESH_COMPUTED
1721         if ( ret ) {
1722           if ( !algo->NeedDiscreteBoundary() )
1723             // send SUBMESH_COMPUTED to dependants of all sub-meshes of shape
1724             for (subS.ReInit(); subS.More(); subS.Next())
1725             {
1726               SMESH_subMesh* sm = _father->GetSubMesh( subS.Current() );
1727               SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,false);
1728               while ( smIt->more() ) {
1729                 sm = smIt->next();
1730                 if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1731                   sm->updateDependantsState( SUBMESH_COMPUTED );
1732                 else
1733                   break;
1734               }
1735             }
1736           else
1737             updateDependantsState( SUBMESH_COMPUTED );
1738         }
1739         // let algo clear its data gathered while algo->Compute()
1740         algo->CheckHypothesis((*_father), _subShape, hyp_status);
1741       }
1742       break;
1743     case COMPUTE_CANCELED:               // nothing to do
1744       break;
1745     case CLEAN:
1746       cleanDependants();
1747       removeSubMeshElementsAndNodes();
1748       _computeState = NOT_READY;
1749       algo = GetAlgo();
1750       if (algo)
1751       {
1752         ret = algo->CheckHypothesis((*_father), _subShape, hyp_status);
1753         if (ret)
1754           _computeState = READY_TO_COMPUTE;
1755         else
1756           setAlgoState(MISSING_HYP);
1757       }
1758       break;
1759     case SUBMESH_COMPUTED:      // nothing to do
1760       break;
1761     case SUBMESH_RESTORED:
1762       // check if a mesh is already computed that may
1763       // happen after retrieval from a file
1764       ComputeStateEngine( CHECK_COMPUTE_STATE );
1765       ComputeSubMeshStateEngine( SUBMESH_RESTORED );
1766       algo = GetAlgo();
1767       if (algo) algo->SubmeshRestored( this );
1768       break;
1769     case MESH_ENTITY_REMOVED:
1770       break;
1771     case SUBMESH_LOADED:
1772       loadDependentMeshes();
1773       ComputeSubMeshStateEngine( SUBMESH_LOADED );
1774       //break;
1775       // fall through
1776     case CHECK_COMPUTE_STATE:
1777       if ( IsMeshComputed() )
1778         _computeState = COMPUTE_OK;
1779       else if ( _computeError && _computeError->IsKO() )
1780         _computeState = FAILED_TO_COMPUTE;
1781       break;
1782     default:
1783       ASSERT(0);
1784       break;
1785     }
1786     break;
1787
1788     // ----------------------------------------------------------------------
1789
1790   case COMPUTE_OK:
1791     switch (event)
1792     {
1793     case MODIF_ALGO_STATE:
1794       ComputeStateEngine( CLEAN );
1795       algo = GetAlgo();
1796       if (algo && !algo->NeedDiscreteBoundary())
1797         cleanDependsOn( algo ); // clean sub-meshes with event CLEAN
1798       break;
1799     case COMPUTE:               // nothing to do
1800       break;
1801     case COMPUTE_SUBMESH:       // nothing to do
1802       break;
1803     case COMPUTE_CANCELED:      // nothing to do
1804       break;
1805     case CLEAN:
1806       cleanDependants();  // clean sub-meshes, dependent on this one, with event CLEAN
1807       removeSubMeshElementsAndNodes();
1808       _computeState = NOT_READY;
1809       if ( _algoState == HYP_OK )
1810         _computeState = READY_TO_COMPUTE;
1811       break;
1812     case SUBMESH_COMPUTED:      // nothing to do
1813       break;
1814     case SUBMESH_RESTORED:
1815       ComputeStateEngine( CHECK_COMPUTE_STATE );
1816       ComputeSubMeshStateEngine( SUBMESH_RESTORED );
1817       algo = GetAlgo();
1818       if (algo) algo->SubmeshRestored( this );
1819       break;
1820     case MESH_ENTITY_REMOVED:
1821       updateDependantsState    ( CHECK_COMPUTE_STATE );
1822       ComputeStateEngine       ( CHECK_COMPUTE_STATE );
1823       ComputeSubMeshStateEngine( CHECK_COMPUTE_STATE );
1824       break;
1825     case CHECK_COMPUTE_STATE:
1826       if ( !IsMeshComputed() ) {
1827         if (_algoState == HYP_OK)
1828           _computeState = READY_TO_COMPUTE;
1829         else
1830           _computeState = NOT_READY;
1831       }
1832       break;
1833     case SUBMESH_LOADED:
1834       // already treated event, thanks to which _computeState == COMPUTE_OK
1835       break;
1836     default:
1837       ASSERT(0);
1838       break;
1839     }
1840     break;
1841
1842     // ----------------------------------------------------------------------
1843
1844   case FAILED_TO_COMPUTE:
1845     switch (event)
1846     {
1847     case MODIF_ALGO_STATE:
1848       if ( !IsEmpty() )
1849         ComputeStateEngine( CLEAN );
1850       algo = GetAlgo();
1851       if (algo && !algo->NeedDiscreteBoundary())
1852         cleanDependsOn( algo ); // clean sub-meshes with event CLEAN
1853       if (_algoState == HYP_OK)
1854         _computeState = READY_TO_COMPUTE;
1855       else
1856         _computeState = NOT_READY;
1857       break;
1858     case COMPUTE:        // nothing to do
1859     case COMPUTE_SUBMESH:
1860       break;
1861     case COMPUTE_CANCELED:
1862       {
1863         algo = GetAlgo();
1864         algo->CancelCompute();
1865       }
1866       break;
1867     case CLEAN:
1868       cleanDependants(); // submeshes dependent on me should be cleaned as well
1869       removeSubMeshElementsAndNodes();
1870       break;
1871     case SUBMESH_COMPUTED:      // allow retry compute
1872       if ( IsEmpty() ) // 23061
1873       {
1874         if (_algoState == HYP_OK)
1875           _computeState = READY_TO_COMPUTE;
1876         else
1877           _computeState = NOT_READY;
1878       }
1879       break;
1880     case SUBMESH_RESTORED:
1881       ComputeSubMeshStateEngine( SUBMESH_RESTORED );
1882       break;
1883     case MESH_ENTITY_REMOVED:
1884       break;
1885     case CHECK_COMPUTE_STATE:
1886       if ( IsMeshComputed() )
1887         _computeState = COMPUTE_OK;
1888       else
1889         if (_algoState == HYP_OK)
1890           _computeState = READY_TO_COMPUTE;
1891         else
1892           _computeState = NOT_READY;
1893       break;
1894     // case SUBMESH_LOADED:
1895     //   break;
1896     default:
1897       ASSERT(0);
1898       break;
1899     }
1900     break;
1901
1902     // ----------------------------------------------------------------------
1903   default:
1904     ASSERT(0);
1905     break;
1906   }
1907
1908   notifyListenersOnEvent( event, COMPUTE_EVENT );
1909
1910   return ret;
1911 }
1912
1913
1914 //=============================================================================
1915 /*!
1916  *
1917  */
1918 //=============================================================================
1919
1920 bool SMESH_subMesh::Evaluate(MapShapeNbElems& aResMap)
1921 {
1922   _computeError.reset();
1923
1924   bool ret = true;
1925
1926   if (_subShape.ShapeType() == TopAbs_VERTEX) {
1927     vector<smIdType> aVec(SMDSEntity_Last,0);
1928     aVec[SMDSEntity_Node] = 1;
1929     aResMap.insert(make_pair(this,aVec));
1930     return ret;
1931   }
1932
1933   //SMESH_Gen *gen = _father->GetGen();
1934   SMESH_Algo *algo = 0;
1935   SMESH_Hypothesis::Hypothesis_Status hyp_status;
1936
1937   algo = GetAlgo();
1938   if( algo && !aResMap.count( this ))
1939   {
1940     ret = algo->CheckHypothesis((*_father), _subShape, hyp_status);
1941     if (!ret) return false;
1942
1943     if (_father->HasShapeToMesh() && algo->NeedDiscreteBoundary() )
1944     {
1945       // check submeshes needed
1946       bool subMeshEvaluated = true;
1947       int dimToCheck = SMESH_Gen::GetShapeDim( _subShape ) - 1;
1948       SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,/*complexShapeFirst=*/true);
1949       while ( smIt->more() && subMeshEvaluated )
1950       {
1951         SMESH_subMesh* sm = smIt->next();
1952         int dim = SMESH_Gen::GetShapeDim( sm->GetSubShape() );
1953         if (dim < dimToCheck) break; // the rest subMeshes are all of less dimension
1954         const vector<smIdType> & nbs = aResMap[ sm ];
1955         subMeshEvaluated = (std::accumulate( nbs.begin(), nbs.end(), 0 ) > 0 );
1956       }
1957       if ( !subMeshEvaluated )
1958         return false;
1959     }
1960     _computeError = SMESH_ComputeError::New(COMPERR_OK,"",algo);
1961
1962     if ( IsMeshComputed() )
1963     {
1964       vector<smIdType> & nbEntities = aResMap[ this ];
1965       nbEntities.resize( SMDSEntity_Last, 0 );
1966       if ( SMESHDS_SubMesh* sm = GetSubMeshDS() )
1967       {
1968         nbEntities[ SMDSEntity_Node ] = sm->NbNodes();
1969         SMDS_ElemIteratorPtr   elemIt = sm->GetElements();
1970         while ( elemIt->more() )
1971           nbEntities[ elemIt->next()->GetEntityType() ]++;
1972       }
1973     }
1974     else
1975     {
1976       ret = algo->Evaluate((*_father), _subShape, aResMap);
1977     }
1978     aResMap.insert( make_pair( this,vector<smIdType>(0)));
1979   }
1980
1981   return ret;
1982 }
1983
1984
1985 //=======================================================================
1986 /*!
1987  * \brief Update compute_state by _computeError and send proper events to
1988  * dependent submeshes
1989   * \retval bool - true if _computeError is NOT set
1990  */
1991 //=======================================================================
1992
1993 bool SMESH_subMesh::checkComputeError(SMESH_Algo*         theAlgo,
1994                                       const bool          theComputeOK,
1995                                       const TopoDS_Shape& theShape)
1996 {
1997   bool noErrors = true;
1998
1999   if ( !theShape.IsNull() )
2000   {
2001     // Check state of submeshes
2002     if ( !theAlgo->NeedDiscreteBoundary())
2003     {
2004       SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
2005       while ( smIt->more() )
2006         if ( !smIt->next()->checkComputeError( theAlgo, theComputeOK ))
2007           noErrors = false;
2008     }
2009
2010     // Check state of neighbours
2011     if ( !theAlgo->OnlyUnaryInput() &&
2012          theShape.ShapeType() == TopAbs_COMPOUND &&
2013          !theShape.IsSame( _subShape ))
2014     {
2015       for (TopoDS_Iterator subIt( theShape ); subIt.More(); subIt.Next()) {
2016         SMESH_subMesh* sm = _father->GetSubMesh( subIt.Value() );
2017         if ( sm != this ) {
2018           if ( !sm->checkComputeError( theAlgo, theComputeOK, sm->GetSubShape() ))
2019             noErrors = false;
2020           updateDependantsState( SUBMESH_COMPUTED ); // send event SUBMESH_COMPUTED
2021         }
2022       }
2023     }
2024   }
2025   {
2026
2027     // Set my _computeState
2028
2029     if ( !_computeError || _computeError->IsOK() )
2030     {
2031       // no error description is set to this sub-mesh, check if any mesh is computed
2032       _computeState = IsMeshComputed() ? COMPUTE_OK : FAILED_TO_COMPUTE;
2033       if ( _computeState != COMPUTE_OK )
2034       {
2035         if ( _subShape.ShapeType() == TopAbs_EDGE &&
2036              SMESH_Algo::isDegenerated( TopoDS::Edge( _subShape )) )
2037           _computeState = COMPUTE_OK;
2038         else if ( theComputeOK )
2039           _computeError = SMESH_ComputeError::New(COMPERR_NO_MESH_ON_SHAPE,"",theAlgo);
2040       }
2041     }
2042
2043     if ( _computeError && !_computeError->IsOK() )
2044     {
2045       if ( !_computeError->myAlgo )
2046         _computeError->myAlgo = theAlgo;
2047
2048       // Show error
2049       SMESH_Comment text;
2050       text << theAlgo->GetName() << " failed on sub-shape #" << _Id << " with error ";
2051       if (_computeError->IsCommon() )
2052         text << _computeError->CommonName();
2053       else
2054         text << _computeError->myName;
2055       if ( _computeError->myComment.size() > 0 )
2056         text << " \"" << _computeError->myComment << "\"";
2057
2058       INFOS( text );
2059
2060       _computeState = _computeError->IsKO() ? FAILED_TO_COMPUTE : COMPUTE_OK;
2061
2062       noErrors = false;
2063     }
2064   }
2065   return noErrors;
2066 }
2067
2068 //=======================================================================
2069 //function : updateSubMeshState
2070 //purpose  :
2071 //=======================================================================
2072
2073 void SMESH_subMesh::updateSubMeshState(const compute_state theState)
2074 {
2075   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(false,false);
2076   while ( smIt->more() )
2077     smIt->next()->_computeState = theState;
2078 }
2079
2080 //=======================================================================
2081 //function : ComputeSubMeshStateEngine
2082 //purpose  :
2083 //=======================================================================
2084
2085 void SMESH_subMesh::ComputeSubMeshStateEngine(compute_event event, const bool includeSelf)
2086 {
2087   SMESH_subMeshIteratorPtr smIt = getDependsOnIterator(includeSelf,false);
2088   while ( smIt->more() )
2089     smIt->next()->ComputeStateEngine(event);
2090 }
2091
2092 //=======================================================================
2093 //function : updateDependantsState
2094 //purpose  :
2095 //=======================================================================
2096
2097 void SMESH_subMesh::updateDependantsState(const compute_event theEvent)
2098 {
2099   const std::vector< SMESH_subMesh * > & ancestors = GetAncestors();
2100   for ( size_t iA = 0; iA < ancestors.size(); ++iA )
2101   {
2102     ancestors[ iA ]->ComputeStateEngine( theEvent );
2103   }
2104 }
2105
2106 //=======================================================================
2107 //function : cleanDependants
2108 //purpose  :
2109 //=======================================================================
2110
2111 void SMESH_subMesh::cleanDependants()
2112 {
2113   int dimToClean = SMESH_Gen::GetShapeDim( _subShape ) + 1;
2114
2115   const std::vector< SMESH_subMesh * > & ancestors = GetAncestors();
2116   for ( size_t iA = 0; iA < ancestors.size(); ++iA )
2117   {
2118     const TopoDS_Shape& ancestor = ancestors[ iA ]->GetSubShape();
2119     if ( SMESH_Gen::GetShapeDim( ancestor ) == dimToClean )
2120     {
2121       // PAL8021. do not go upper than SOLID, else ComputeStateEngine(CLEAN)
2122       // will erase mesh on other shapes in a compound
2123       if ( ancestor.ShapeType() >= TopAbs_SOLID &&
2124            !ancestors[ iA ]->IsEmpty() )  // prevent infinite CLEAN via event lesteners
2125         ancestors[ iA ]->ComputeStateEngine(CLEAN);
2126     }
2127   }
2128 }
2129
2130 //=======================================================================
2131 //function : removeSubMeshElementsAndNodes
2132 //purpose  :
2133 //=======================================================================
2134
2135 void SMESH_subMesh::removeSubMeshElementsAndNodes()
2136 {
2137   cleanSubMesh( this );
2138
2139   // algo may bind a submesh not to _subShape, eg 3D algo
2140   // sets nodes on SHELL while _subShape may be SOLID
2141
2142   int dim = SMESH_Gen::GetShapeDim( _subShape );
2143   int type = _subShape.ShapeType() + 1;
2144   for ( ; type <= TopAbs_EDGE; type++) {
2145     if ( dim == SMESH_Gen::GetShapeDim( (TopAbs_ShapeEnum) type ))
2146     {
2147       TopExp_Explorer exp( _subShape, (TopAbs_ShapeEnum) type );
2148       for ( ; exp.More(); exp.Next() )
2149         cleanSubMesh( _father->GetSubMeshContaining( exp.Current() ));
2150     }
2151     else
2152       break;
2153   }
2154 }
2155
2156 //=======================================================================
2157 //function : getCollection
2158 //purpose  : return a shape containing all sub-shapes of the MainShape that can be
2159 //           meshed at once along with _subShape
2160 //=======================================================================
2161
2162 TopoDS_Shape SMESH_subMesh::getCollection(SMESH_Gen * /*theGen*/,
2163                                           SMESH_Algo* theAlgo,
2164                                           bool &      theSubComputed,
2165                                           bool &      theSubFailed,
2166                                           std::vector<SMESH_subMesh*>& theSubs)
2167 {
2168   theSubComputed = SubMeshesComputed( & theSubFailed );
2169
2170   TopoDS_Shape mainShape = _father->GetMeshDS()->ShapeToMesh();
2171
2172   if ( mainShape.IsSame( _subShape ))
2173     return _subShape;
2174
2175   const bool skipAuxHyps = false;
2176   list<const SMESHDS_Hypothesis*> usedHyps =
2177     theAlgo->GetUsedHypothesis( *_father, _subShape, skipAuxHyps ); // copy
2178   std::list < TopoDS_Shape >  assiShapes = theAlgo->GetAssignedShapes();
2179
2180   // put in a compound all shapes with the same hypothesis assigned
2181   // and a good ComputeState
2182
2183   TopoDS_Compound aCompound;
2184   BRep_Builder aBuilder;
2185   aBuilder.MakeCompound( aCompound );
2186
2187   theSubs.clear();
2188
2189   SMESH_subMeshIteratorPtr smIt = _father->GetSubMesh( mainShape )->getDependsOnIterator(false);
2190   while ( smIt->more() )
2191   {
2192     SMESH_subMesh* subMesh = smIt->next();
2193     const TopoDS_Shape&  S = subMesh->_subShape;
2194
2195     if ( S.ShapeType() != this->_subShape.ShapeType() ){
2196       continue;
2197     }
2198     if ( _allowedSubShapes && !_allowedSubShapes->IsEmpty() && !_allowedSubShapes->Contains( S )){
2199       continue;
2200     }
2201     if ( subMesh == this )
2202     {
2203       aBuilder.Add( aCompound, S );
2204       theSubs.push_back( subMesh );
2205     }
2206     else if ( subMesh->GetComputeState() == READY_TO_COMPUTE )
2207     {
2208       SMESH_Algo* anAlgo = subMesh->GetAlgo();
2209
2210       if (( anAlgo->IsSameName( *theAlgo )) && // same algo
2211           ( anAlgo->GetUsedHypothesis( *_father, S, skipAuxHyps ) == usedHyps ) && // same hyps
2212           ( anAlgo->GetAssignedShapes() == assiShapes ) && // on same sub-shapes
2213           ( _algoShape == subMesh->_algoShape ))
2214       {
2215         aBuilder.Add( aCompound, S );
2216         if ( !subMesh->SubMeshesComputed() )
2217           theSubComputed = false;
2218         theSubs.push_back( subMesh );
2219       }
2220     }
2221   }
2222
2223   return theSubs.size() == 1 ? theSubs[0]->GetSubShape() : aCompound;
2224 }
2225
2226 //=======================================================================
2227 //function : getSimilarAttached
2228 //purpose  : return a hypothesis attached to theShape.
2229 //           If theHyp is provided, similar but not same hypotheses
2230 //           is returned; else only applicable ones having theHypType
2231 //           is returned
2232 //=======================================================================
2233
2234 const SMESH_Hypothesis* SMESH_subMesh::getSimilarAttached(const TopoDS_Shape&      theShape,
2235                                                           const SMESH_Hypothesis * theHyp,
2236                                                           const int                theHypType)
2237 {
2238   SMESH_HypoFilter hypoKind;
2239   hypoKind.Init( hypoKind.HasType( theHyp ? theHyp->GetType() : theHypType ));
2240   if ( theHyp ) {
2241     hypoKind.And   ( hypoKind.HasDim( theHyp->GetDim() ));
2242     hypoKind.AndNot( hypoKind.Is( theHyp ));
2243     if ( theHyp->IsAuxiliary() )
2244       hypoKind.And( hypoKind.HasName( theHyp->GetName() ));
2245     else
2246       hypoKind.AndNot( hypoKind.IsAuxiliary());
2247   }
2248   else {
2249     hypoKind.And( hypoKind.IsApplicableTo( theShape ));
2250   }
2251
2252   return _father->GetHypothesis( theShape, hypoKind, false );
2253 }
2254
2255 //=======================================================================
2256 //function : CheckConcurrentHypothesis
2257 //purpose  : check if there are several applicable hypothesis attached to
2258 //           ancestors
2259 //=======================================================================
2260
2261 SMESH_Hypothesis::Hypothesis_Status
2262   SMESH_subMesh::CheckConcurrentHypothesis( SMESH_Hypothesis* theHypothesis)
2263 {
2264   // is there local hypothesis on me?
2265   if ( getSimilarAttached( _subShape, theHypothesis ) )
2266     return SMESH_Hypothesis::HYP_OK;
2267
2268
2269   TopoDS_Shape aPrevWithHyp;
2270   const SMESH_Hypothesis* aPrevHyp = 0;
2271   TopTools_ListIteratorOfListOfShape it( _father->GetAncestors( _subShape ));
2272   for (; it.More(); it.Next())
2273   {
2274     const TopoDS_Shape& ancestor = it.Value();
2275     const SMESH_Hypothesis* hyp = getSimilarAttached( ancestor, theHypothesis );
2276     if ( hyp )
2277     {
2278       if ( aPrevWithHyp.IsNull() || aPrevWithHyp.IsSame( ancestor ))
2279       {
2280         aPrevWithHyp = ancestor;
2281         aPrevHyp     = hyp;
2282       }
2283       else if ( aPrevWithHyp.ShapeType() == ancestor.ShapeType() && aPrevHyp != hyp )
2284         return SMESH_Hypothesis::HYP_CONCURRENT;
2285       else
2286         return SMESH_Hypothesis::HYP_OK;
2287     }
2288   }
2289   return SMESH_Hypothesis::HYP_OK;
2290 }
2291
2292 //================================================================================
2293 /*!
2294  * \brief Constructor of OwnListenerData
2295  */
2296 //================================================================================
2297
2298 SMESH_subMesh::OwnListenerData::OwnListenerData( SMESH_subMesh* sm, EventListener* el):
2299   mySubMesh( sm ),
2300   myMeshID( sm ? sm->GetFather()->GetId() : -1 ),
2301   mySubMeshID( sm ? sm->GetId() : -1 ),
2302   myListener( el )
2303 {
2304 }
2305
2306 //================================================================================
2307 /*!
2308  * \brief Sets an event listener and its data to a submesh
2309  * \param listener - the listener to store
2310  * \param data - the listener data to store
2311  * \param where - the submesh to store the listener and it's data
2312  *
2313  * It remembers the submesh where it puts the listener in order to delete
2314  * them when HYP_OK algo_state is lost
2315  * After being set, event listener is notified on each event of where submesh.
2316  */
2317 //================================================================================
2318
2319 void SMESH_subMesh::SetEventListener(EventListener*     listener,
2320                                      EventListenerData* data,
2321                                      SMESH_subMesh*     where)
2322 {
2323   if ( listener && where ) {
2324     where->setEventListener( listener, data );
2325     _ownListeners.push_back( OwnListenerData( where, listener ));
2326   }
2327 }
2328
2329 //================================================================================
2330 /*!
2331  * \brief Sets an event listener and its data to a submesh
2332  * \param listener - the listener to store
2333  * \param data - the listener data to store
2334  *
2335  * After being set, event listener is notified on each event of a submesh.
2336  */
2337 //================================================================================
2338
2339 void SMESH_subMesh::setEventListener(EventListener*     listener,
2340                                      EventListenerData* data)
2341 {
2342   map< EventListener*, EventListenerData* >::iterator l_d =
2343     _eventListeners.find( listener );
2344   if ( l_d != _eventListeners.end() ) {
2345     EventListenerData* curData = l_d->second;
2346     l_d->second = data;
2347     if ( curData && curData != data && curData->IsDeletable() )
2348       delete curData;
2349   }
2350   else
2351   {
2352     for ( l_d = _eventListeners.begin(); l_d != _eventListeners.end(); ++l_d )
2353       if ( listener->GetName() == l_d->first->GetName() )
2354       {
2355         EventListenerData* curData = l_d->second;
2356         l_d->second = 0;
2357         if ( curData && curData != data && curData->IsDeletable() )
2358           delete curData;
2359         if ( l_d->first != listener && l_d->first->IsDeletable() )
2360           delete l_d->first;
2361         _eventListeners.erase( l_d );
2362         break;
2363       }
2364     _eventListeners.insert( make_pair( listener, data ));
2365   }
2366 }
2367
2368 //================================================================================
2369 /*!
2370  * \brief Return an event listener data
2371  * \param listener - the listener whose data is
2372  * \param myOwn - if \c true, returns a listener set by this sub-mesh,
2373  *        else returns a listener listening to events of this sub-mesh
2374  * \retval EventListenerData* - found data, maybe NULL
2375  */
2376 //================================================================================
2377
2378 EventListenerData* SMESH_subMesh::GetEventListenerData(EventListener* listener,
2379                                                        const bool     myOwn) const
2380 {
2381   if ( myOwn )
2382   {
2383     list< OwnListenerData >::const_iterator d;
2384     for ( d = _ownListeners.begin(); d != _ownListeners.end(); ++d )
2385     {
2386       if ( d->myListener == listener && _father->MeshExists( d->myMeshID ))
2387         return d->mySubMesh->GetEventListenerData( listener, !myOwn );
2388     }
2389   }
2390   else
2391   {
2392     map< EventListener*, EventListenerData* >::const_iterator l_d =
2393       _eventListeners.find( listener );
2394     if ( l_d != _eventListeners.end() )
2395       return l_d->second;
2396   }
2397   return 0;
2398 }
2399
2400 //================================================================================
2401 /*!
2402  * \brief Return an event listener data
2403  * \param listenerName - the listener name
2404  * \param myOwn - if \c true, returns a listener set by this sub-mesh,
2405  *        else returns a listener listening to events of this sub-mesh
2406  * \retval EventListenerData* - found data, maybe NULL
2407  */
2408 //================================================================================
2409
2410 EventListenerData* SMESH_subMesh::GetEventListenerData(const string& listenerName,
2411                                                        const bool    myOwn) const
2412 {
2413   if ( myOwn )
2414   {
2415     list< OwnListenerData >::const_iterator d;
2416     for ( d = _ownListeners.begin(); d != _ownListeners.end(); ++d )
2417     {
2418       if ( _father->MeshExists( d->myMeshID ) && listenerName == d->myListener->GetName())
2419         return d->mySubMesh->GetEventListenerData( listenerName, !myOwn );
2420     }
2421   }
2422   else
2423   {
2424     map< EventListener*, EventListenerData* >::const_iterator l_d = _eventListeners.begin();
2425     for ( ; l_d != _eventListeners.end(); ++l_d )
2426       if ( listenerName == l_d->first->GetName() )
2427         return l_d->second;
2428   }
2429   return 0;
2430 }
2431
2432 //================================================================================
2433 /*!
2434  * \brief Notify stored event listeners on the occurred event
2435  * \param event - algo_event or compute_event itself
2436  * \param eventType - algo_event or compute_event
2437  * \param hyp - hypothesis, if eventType is algo_event
2438  */
2439 //================================================================================
2440
2441 void SMESH_subMesh::notifyListenersOnEvent( const int         event,
2442                                             const event_type  eventType,
2443                                             SMESH_Hypothesis* hyp)
2444 {
2445   list< pair< EventListener*, EventListenerData* > > eventListeners( _eventListeners.begin(),
2446                                                                      _eventListeners.end());
2447   list< pair< EventListener*, EventListenerData* > >::iterator l_d = eventListeners.begin();
2448   for ( ; l_d != eventListeners.end(); ++l_d )
2449   {
2450     std::pair< EventListener*, EventListenerData* > li_da = *l_d;
2451     if ( !_eventListeners.count( li_da.first )) continue;
2452
2453     if ( li_da.first->myBusySM.insert( this ).second )
2454     {
2455       const bool isDeletable = li_da.first->IsDeletable();
2456
2457       li_da.first->ProcessEvent( event, eventType, this, li_da.second, hyp );
2458
2459       if ( !isDeletable || _eventListeners.count( li_da.first ))
2460         li_da.first->myBusySM.erase( this ); // a listener is hopefully not dead
2461     }
2462   }
2463 }
2464
2465 //================================================================================
2466 /*!
2467  * \brief Unregister the listener and delete listener's data
2468  * \param listener - the event listener
2469  */
2470 //================================================================================
2471
2472 void SMESH_subMesh::DeleteEventListener(EventListener* listener)
2473 {
2474   map< EventListener*, EventListenerData* >::iterator l_d =
2475     _eventListeners.find( listener );
2476   if ( l_d != _eventListeners.end() && l_d->first )
2477   {
2478     if ( l_d->second && l_d->second->IsDeletable() )
2479     {
2480       delete l_d->second;
2481     }
2482     l_d->first->myBusySM.erase( this );
2483     if ( l_d->first->IsDeletable() )
2484     {
2485       l_d->first->BeforeDelete( this, l_d->second );
2486       delete l_d->first;
2487     }
2488     _eventListeners.erase( l_d );
2489   }
2490 }
2491
2492 //================================================================================
2493 /*!
2494  * \brief Delete event listeners depending on algo of this submesh
2495  */
2496 //================================================================================
2497
2498 void SMESH_subMesh::deleteOwnListeners()
2499 {
2500   list< OwnListenerData >::iterator d;
2501   for ( d = _ownListeners.begin(); d != _ownListeners.end(); ++d )
2502   {
2503     SMESH_Mesh* mesh = _father->FindMesh( d->myMeshID );
2504     if ( !mesh || !mesh->GetSubMeshContaining( d->mySubMeshID ))
2505       continue;
2506     d->mySubMesh->DeleteEventListener( d->myListener );
2507   }
2508   _ownListeners.clear();
2509 }
2510
2511 //=======================================================================
2512 //function : loadDependentMeshes
2513 //purpose  : loads dependent meshes on SUBMESH_LOADED event
2514 //=======================================================================
2515
2516 void SMESH_subMesh::loadDependentMeshes()
2517 {
2518   list< OwnListenerData >::iterator d;
2519   for ( d = _ownListeners.begin(); d != _ownListeners.end(); ++d )
2520     if ( _father != d->mySubMesh->_father &&
2521          _father->FindMesh( d->myMeshID ))
2522       d->mySubMesh->_father->Load();
2523
2524   // map< EventListener*, EventListenerData* >::iterator l_d = _eventListeners.begin();
2525   // for ( ; l_d != _eventListeners.end(); ++l_d )
2526   //   if ( l_d->second )
2527   //   {
2528   //     const list<SMESH_subMesh*>& smList = l_d->second->mySubMeshes;
2529   //     list<SMESH_subMesh*>::const_iterator sm = smList.begin();
2530   //     for ( ; sm != smList.end(); ++sm )
2531   //       if ( _father != (*sm)->_father )
2532   //         (*sm)->_father->Load();
2533   //   }
2534 }
2535
2536 //================================================================================
2537 /*!
2538  * \brief Do something on a certain event
2539  * \param event - algo_event or compute_event itself
2540  * \param eventType - algo_event or compute_event
2541  * \param subMesh - the submesh where the event occurs
2542  * \param data - listener data stored in the subMesh
2543  * \param hyp - hypothesis, if eventType is algo_event
2544  *
2545  * The base implementation translates CLEAN event to the subMesh
2546  * stored in listener data. Also it sends SUBMESH_COMPUTED event in case of
2547  * successful COMPUTE event.
2548  */
2549 //================================================================================
2550
2551 void SMESH_subMeshEventListener::ProcessEvent(const int          event,
2552                                               const int          eventType,
2553                                               SMESH_subMesh*     subMesh,
2554                                               EventListenerData* data,
2555                                               const SMESH_Hypothesis*  /*hyp*/)
2556 {
2557   if ( data && !data->mySubMeshes.empty() &&
2558        eventType == SMESH_subMesh::COMPUTE_EVENT)
2559   {
2560     ASSERT( data->mySubMeshes.front() != subMesh );
2561     list<SMESH_subMesh*>::iterator smIt = data->mySubMeshes.begin();
2562     list<SMESH_subMesh*>::iterator smEnd = data->mySubMeshes.end();
2563     switch ( event ) {
2564     case SMESH_subMesh::CLEAN:
2565       for ( ; smIt != smEnd; ++ smIt)
2566         (*smIt)->ComputeStateEngine( SMESH_subMesh::compute_event( event ));
2567       break;
2568     case SMESH_subMesh::COMPUTE:
2569     case SMESH_subMesh::COMPUTE_SUBMESH:
2570       if ( subMesh->GetComputeState() == SMESH_subMesh::COMPUTE_OK )
2571         for ( ; smIt != smEnd; ++ smIt)
2572           (*smIt)->ComputeStateEngine( SMESH_subMesh::SUBMESH_COMPUTED );
2573       break;
2574     default:;
2575     }
2576   }
2577 }
2578
2579 namespace {
2580
2581   //================================================================================
2582   /*!
2583    * \brief Iterator over submeshes and optionally prepended or appended one
2584    */
2585   //================================================================================
2586
2587   struct _Iterator : public SMDS_Iterator<SMESH_subMesh*>
2588   {
2589     _Iterator(SMDS_Iterator<SMESH_subMesh*>* subIt,
2590               SMESH_subMesh*                 prepend,
2591               SMESH_subMesh*                 append): myAppend(append), myIt(subIt)
2592     {
2593       myCur = prepend ? prepend : myIt->more() ? myIt->next() : append;
2594       if ( myCur == append ) append = 0;
2595     }
2596     /// Return true if and only if there are other object in this iterator
2597     virtual bool more()
2598     {
2599       return myCur;
2600     }
2601     /// Return the current object and step to the next one
2602     virtual SMESH_subMesh* next()
2603     {
2604       SMESH_subMesh* res = myCur;
2605       if ( myIt->more() ) { myCur = myIt->next(); }
2606       else                { myCur = myAppend; myAppend = 0; }
2607       return res;
2608     }
2609     /// ~
2610     ~_Iterator()
2611     { delete myIt; }
2612     ///
2613     SMESH_subMesh                 *myAppend, *myCur;
2614     SMDS_Iterator<SMESH_subMesh*> *myIt;
2615   };
2616 }
2617
2618 //================================================================================
2619 /*!
2620  * \brief Return iterator on the submeshes this one depends on
2621  *  \param includeSelf - this submesh to be returned also
2622  *  \param reverse - if true, complex shape submeshes go first
2623  */
2624 //================================================================================
2625
2626 SMESH_subMeshIteratorPtr SMESH_subMesh::getDependsOnIterator(const bool includeSelf,
2627                                                              const bool reverse) const
2628 {
2629   SMESH_subMesh *me = (SMESH_subMesh*) this;
2630   SMESH_subMesh *prepend=0, *append=0;
2631   if ( includeSelf ) {
2632     if ( reverse ) prepend = me;
2633     else            append = me;
2634   }
2635   typedef map < int, SMESH_subMesh * > TMap;
2636   if ( reverse )
2637   {
2638     return SMESH_subMeshIteratorPtr
2639       ( new _Iterator( new SMDS_mapReverseIterator<TMap>( me->DependsOn() ), prepend, append ));
2640   }
2641   {
2642     return SMESH_subMeshIteratorPtr
2643       ( new _Iterator( new SMDS_mapIterator<TMap>( me->DependsOn() ), prepend, append ));
2644   }
2645 }
2646
2647 //================================================================================
2648 /*!
2649  * \brief Returns ancestor sub-meshes. Finds them if not yet found.
2650  */
2651 //================================================================================
2652
2653 const std::vector< SMESH_subMesh * > & SMESH_subMesh::GetAncestors() const
2654 {
2655   if ( _ancestors.empty() &&
2656        !_subShape.IsSame( _father->GetShapeToMesh() ))
2657   {
2658     const TopTools_ListOfShape& ancShapes = _father->GetAncestors( _subShape );
2659
2660     SMESH_subMesh* me = const_cast< SMESH_subMesh* >( this );
2661     me->_ancestors.reserve( ancShapes.Extent() );
2662
2663     // assure that all sub-meshes exist
2664     TopoDS_Shape mainShape = _father->GetShapeToMesh();
2665     if ( !mainShape.IsNull() )
2666       _father->GetSubMesh( mainShape )->DependsOn();
2667
2668     TopTools_MapOfShape map;
2669
2670     for ( TopTools_ListIteratorOfListOfShape it( ancShapes ); it.More(); it.Next() )
2671       if ( SMESH_subMesh* sm = _father->GetSubMeshContaining( it.Value() ))
2672         if ( map.Add( it.Value() ))
2673           me->_ancestors.push_back( sm );
2674   }
2675
2676   return _ancestors;
2677 }
2678
2679 //================================================================================
2680 /*!
2681  * \brief Clears the vector of ancestor sub-meshes
2682  */
2683 //================================================================================
2684
2685 void SMESH_subMesh::ClearAncestors()
2686 {
2687   _ancestors.clear();
2688 }
2689
2690 //================================================================================
2691 /*!
2692  * \brief  Find common submeshes (based on shared sub-shapes with other
2693   * \param theOther submesh to check
2694   * \param theSetOfCommon set of common submesh
2695  */
2696 //================================================================================
2697
2698 bool SMESH_subMesh::FindIntersection(const SMESH_subMesh*            theOther,
2699                                      std::set<const SMESH_subMesh*>& theSetOfCommon ) const
2700 {
2701   size_t oldNb = theSetOfCommon.size();
2702
2703   // check main submeshes
2704   const map <int, SMESH_subMesh*>::const_iterator otherEnd = theOther->_mapDepend.end();
2705   if ( theOther->_mapDepend.find(this->GetId()) != otherEnd )
2706     theSetOfCommon.insert( this );
2707   if ( _mapDepend.find(theOther->GetId()) != _mapDepend.end() )
2708     theSetOfCommon.insert( theOther );
2709
2710   // check common submeshes
2711   map <int, SMESH_subMesh*>::const_iterator mapIt = _mapDepend.begin();
2712   for( ; mapIt != _mapDepend.end(); mapIt++ )
2713     if ( theOther->_mapDepend.find((*mapIt).first) != otherEnd )
2714       theSetOfCommon.insert( (*mapIt).second );
2715   return oldNb < theSetOfCommon.size();
2716 }