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