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