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