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