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