Salome HOME
22806: EDF SMESH: Regression: Prism_3D error
[modules/smesh.git] / src / SMESH / SMESH_Mesh.cxx
1 // Copyright (C) 2007-2014  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 //  File   : SMESH_Mesh.cxx
24 //  Author : Paul RASCLE, EDF
25 //  Module : SMESH
26 //
27 #include "SMESH_Mesh.hxx"
28 #include "SMESH_MesherHelper.hxx"
29 #include "SMDS_MeshVolume.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Document.hxx"
32 #include "SMESHDS_Group.hxx"
33 #include "SMESHDS_GroupOnGeom.hxx"
34 #include "SMESHDS_Script.hxx"
35 #include "SMESHDS_TSubMeshHolder.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Hypothesis.hxx"
40 #include "SMESH_subMesh.hxx"
41
42 #include "utilities.h"
43
44 #include "DriverDAT_W_SMDS_Mesh.h"
45 #include "DriverGMF_Read.hxx"
46 #include "DriverGMF_Write.hxx"
47 #include "DriverMED_R_SMESHDS_Mesh.h"
48 #include "DriverMED_W_SMESHDS_Mesh.h"
49 #include "DriverSTL_R_SMDS_Mesh.h"
50 #include "DriverSTL_W_SMDS_Mesh.h"
51 #include "DriverUNV_R_SMDS_Mesh.h"
52 #include "DriverUNV_W_SMDS_Mesh.h"
53 #ifdef WITH_CGNS
54 #include "DriverCGNS_Read.hxx"
55 #include "DriverCGNS_Write.hxx"
56 #endif
57
58 #include <GEOMUtils.hxx>
59
60 #undef _Precision_HeaderFile
61 //#include <BRepBndLib.hxx>
62 #include <BRepPrimAPI_MakeBox.hxx>
63 #include <Bnd_Box.hxx>
64 #include <TColStd_MapOfInteger.hxx>
65 #include <TopExp.hxx>
66 #include <TopExp_Explorer.hxx>
67 #include <TopTools_ListIteratorOfListOfShape.hxx>
68 #include <TopTools_ListOfShape.hxx>
69 #include <TopTools_MapOfShape.hxx>
70 #include <TopoDS_Iterator.hxx>
71
72 #include "SMESH_TryCatch.hxx" // include after OCCT headers!
73
74 #include "Utils_ExceptHandlers.hxx"
75 #ifndef WIN32
76 #include <boost/thread/thread.hpp>
77 #include <boost/bind.hpp>
78 #else 
79 #include <pthread.h> 
80 #endif
81
82 using namespace std;
83
84 // maximum stored group name length in MED file
85 #define MAX_MED_GROUP_NAME_LENGTH 80
86
87 #ifdef _DEBUG_
88 static int MYDEBUG = 0;
89 #else
90 static int MYDEBUG = 0;
91 #endif
92
93 #define cSMESH_Hyp(h) static_cast<const SMESH_Hypothesis*>(h)
94
95 typedef SMESH_HypoFilter THypType;
96
97 class SMESH_Mesh::SubMeshHolder : public SMESHDS_TSubMeshHolder< SMESH_subMesh >
98 {
99 };
100
101 //=============================================================================
102 /*!
103  * 
104  */
105 //=============================================================================
106
107 SMESH_Mesh::SMESH_Mesh(int               theLocalId, 
108                        int               theStudyId, 
109                        SMESH_Gen*        theGen,
110                        bool              theIsEmbeddedMode,
111                        SMESHDS_Document* theDocument):
112   _groupId( 0 ), _nbSubShapes( 0 )
113 {
114   MESSAGE("SMESH_Mesh::SMESH_Mesh(int localId)");
115   _id            = theLocalId;
116   _studyId       = theStudyId;
117   _gen           = theGen;
118   _myDocument    = theDocument;
119   _myMeshDS      = theDocument->NewMesh(theIsEmbeddedMode,theLocalId);
120   _isShapeToMesh = false;
121   _isAutoColor   = false;
122   _isModified    = false;
123   _shapeDiagonal = 0.0;
124   _callUp        = NULL;
125   _myMeshDS->ShapeToMesh( PseudoShape() );
126   _subMeshHolder = new SubMeshHolder;
127 }
128
129 //================================================================================
130 /*!
131  * \brief Constructor of SMESH_Mesh being a base of some descendant class
132  */
133 //================================================================================
134
135 SMESH_Mesh::SMESH_Mesh():
136   _id(-1),
137   _studyId(-1),
138   _groupId( 0 ),
139   _nbSubShapes( 0 ),
140   _isShapeToMesh( false ),
141   _myDocument( 0 ),
142   _myMeshDS( 0 ),
143   _gen( 0 ),
144   _isAutoColor( false ),
145   _isModified( false ),
146   _shapeDiagonal( 0.0 ),
147   _callUp( 0 )
148 {
149   _subMeshHolder = new SubMeshHolder;
150 }
151
152 namespace
153 {
154 #ifndef WIN32
155   void deleteMeshDS(SMESHDS_Mesh* meshDS)
156   {
157     //cout << "deleteMeshDS( " << meshDS << endl;
158     delete meshDS;
159   }
160 #else
161   static void* deleteMeshDS(void* meshDS)
162   {
163     //cout << "deleteMeshDS( " << meshDS << endl;
164     SMESHDS_Mesh* m = (SMESHDS_Mesh*)meshDS;
165     if(m) {
166       delete m;
167     }
168     return 0;
169   }
170 #endif
171 }
172
173 //=============================================================================
174 /*!
175  *
176  */
177 //=============================================================================
178
179 SMESH_Mesh::~SMESH_Mesh()
180 {
181   MESSAGE("SMESH_Mesh::~SMESH_Mesh");
182
183   // issue 0020340: EDF 1022 SMESH : Crash with FindNodeClosestTo in a second new study
184   //   Notify event listeners at least that something happens
185   if ( SMESH_subMesh * sm = GetSubMeshContaining(1))
186     sm->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
187
188   // delete groups
189   map < int, SMESH_Group * >::iterator itg;
190   for (itg = _mapGroup.begin(); itg != _mapGroup.end(); itg++) {
191     SMESH_Group *aGroup = (*itg).second;
192     delete aGroup;
193   }
194   _mapGroup.clear();
195
196   // delete sub-meshes
197   delete _subMeshHolder;
198
199   if ( _callUp) delete _callUp;
200   _callUp = 0;
201
202   // remove self from studyContext
203   if ( _gen )
204   {
205     StudyContextStruct * studyContext = _gen->GetStudyContext( _studyId );
206     studyContext->mapMesh.erase( _id );
207   }
208   if ( _myDocument )
209     _myDocument->RemoveMesh( _id );
210   _myDocument = 0;
211
212   if ( _myMeshDS ) {
213     // delete _myMeshDS, in a thread in order not to block closing a study with large meshes
214 #ifndef WIN32
215     boost::thread aThread(boost::bind( & deleteMeshDS, _myMeshDS ));
216 #else
217     pthread_t thread;
218     int result=pthread_create(&thread, NULL, deleteMeshDS, (void*)_myMeshDS);
219 #endif
220   }
221 }
222
223 //================================================================================
224 /*!
225  * \brief Return true if a mesh with given id exists
226  */
227 //================================================================================
228
229 bool SMESH_Mesh::MeshExists( int meshId ) const
230 {
231   return _myDocument ? bool( _myDocument->GetMesh( meshId )) : false;
232 }
233
234 //=============================================================================
235 /*!
236  * \brief Set geometry to be meshed
237  */
238 //=============================================================================
239
240 void SMESH_Mesh::ShapeToMesh(const TopoDS_Shape & aShape)
241 {
242   if(MYDEBUG) MESSAGE("SMESH_Mesh::ShapeToMesh");
243
244   if ( !aShape.IsNull() && _isShapeToMesh ) {
245     if ( aShape.ShapeType() != TopAbs_COMPOUND && // group contents is allowed to change
246          _myMeshDS->ShapeToMesh().ShapeType() != TopAbs_COMPOUND )
247       throw SALOME_Exception(LOCALIZED ("a shape to mesh has already been defined"));
248   }
249   // clear current data
250   if ( !_myMeshDS->ShapeToMesh().IsNull() )
251   {
252     // removal of a shape to mesh, delete objects referring to sub-shapes:
253     // - sub-meshes
254     _subMeshHolder->DeleteAll();
255     //  - groups on geometry
256     map <int, SMESH_Group *>::iterator i_gr = _mapGroup.begin();
257     while ( i_gr != _mapGroup.end() ) {
258       if ( dynamic_cast<SMESHDS_GroupOnGeom*>( i_gr->second->GetGroupDS() )) {
259         _myMeshDS->RemoveGroup( i_gr->second->GetGroupDS() );
260         delete i_gr->second;
261         _mapGroup.erase( i_gr++ );
262       }
263       else
264         i_gr++;
265     }
266     _mapAncestors.Clear();
267
268     // clear SMESHDS
269     TopoDS_Shape aNullShape;
270     _myMeshDS->ShapeToMesh( aNullShape );
271
272     _shapeDiagonal = 0.0;
273   }
274
275   // set a new geometry
276   if ( !aShape.IsNull() )
277   {
278     _myMeshDS->ShapeToMesh(aShape);
279     _isShapeToMesh = true;
280     _nbSubShapes = _myMeshDS->MaxShapeIndex();
281
282     // fill map of ancestors
283     fillAncestorsMap(aShape);
284   }
285   else
286   {
287     _isShapeToMesh = false;
288     _shapeDiagonal = 0.0;
289     _myMeshDS->ShapeToMesh( PseudoShape() );
290   }
291   _isModified = false;
292 }
293
294 //=======================================================================
295 /*!
296  * \brief Return geometry to be meshed. (It may be a PseudoShape()!)
297  */
298 //=======================================================================
299
300 TopoDS_Shape SMESH_Mesh::GetShapeToMesh() const
301 {
302   return _myMeshDS->ShapeToMesh();
303 }
304
305 //=======================================================================
306 /*!
307  * \brief Return a solid which is returned by GetShapeToMesh() if
308  *        a real geometry to be meshed was not set
309  */
310 //=======================================================================
311
312 const TopoDS_Solid& SMESH_Mesh::PseudoShape()
313 {
314   static TopoDS_Solid aSolid;
315   if ( aSolid.IsNull() )
316   {
317     aSolid = BRepPrimAPI_MakeBox(1,1,1);
318   }
319   return aSolid;
320 }
321
322 //=======================================================================
323 /*!
324  * \brief Return diagonal size of bounding box of a shape
325  */
326 //=======================================================================
327
328 double SMESH_Mesh::GetShapeDiagonalSize(const TopoDS_Shape & aShape)
329 {
330   if ( !aShape.IsNull() ) {
331     Bnd_Box Box;
332     GEOMUtils::PreciseBoundingBox(aShape, Box);
333     if ( !Box.IsVoid() )
334       return sqrt( Box.SquareExtent() );
335   }
336   return 0;
337 }
338
339 //=======================================================================
340 /*!
341  * \brief Return diagonal size of bounding box of shape to mesh
342  */
343 //=======================================================================
344
345 double SMESH_Mesh::GetShapeDiagonalSize() const
346 {
347   if ( _shapeDiagonal == 0. && _isShapeToMesh )
348     const_cast<SMESH_Mesh*>(this)->_shapeDiagonal = GetShapeDiagonalSize( GetShapeToMesh() );
349
350   return _shapeDiagonal;
351 }
352
353 //================================================================================
354 /*!
355  * \brief Load mesh from study file
356  */
357 //================================================================================
358
359 void SMESH_Mesh::Load()
360 {
361   if (_callUp)
362     _callUp->Load();
363 }
364
365 //=======================================================================
366 /*!
367  * \brief Remove all nodes and elements
368  */
369 //=======================================================================
370
371 void SMESH_Mesh::Clear()
372 {
373   if ( HasShapeToMesh() ) // remove all nodes and elements
374   {
375     // clear mesh data
376     _myMeshDS->ClearMesh();
377
378     // update compute state of submeshes
379     if ( SMESH_subMesh *sm = GetSubMeshContaining( GetShapeToMesh() ) )
380     {
381       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
382       sm->ComputeSubMeshStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
383       sm->ComputeStateEngine( SMESH_subMesh::CLEAN ); // for event listeners (issue 0020918)
384       sm->ComputeSubMeshStateEngine( SMESH_subMesh::CLEAN );
385     }
386   }
387   else // remove only nodes/elements computed by algorithms
388   {
389     if ( SMESH_subMesh *sm = GetSubMeshContaining( GetShapeToMesh() ) )
390     {
391       sm->ComputeStateEngine( SMESH_subMesh::CLEAN );
392       sm->ComputeSubMeshStateEngine( SMESH_subMesh::CLEAN );
393       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
394       sm->ComputeSubMeshStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
395     }
396   }
397   _isModified = false;
398 }
399
400 //=======================================================================
401 /*!
402  * \brief Remove all nodes and elements of indicated shape
403  */
404 //=======================================================================
405
406 void SMESH_Mesh::ClearSubMesh(const int theShapeId)
407 {
408   // clear sub-meshes; get ready to re-compute as a side-effect 
409   if ( SMESH_subMesh *sm = GetSubMeshContaining( theShapeId ) )
410   {
411     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true,
412                                                              /*complexShapeFirst=*/false);
413     while ( smIt->more() )
414     {
415       sm = smIt->next();
416       TopAbs_ShapeEnum shapeType = sm->GetSubShape().ShapeType();      
417       if ( shapeType == TopAbs_VERTEX || shapeType < TopAbs_SOLID )
418         // all other shapes depends on vertices so they are already cleaned
419         sm->ComputeStateEngine( SMESH_subMesh::CLEAN );
420       // to recompute even if failed
421       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
422     }
423   }
424 }
425
426 //=======================================================================
427 //function : UNVToMesh
428 //purpose  : 
429 //=======================================================================
430
431 int SMESH_Mesh::UNVToMesh(const char* theFileName)
432 {
433   if(MYDEBUG) MESSAGE("UNVToMesh - theFileName = "<<theFileName);
434   if(_isShapeToMesh)
435     throw SALOME_Exception(LOCALIZED("a shape to mesh has already been defined"));
436   _isShapeToMesh = false;
437   DriverUNV_R_SMDS_Mesh myReader;
438   myReader.SetMesh(_myMeshDS);
439   myReader.SetFile(theFileName);
440   myReader.SetMeshId(-1);
441   myReader.Perform();
442   if(MYDEBUG){
443     MESSAGE("UNVToMesh - _myMeshDS->NbNodes() = "<<_myMeshDS->NbNodes());
444     MESSAGE("UNVToMesh - _myMeshDS->NbEdges() = "<<_myMeshDS->NbEdges());
445     MESSAGE("UNVToMesh - _myMeshDS->NbFaces() = "<<_myMeshDS->NbFaces());
446     MESSAGE("UNVToMesh - _myMeshDS->NbVolumes() = "<<_myMeshDS->NbVolumes());
447   }
448   SMDS_MeshGroup* aGroup = (SMDS_MeshGroup*) myReader.GetGroup();
449   if (aGroup != 0) {
450     TGroupNamesMap aGroupNames = myReader.GetGroupNamesMap();
451     //const TGroupIdMap& aGroupId = myReader.GetGroupIdMap();
452     aGroup->InitSubGroupsIterator();
453     while (aGroup->MoreSubGroups()) {
454       SMDS_MeshGroup* aSubGroup = (SMDS_MeshGroup*) aGroup->NextSubGroup();
455       string aName = aGroupNames[aSubGroup];
456       int aId;
457
458       SMESH_Group* aSMESHGroup = AddGroup( aSubGroup->GetType(), aName.c_str(), aId );
459       if ( aSMESHGroup ) {
460         if(MYDEBUG) MESSAGE("UNVToMesh - group added: "<<aName);      
461         SMESHDS_Group* aGroupDS = dynamic_cast<SMESHDS_Group*>( aSMESHGroup->GetGroupDS() );
462         if ( aGroupDS ) {
463           aGroupDS->SetStoreName(aName.c_str());
464           aSubGroup->InitIterator();
465           const SMDS_MeshElement* aElement = 0;
466           while (aSubGroup->More()) {
467             aElement = aSubGroup->Next();
468             if (aElement) {
469               aGroupDS->SMDSGroup().Add(aElement);
470             }
471           }
472           if (aElement)
473             aGroupDS->SetType(aElement->GetType());
474         }
475       }
476     }
477   }
478   return 1;
479 }
480
481 //=======================================================================
482 //function : MEDToMesh
483 //purpose  : 
484 //=======================================================================
485
486 int SMESH_Mesh::MEDToMesh(const char* theFileName, const char* theMeshName)
487 {
488   if(MYDEBUG) MESSAGE("MEDToMesh - theFileName = "<<theFileName<<", mesh name = "<<theMeshName);
489   if(_isShapeToMesh)
490     throw SALOME_Exception(LOCALIZED("a shape to mesh has already been defined"));
491   _isShapeToMesh = false;
492   DriverMED_R_SMESHDS_Mesh myReader;
493   myReader.SetMesh(_myMeshDS);
494   myReader.SetMeshId(-1);
495   myReader.SetFile(theFileName);
496   myReader.SetMeshName(theMeshName);
497   Driver_Mesh::Status status = myReader.Perform();
498   if(MYDEBUG){
499     MESSAGE("MEDToMesh - _myMeshDS->NbNodes() = "<<_myMeshDS->NbNodes());
500     MESSAGE("MEDToMesh - _myMeshDS->NbEdges() = "<<_myMeshDS->NbEdges());
501     MESSAGE("MEDToMesh - _myMeshDS->NbFaces() = "<<_myMeshDS->NbFaces());
502     MESSAGE("MEDToMesh - _myMeshDS->NbVolumes() = "<<_myMeshDS->NbVolumes());
503   }
504
505   // Reading groups (sub-meshes are out of scope of MED import functionality)
506   list<TNameAndType> aGroupNames = myReader.GetGroupNamesAndTypes();
507   if(MYDEBUG) MESSAGE("MEDToMesh - Nb groups = "<<aGroupNames.size()); 
508   int anId;
509   list<TNameAndType>::iterator name_type = aGroupNames.begin();
510   for ( ; name_type != aGroupNames.end(); name_type++ ) {
511     SMESH_Group* aGroup = AddGroup( name_type->second, name_type->first.c_str(), anId );
512     if ( aGroup ) {
513       if(MYDEBUG) MESSAGE("MEDToMesh - group added: "<<name_type->first.c_str());      
514       SMESHDS_Group* aGroupDS = dynamic_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
515       if ( aGroupDS ) {
516         aGroupDS->SetStoreName( name_type->first.c_str() );
517         myReader.GetGroup( aGroupDS );
518       }
519     }
520   }
521   return (int) status;
522 }
523
524 //=======================================================================
525 //function : STLToMesh
526 //purpose  : 
527 //=======================================================================
528
529 int SMESH_Mesh::STLToMesh(const char* theFileName)
530 {
531   if(MYDEBUG) MESSAGE("STLToMesh - theFileName = "<<theFileName);
532   if(_isShapeToMesh)
533     throw SALOME_Exception(LOCALIZED("a shape to mesh has already been defined"));
534   _isShapeToMesh = false;
535   DriverSTL_R_SMDS_Mesh myReader;
536   myReader.SetMesh(_myMeshDS);
537   myReader.SetFile(theFileName);
538   myReader.SetMeshId(-1);
539   myReader.Perform();
540   if(MYDEBUG){
541     MESSAGE("STLToMesh - _myMeshDS->NbNodes() = "<<_myMeshDS->NbNodes());
542     MESSAGE("STLToMesh - _myMeshDS->NbEdges() = "<<_myMeshDS->NbEdges());
543     MESSAGE("STLToMesh - _myMeshDS->NbFaces() = "<<_myMeshDS->NbFaces());
544     MESSAGE("STLToMesh - _myMeshDS->NbVolumes() = "<<_myMeshDS->NbVolumes());
545   }
546   return 1;
547 }
548
549 //================================================================================
550 /*!
551  * \brief Reads the given mesh from the CGNS file
552  *  \param theFileName - name of the file
553  *  \retval int - Driver_Mesh::Status
554  */
555 //================================================================================
556
557 int SMESH_Mesh::CGNSToMesh(const char*  theFileName,
558                            const int    theMeshIndex,
559                            std::string& theMeshName)
560 {
561   int res = Driver_Mesh::DRS_FAIL;
562 #ifdef WITH_CGNS
563
564   DriverCGNS_Read myReader;
565   myReader.SetMesh(_myMeshDS);
566   myReader.SetFile(theFileName);
567   myReader.SetMeshId(theMeshIndex);
568   res = myReader.Perform();
569   theMeshName = myReader.GetMeshName();
570
571   // create groups
572   SynchronizeGroups();
573
574 #endif
575   return res;
576 }
577
578 //================================================================================
579 /*!
580  * \brief Fill its data by reading a GMF file
581  */
582 //================================================================================
583
584 SMESH_ComputeErrorPtr SMESH_Mesh::GMFToMesh(const char* theFileName,
585                                             bool        theMakeRequiredGroups)
586 {
587   DriverGMF_Read myReader;
588   myReader.SetMesh(_myMeshDS);
589   myReader.SetFile(theFileName);
590   myReader.SetMakeRequiredGroups( theMakeRequiredGroups );
591   myReader.Perform();
592   //theMeshName = myReader.GetMeshName();
593
594   // create groups
595   SynchronizeGroups();
596
597   return myReader.GetError();
598 }
599
600 //=============================================================================
601 /*!
602  * 
603  */
604 //=============================================================================
605
606 SMESH_Hypothesis::Hypothesis_Status
607 SMESH_Mesh::AddHypothesis(const TopoDS_Shape & aSubShape,
608                           int                  anHypId,
609                           std::string*         anError  ) throw(SALOME_Exception)
610 {
611   Unexpect aCatch(SalomeException);
612   if(MYDEBUG) MESSAGE("SMESH_Mesh::AddHypothesis");
613
614   if ( anError )
615     anError->clear();
616
617   SMESH_subMesh *subMesh = GetSubMesh(aSubShape);
618   if ( !subMesh || !subMesh->GetId())
619     return SMESH_Hypothesis::HYP_BAD_SUBSHAPE;
620
621   SMESH_Hypothesis *anHyp = GetHypothesis( anHypId );
622   if ( !anHyp )
623     throw SALOME_Exception(LOCALIZED("hypothesis does not exist"));
624
625   bool isGlobalHyp = IsMainShape( aSubShape );
626
627   // NotConformAllowed can be only global
628   if ( !isGlobalHyp )
629   {
630     // NOTE: this is not a correct way to check a name of hypothesis,
631     // there should be an attribute of hypothesis saying that it can/can't
632     // be global/local
633     string hypName = anHyp->GetName();
634     if ( hypName == "NotConformAllowed" )
635     {
636       if(MYDEBUG) MESSAGE( "Hypotesis <NotConformAllowed> can be only global" );
637       return SMESH_Hypothesis::HYP_INCOMPATIBLE;
638     }
639   }
640
641   // shape
642
643   bool isAlgo = ( anHyp->GetType() != SMESHDS_Hypothesis::PARAM_ALGO );
644   int   event = isAlgo ? SMESH_subMesh::ADD_ALGO : SMESH_subMesh::ADD_HYP;
645
646   SMESH_Hypothesis::Hypothesis_Status ret = subMesh->AlgoStateEngine(event, anHyp);
647
648   if ( anError && SMESH_Hypothesis::IsStatusFatal(ret) && subMesh->GetComputeError() )
649     *anError = subMesh->GetComputeError()->myComment;
650
651   // sub-shapes
652   if ( !SMESH_Hypothesis::IsStatusFatal(ret) &&
653        anHyp->GetDim() <= SMESH_Gen::GetShapeDim(aSubShape)) // is added on father
654   {
655     event = isAlgo ? SMESH_subMesh::ADD_FATHER_ALGO : SMESH_subMesh::ADD_FATHER_HYP;
656
657     SMESH_Hypothesis::Hypothesis_Status ret2 =
658       subMesh->SubMeshesAlgoStateEngine(event, anHyp, /*exitOnFatal=*/true);
659     if (ret2 > ret)
660     {
661       ret = ret2;
662       if ( SMESH_Hypothesis::IsStatusFatal( ret ))
663       {
664         if ( anError && subMesh->GetComputeError() )
665           *anError = subMesh->GetComputeError()->myComment;
666         // remove anHyp
667         event = isAlgo ? SMESH_subMesh::REMOVE_ALGO : SMESH_subMesh::REMOVE_HYP;
668         subMesh->AlgoStateEngine(event, anHyp);
669       }
670     }
671
672     // check concurent hypotheses on ancestors
673     if (ret < SMESH_Hypothesis::HYP_CONCURENT && !isGlobalHyp )
674     {
675       SMESH_subMeshIteratorPtr smIt = subMesh->getDependsOnIterator(false,false);
676       while ( smIt->more() ) {
677         SMESH_subMesh* sm = smIt->next();
678         if ( sm->IsApplicableHypotesis( anHyp )) {
679           ret2 = sm->CheckConcurentHypothesis( anHyp->GetType() );
680           if (ret2 > ret) {
681             ret = ret2;
682             break;
683           }
684         }
685       }
686     }
687   }
688   HasModificationsToDiscard(); // to reset _isModified flag if a mesh becomes empty
689
690   if(MYDEBUG) subMesh->DumpAlgoState(true);
691   if(MYDEBUG) SCRUTE(ret);
692   return ret;
693 }
694
695 //=============================================================================
696 /*!
697  * 
698  */
699 //=============================================================================
700
701 SMESH_Hypothesis::Hypothesis_Status
702   SMESH_Mesh::RemoveHypothesis(const TopoDS_Shape & aSubShape,
703                                int anHypId)throw(SALOME_Exception)
704 {
705   Unexpect aCatch(SalomeException);
706   if(MYDEBUG) MESSAGE("SMESH_Mesh::RemoveHypothesis");
707   
708   StudyContextStruct *sc = _gen->GetStudyContext(_studyId);
709   if (sc->mapHypothesis.find(anHypId) == sc->mapHypothesis.end())
710     throw SALOME_Exception(LOCALIZED("hypothesis does not exist"));
711   
712   SMESH_Hypothesis *anHyp = sc->mapHypothesis[anHypId];
713   if(MYDEBUG) {
714     SCRUTE(anHyp->GetType());
715   }
716   
717   // shape 
718   
719   bool isAlgo = ( !anHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO );
720   int event = isAlgo ? SMESH_subMesh::REMOVE_ALGO : SMESH_subMesh::REMOVE_HYP;
721
722   SMESH_subMesh *subMesh = GetSubMesh(aSubShape);
723
724   SMESH_Hypothesis::Hypothesis_Status ret = subMesh->AlgoStateEngine(event, anHyp);
725
726   // there may appear concurrent hyps that were covered by the removed hyp
727   if (ret < SMESH_Hypothesis::HYP_CONCURENT &&
728       subMesh->IsApplicableHypotesis( anHyp ) &&
729       subMesh->CheckConcurentHypothesis( anHyp->GetType() ) != SMESH_Hypothesis::HYP_OK)
730     ret = SMESH_Hypothesis::HYP_CONCURENT;
731
732   // sub-shapes
733   if (!SMESH_Hypothesis::IsStatusFatal(ret) &&
734       anHyp->GetDim() <= SMESH_Gen::GetShapeDim(aSubShape)) // is removed from father
735   {
736     event = isAlgo ? SMESH_subMesh::REMOVE_FATHER_ALGO : SMESH_subMesh::REMOVE_FATHER_HYP;
737
738     SMESH_Hypothesis::Hypothesis_Status ret2 =
739       subMesh->SubMeshesAlgoStateEngine(event, anHyp);
740     if (ret2 > ret) // more severe
741       ret = ret2;
742
743     // check concurent hypotheses on ancestors
744     if (ret < SMESH_Hypothesis::HYP_CONCURENT && !IsMainShape( aSubShape ) )
745     {
746       SMESH_subMeshIteratorPtr smIt = subMesh->getDependsOnIterator(false,false);
747       while ( smIt->more() ) {
748         SMESH_subMesh* sm = smIt->next();
749         if ( sm->IsApplicableHypotesis( anHyp )) {
750           ret2 = sm->CheckConcurentHypothesis( anHyp->GetType() );
751           if (ret2 > ret) {
752             ret = ret2;
753             break;
754           }
755         }
756       }
757     }
758   }
759
760   HasModificationsToDiscard(); // to reset _isModified flag if mesh become empty
761
762   if(MYDEBUG) subMesh->DumpAlgoState(true);
763   if(MYDEBUG) SCRUTE(ret);
764   return ret;
765 }
766
767 //=============================================================================
768 /*!
769  * 
770  */
771 //=============================================================================
772
773 const list<const SMESHDS_Hypothesis*>&
774 SMESH_Mesh::GetHypothesisList(const TopoDS_Shape & aSubShape) const
775   throw(SALOME_Exception)
776 {
777   return _myMeshDS->GetHypothesis(aSubShape);
778 }
779
780 //=======================================================================
781 /*!
782  * \brief Return the hypothesis assigned to the shape
783  *  \param aSubShape    - the shape to check
784  *  \param aFilter      - the hypothesis filter
785  *  \param andAncestors - flag to check hypos assigned to ancestors of the shape
786  *  \param assignedTo   - to return the shape the found hypo is assigned to
787  *  \retval SMESH_Hypothesis* - the first hypo passed through aFilter
788  */
789 //=======================================================================
790
791 const SMESH_Hypothesis * SMESH_Mesh::GetHypothesis(const TopoDS_Shape &    aSubShape,
792                                                    const SMESH_HypoFilter& aFilter,
793                                                    const bool              andAncestors,
794                                                    TopoDS_Shape*           assignedTo) const
795 {
796   return GetHypothesis( const_cast< SMESH_Mesh* >(this)->GetSubMesh( aSubShape ),
797                         aFilter, andAncestors, assignedTo );
798 }
799
800 //=======================================================================
801 /*!
802  * \brief Return the hypothesis assigned to the shape of a sub-mesh
803  *  \param aSubMesh     - the sub-mesh to check
804  *  \param aFilter      - the hypothesis filter
805  *  \param andAncestors - flag to check hypos assigned to ancestors of the shape
806  *  \param assignedTo   - to return the shape the found hypo is assigned to
807  *  \retval SMESH_Hypothesis* - the first hypo passed through aFilter
808  */
809 //=======================================================================
810
811 const SMESH_Hypothesis * SMESH_Mesh::GetHypothesis(const SMESH_subMesh *   aSubMesh,
812                                                    const SMESH_HypoFilter& aFilter,
813                                                    const bool              andAncestors,
814                                                    TopoDS_Shape*           assignedTo) const
815 {
816   if ( !aSubMesh ) return 0;
817
818   {
819     const TopoDS_Shape & aSubShape = aSubMesh->GetSubShape();
820     const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(aSubShape);
821     list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
822     for ( ; hyp != hypList.end(); hyp++ ) {
823       const SMESH_Hypothesis * h = cSMESH_Hyp( *hyp );
824       if ( aFilter.IsOk( h, aSubShape)) {
825         if ( assignedTo ) *assignedTo = aSubShape;
826         return h;
827       }
828     }
829   }
830   if ( andAncestors )
831   {
832     // user sorted submeshes of ancestors, according to stored submesh priority
833     std::vector< SMESH_subMesh * > & ancestors =
834       const_cast< std::vector< SMESH_subMesh * > & > ( aSubMesh->GetAncestors() );
835     SortByMeshOrder( ancestors );
836
837     vector<SMESH_subMesh*>::const_iterator smIt = ancestors.begin(); 
838     for ( ; smIt != ancestors.end(); smIt++ )
839     {
840       const TopoDS_Shape& curSh = (*smIt)->GetSubShape();
841       const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(curSh);
842       list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
843       for ( ; hyp != hypList.end(); hyp++ ) {
844         const SMESH_Hypothesis * h = cSMESH_Hyp( *hyp );
845         if (aFilter.IsOk( h, curSh )) {
846           if ( assignedTo ) *assignedTo = curSh;
847           return h;
848         }
849       }
850     }
851   }
852   return 0;
853 }
854
855 //================================================================================
856 /*!
857  * \brief Return hypotheses assigned to the shape
858   * \param aSubShape - the shape to check
859   * \param aFilter - the hypothesis filter
860   * \param aHypList - the list of the found hypotheses
861   * \param andAncestors - flag to check hypos assigned to ancestors of the shape
862   * \retval int - number of unique hypos in aHypList
863  */
864 //================================================================================
865
866 int SMESH_Mesh::GetHypotheses(const TopoDS_Shape &                aSubShape,
867                               const SMESH_HypoFilter&             aFilter,
868                               list <const SMESHDS_Hypothesis * >& aHypList,
869                               const bool                          andAncestors,
870                               list< TopoDS_Shape > *              assignedTo/*=0*/) const
871 {
872   return GetHypotheses( const_cast< SMESH_Mesh* >(this)->GetSubMesh( aSubShape ),
873                         aFilter, aHypList, andAncestors, assignedTo );
874 }
875
876 //================================================================================
877 /*!
878  * \brief Return hypotheses assigned to the shape of a sub-mesh
879   * \param aSubShape - the sub-mesh to check
880   * \param aFilter - the hypothesis filter
881   * \param aHypList - the list of the found hypotheses
882   * \param andAncestors - flag to check hypos assigned to ancestors of the shape
883   * \retval int - number of unique hypos in aHypList
884  */
885 //================================================================================
886
887 int SMESH_Mesh::GetHypotheses(const SMESH_subMesh *               aSubMesh,
888                               const SMESH_HypoFilter&             aFilter,
889                               list <const SMESHDS_Hypothesis * >& aHypList,
890                               const bool                          andAncestors,
891                               list< TopoDS_Shape > *              assignedTo/*=0*/) const
892 {
893   if ( !aSubMesh ) return 0;
894
895   set<string> hypTypes; // to exclude same type hypos from the result list
896   int nbHyps = 0;
897
898   // only one main hypothesis is allowed
899   bool mainHypFound = false;
900
901   // fill in hypTypes
902   list<const SMESHDS_Hypothesis*>::const_iterator hyp;
903   for ( hyp = aHypList.begin(); hyp != aHypList.end(); hyp++ ) {
904     if ( hypTypes.insert( (*hyp)->GetName() ).second )
905       nbHyps++;
906     if ( !cSMESH_Hyp(*hyp)->IsAuxiliary() )
907       mainHypFound = true;
908   }
909
910   // get hypos from aSubShape
911   {
912     const TopoDS_Shape & aSubShape = aSubMesh->GetSubShape();
913     const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(aSubShape);
914     for ( hyp = hypList.begin(); hyp != hypList.end(); hyp++ )
915     {
916       const SMESH_Hypothesis* h = cSMESH_Hyp( *hyp );
917       if (( aFilter.IsOk( h, aSubShape )) &&
918           ( h->IsAuxiliary() || !mainHypFound ) &&
919           ( h->IsAuxiliary() || hypTypes.insert( h->GetName() ).second ))
920       {
921         aHypList.push_back( *hyp );
922         nbHyps++;
923         if ( !h->IsAuxiliary() )
924           mainHypFound = true;
925         if ( assignedTo ) assignedTo->push_back( aSubShape );
926       }
927     }
928   }
929
930   // get hypos from ancestors of aSubShape
931   if ( andAncestors )
932   {
933     // user sorted submeshes of ancestors, according to stored submesh priority
934     std::vector< SMESH_subMesh * > & ancestors =
935       const_cast< std::vector< SMESH_subMesh * > & > ( aSubMesh->GetAncestors() );
936     SortByMeshOrder( ancestors );
937
938     vector<SMESH_subMesh*>::const_iterator smIt = ancestors.begin();
939     for ( ; smIt != ancestors.end(); smIt++ )
940     {
941       const TopoDS_Shape& curSh = (*smIt)->GetSubShape();
942       const list<const SMESHDS_Hypothesis*>& hypList = _myMeshDS->GetHypothesis(curSh);
943       for ( hyp = hypList.begin(); hyp != hypList.end(); hyp++ )
944       {
945         const SMESH_Hypothesis* h = cSMESH_Hyp( *hyp );
946         if (( aFilter.IsOk( h, curSh )) &&
947             ( h->IsAuxiliary() || !mainHypFound ) &&
948             ( h->IsAuxiliary() || hypTypes.insert( h->GetName() ).second ))
949         {
950           aHypList.push_back( *hyp );
951           nbHyps++;
952           if ( !h->IsAuxiliary() )
953             mainHypFound = true;
954           if ( assignedTo ) assignedTo->push_back( curSh );
955         }
956       }
957     }
958   }
959   return nbHyps;
960 }
961
962 //================================================================================
963 /*!
964  * \brief Return a hypothesis by its ID
965  */
966 //================================================================================
967
968 SMESH_Hypothesis * SMESH_Mesh::GetHypothesis(const int anHypId) const
969 {
970   StudyContextStruct *sc = _gen->GetStudyContext(_studyId);
971   if (sc->mapHypothesis.find(anHypId) == sc->mapHypothesis.end())
972     return NULL;
973
974   SMESH_Hypothesis *anHyp = sc->mapHypothesis[anHypId];
975   return anHyp;
976 }
977
978 //=============================================================================
979 /*!
980  * 
981  */
982 //=============================================================================
983
984 const list<SMESHDS_Command*> & SMESH_Mesh::GetLog() throw(SALOME_Exception)
985 {
986   Unexpect aCatch(SalomeException);
987   if(MYDEBUG) MESSAGE("SMESH_Mesh::GetLog");
988   return _myMeshDS->GetScript()->GetCommands();
989 }
990
991 //=============================================================================
992 /*!
993  * 
994  */
995 //=============================================================================
996 void SMESH_Mesh::ClearLog() throw(SALOME_Exception)
997 {
998   Unexpect aCatch(SalomeException);
999   if(MYDEBUG) MESSAGE("SMESH_Mesh::ClearLog");
1000   _myMeshDS->GetScript()->Clear();
1001 }
1002
1003 //=============================================================================
1004 /*!
1005  * Get or Create the SMESH_subMesh object implementation
1006  */
1007 //=============================================================================
1008
1009 SMESH_subMesh *SMESH_Mesh::GetSubMesh(const TopoDS_Shape & aSubShape)
1010   throw(SALOME_Exception)
1011 {
1012   int index = _myMeshDS->ShapeToIndex(aSubShape);
1013   if ( !index && aSubShape.IsNull() )
1014     return 0;
1015
1016   // for submeshes on GEOM Group
1017   if (( !index || index > _nbSubShapes ) && aSubShape.ShapeType() == TopAbs_COMPOUND ) {
1018     TopoDS_Iterator it( aSubShape );
1019     if ( it.More() )
1020     {
1021       index = _myMeshDS->AddCompoundSubmesh( aSubShape, it.Value().ShapeType() );
1022       // fill map of Ancestors
1023       while ( _nbSubShapes < index )
1024         fillAncestorsMap( _myMeshDS->IndexToShape( ++_nbSubShapes ));
1025     }
1026   }
1027   // if ( !index )
1028   //   return NULL; // neither sub-shape nor a group
1029
1030   SMESH_subMesh* aSubMesh = _subMeshHolder->Get( index );
1031   if ( !aSubMesh )
1032   {
1033     aSubMesh = new SMESH_subMesh(index, this, _myMeshDS, aSubShape);
1034     _subMeshHolder->Add( index, aSubMesh );
1035
1036     // include non-computable sub-meshes in SMESH_subMesh::_ancestors of sub-submeshes
1037     switch ( aSubShape.ShapeType() ) {
1038     case TopAbs_COMPOUND:
1039     case TopAbs_WIRE:
1040     case TopAbs_SHELL:
1041       for ( TopoDS_Iterator subIt( aSubShape ); subIt.More(); subIt.Next() )
1042       {
1043         SMESH_subMesh* sm = GetSubMesh( subIt.Value() );
1044         SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*inclideSelf=*/true);
1045         while ( smIt->more() )
1046           smIt->next()->ClearAncestors();
1047       }
1048     default:;
1049     }
1050   }
1051   return aSubMesh;
1052 }
1053
1054 //=============================================================================
1055 /*!
1056  * Get the SMESH_subMesh object implementation. Dont create it, return null
1057  * if it does not exist.
1058  */
1059 //=============================================================================
1060
1061 SMESH_subMesh *SMESH_Mesh::GetSubMeshContaining(const TopoDS_Shape & aSubShape) const
1062   throw(SALOME_Exception)
1063 {
1064   int index = _myMeshDS->ShapeToIndex(aSubShape);
1065   return GetSubMeshContaining( index );
1066 }
1067
1068 //=============================================================================
1069 /*!
1070  * Get the SMESH_subMesh object implementation. Dont create it, return null
1071  * if it does not exist.
1072  */
1073 //=============================================================================
1074
1075 SMESH_subMesh *SMESH_Mesh::GetSubMeshContaining(const int aShapeID) const
1076 throw(SALOME_Exception)
1077 {
1078   SMESH_subMesh *aSubMesh = _subMeshHolder->Get( aShapeID );
1079
1080   return aSubMesh;
1081 }
1082
1083 //================================================================================
1084 /*!
1085  * \brief Return submeshes of groups containing the given sub-shape
1086  */
1087 //================================================================================
1088
1089 list<SMESH_subMesh*>
1090 SMESH_Mesh::GetGroupSubMeshesContaining(const TopoDS_Shape & aSubShape) const
1091   throw(SALOME_Exception)
1092 {
1093   list<SMESH_subMesh*> found;
1094
1095   SMESH_subMesh * subMesh = GetSubMeshContaining(aSubShape);
1096   if ( !subMesh )
1097     return found;
1098
1099   // submeshes of groups have max IDs, so search from the map end
1100 SMESH_subMeshIteratorPtr smIt( _subMeshHolder->GetIterator( /*reverse=*/true ) );
1101   while ( smIt->more() ) {
1102     SMESH_subMesh*    sm = smIt->next();
1103     SMESHDS_SubMesh * ds = sm->GetSubMeshDS();
1104     if ( ds && ds->IsComplexSubmesh() ) {
1105       if ( SMESH_MesherHelper::IsSubShape( aSubShape, sm->GetSubShape() ))
1106       {
1107         found.push_back( sm );
1108         //break;
1109       }
1110     } else {
1111       break; // the rest sub-meshes are not those of groups
1112     }
1113   }
1114
1115   if ( found.empty() ) // maybe the main shape is a COMPOUND (issue 0021530)
1116   {
1117     if ( SMESH_subMesh * mainSM = GetSubMeshContaining(1) )
1118       if ( mainSM->GetSubShape().ShapeType() == TopAbs_COMPOUND )
1119       {
1120         TopoDS_Iterator it( mainSM->GetSubShape() );
1121         if ( it.Value().ShapeType() == aSubShape.ShapeType() &&
1122              SMESH_MesherHelper::IsSubShape( aSubShape, mainSM->GetSubShape() ))
1123           found.push_back( mainSM );
1124       }
1125   }
1126   return found;
1127 }
1128 //=======================================================================
1129 //function : IsUsedHypothesis
1130 //purpose  : Return True if anHyp is used to mesh aSubShape
1131 //=======================================================================
1132
1133 bool SMESH_Mesh::IsUsedHypothesis(SMESHDS_Hypothesis * anHyp,
1134                                   const SMESH_subMesh* aSubMesh)
1135 {
1136   SMESH_Hypothesis* hyp = static_cast<SMESH_Hypothesis*>(anHyp);
1137
1138   // check if anHyp can be used to mesh aSubMesh
1139   if ( !aSubMesh || !aSubMesh->IsApplicableHypotesis( hyp ))
1140     return false;
1141
1142   SMESH_Algo *algo = aSubMesh->GetAlgo();
1143
1144   // algorithm
1145   if (anHyp->GetType() > SMESHDS_Hypothesis::PARAM_ALGO)
1146     return ( anHyp == algo );
1147
1148   // algorithm parameter
1149   if (algo)
1150   {
1151     // look trough hypotheses used by algo
1152     const SMESH_HypoFilter* hypoKind;
1153     if (( hypoKind = algo->GetCompatibleHypoFilter( !hyp->IsAuxiliary() ))) {
1154       list <const SMESHDS_Hypothesis * > usedHyps;
1155       if ( GetHypotheses( aSubMesh, *hypoKind, usedHyps, true ))
1156         return ( find( usedHyps.begin(), usedHyps.end(), anHyp ) != usedHyps.end() );
1157     }
1158   }
1159
1160   return false;
1161 }
1162
1163 //=============================================================================
1164 /*!
1165  *
1166  */
1167 //=============================================================================
1168
1169 // const list < SMESH_subMesh * >&
1170 // SMESH_Mesh::GetSubMeshUsingHypothesis(SMESHDS_Hypothesis * anHyp)
1171 //   throw(SALOME_Exception)
1172 // {
1173 //   _subMeshesUsingHypothesisList.clear();
1174 //   SMESH_subMeshIteratorPtr smIt( _subMeshHolder->GetIterator() );
1175 //   while ( smIt->more() )
1176 //   {
1177 //     SMESH_subMesh* aSubMesh = smIt->next();
1178 //     if ( IsUsedHypothesis ( anHyp, aSubMesh ))
1179 //       _subMeshesUsingHypothesisList.push_back( aSubMesh );
1180 //   }
1181 //   return _subMeshesUsingHypothesisList;
1182 // }
1183
1184 //=======================================================================
1185 //function : NotifySubMeshesHypothesisModification
1186 //purpose  : Say all submeshes using theChangedHyp that it has been modified
1187 //=======================================================================
1188
1189 void SMESH_Mesh::NotifySubMeshesHypothesisModification(const SMESH_Hypothesis* hyp)
1190 {
1191   Unexpect aCatch(SalomeException);
1192
1193   if ( !GetMeshDS()->IsUsedHypothesis( hyp ))
1194     return;
1195
1196   if (_callUp)
1197     _callUp->HypothesisModified();
1198
1199   SMESH_Algo *algo;
1200   const SMESH_HypoFilter* compatibleHypoKind;
1201   list <const SMESHDS_Hypothesis * > usedHyps;
1202
1203   // keep sub-meshes not to miss ones whose state can change due to notifying others
1204   vector< SMESH_subMesh* > smToNotify;
1205
1206   SMESH_subMeshIteratorPtr smIt( _subMeshHolder->GetIterator() );
1207   while ( smIt->more() )
1208   {
1209     SMESH_subMesh* aSubMesh = smIt->next();
1210
1211     // if aSubMesh meshing depends on hyp,
1212     // we call aSubMesh->AlgoStateEngine( MODIF_HYP, hyp ) that causes either
1213     // 1) clearing of already computed aSubMesh or
1214     // 2) changing algo_state from MISSING_HYP to HYP_OK when parameters of hyp becomes valid,
1215     // other possible changes are not interesting. (IPAL0052457 - assigning hyp performance pb)
1216     if ( aSubMesh->GetComputeState() != SMESH_subMesh::COMPUTE_OK &&
1217          aSubMesh->GetComputeState() != SMESH_subMesh::FAILED_TO_COMPUTE &&
1218          aSubMesh->GetAlgoState()    != SMESH_subMesh::MISSING_HYP )
1219       continue;
1220
1221     const TopoDS_Shape & aSubShape = aSubMesh->GetSubShape();
1222
1223     if (( aSubMesh->IsApplicableHypotesis( hyp )) &&
1224         ( algo = aSubMesh->GetAlgo() )            &&
1225         ( compatibleHypoKind = algo->GetCompatibleHypoFilter( !hyp->IsAuxiliary() )) &&
1226         ( compatibleHypoKind->IsOk( hyp, aSubShape )))
1227     {
1228       // check if hyp is used by algo
1229       usedHyps.clear();
1230       if ( GetHypotheses( aSubMesh, *compatibleHypoKind, usedHyps, true ) &&
1231            find( usedHyps.begin(), usedHyps.end(), hyp ) != usedHyps.end() )
1232       {
1233         smToNotify.push_back( aSubMesh );
1234       }
1235     }
1236   }
1237
1238   for ( size_t i = 0; i < smToNotify.size(); ++i )
1239   {
1240     smToNotify[i]->AlgoStateEngine(SMESH_subMesh::MODIF_HYP,
1241                                    const_cast< SMESH_Hypothesis*>( hyp ));
1242   }
1243
1244   HasModificationsToDiscard(); // to reset _isModified flag if mesh becomes empty
1245   GetMeshDS()->Modified();
1246 }
1247
1248 //=============================================================================
1249 /*!
1250  *  Auto color functionality
1251  */
1252 //=============================================================================
1253 void SMESH_Mesh::SetAutoColor(bool theAutoColor) throw(SALOME_Exception)
1254 {
1255   Unexpect aCatch(SalomeException);
1256   _isAutoColor = theAutoColor;
1257 }
1258
1259 bool SMESH_Mesh::GetAutoColor() throw(SALOME_Exception)
1260 {
1261   Unexpect aCatch(SalomeException);
1262   return _isAutoColor;
1263 }
1264
1265 //=======================================================================
1266 //function : SetIsModified
1267 //purpose  : Set the flag meaning that the mesh has been edited "manually"
1268 //=======================================================================
1269
1270 void SMESH_Mesh::SetIsModified(bool isModified)
1271 {
1272   _isModified = isModified;
1273
1274   if ( _isModified )
1275     // check if mesh becomes empty as result of modification
1276     HasModificationsToDiscard();
1277 }
1278
1279 //=======================================================================
1280 //function : HasModificationsToDiscard
1281 //purpose  : Return true if the mesh has been edited since a total re-compute
1282 //           and those modifications may prevent successful partial re-compute.
1283 //           As a side effect reset _isModified flag if mesh is empty
1284 //issue    : 0020693
1285 //=======================================================================
1286
1287 bool SMESH_Mesh::HasModificationsToDiscard() const
1288 {
1289   if ( ! _isModified )
1290     return false;
1291
1292   // return true if the next Compute() will be partial and
1293   // existing but changed elements may prevent successful re-compute
1294   bool hasComputed = false, hasNotComputed = false;
1295 SMESH_subMeshIteratorPtr smIt( _subMeshHolder->GetIterator() );
1296   while ( smIt->more() )
1297   {
1298     const SMESH_subMesh* aSubMesh = smIt->next();
1299     switch ( aSubMesh->GetSubShape().ShapeType() )
1300     {
1301     case TopAbs_EDGE:
1302     case TopAbs_FACE:
1303     case TopAbs_SOLID:
1304       if ( aSubMesh->IsMeshComputed() )
1305         hasComputed = true;
1306       else
1307         hasNotComputed = true;
1308       if ( hasComputed && hasNotComputed)
1309         return true;
1310     }
1311   }
1312   if ( NbNodes() < 1 )
1313     const_cast<SMESH_Mesh*>(this)->_isModified = false;
1314
1315   return false;
1316 }
1317
1318 //================================================================================
1319 /*!
1320  * \brief Check if any groups of the same type have equal names
1321  */
1322 //================================================================================
1323
1324 bool SMESH_Mesh::HasDuplicatedGroupNamesMED()
1325 {
1326   //set<string> aGroupNames; // Corrected for Mantis issue 0020028
1327   map< SMDSAbs_ElementType, set<string> > aGroupNames;
1328   for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ )
1329   {
1330     SMESH_Group* aGroup = it->second;
1331     SMDSAbs_ElementType aType = aGroup->GetGroupDS()->GetType();
1332     string aGroupName = aGroup->GetName();
1333     aGroupName.resize(MAX_MED_GROUP_NAME_LENGTH);
1334     if (!aGroupNames[aType].insert(aGroupName).second)
1335       return true;
1336   }
1337
1338   return false;
1339 }
1340
1341 //================================================================================
1342 /*!
1343  * \brief Export the mesh to a med file
1344  *  \param [in] file - name of the MED file
1345  *  \param [in] theMeshName - name of this mesh
1346  *  \param [in] theAutoGroups - boolean parameter for creating/not creating
1347  *              the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1348  *              the typical use is auto_groups=false.
1349  *  \param [in] theVersion - defines the version of format of MED file, that will be created
1350  *  \param [in] meshPart - mesh data to export
1351  *  \param [in] theAutoDimension - if \c true, a space dimension of a MED mesh can be either
1352      *         - 1D if all mesh nodes lie on OX coordinate axis, or
1353      *         - 2D if all mesh nodes lie on XOY coordinate plane, or
1354      *         - 3D in the rest cases.
1355      *         If \a theAutoDimension is \c false, the space dimension is always 3.
1356  *  \return int - mesh index in the file
1357  */
1358 //================================================================================
1359
1360 void SMESH_Mesh::ExportMED(const char *        file, 
1361                            const char*         theMeshName, 
1362                            bool                theAutoGroups,
1363                            int                 theVersion,
1364                            const SMESHDS_Mesh* meshPart,
1365                            bool                theAutoDimension,
1366                            bool                theAddODOnVertices)
1367   throw(SALOME_Exception)
1368 {
1369   SMESH_TRY;
1370
1371   DriverMED_W_SMESHDS_Mesh myWriter;
1372   myWriter.SetFile         ( file, MED::EVersion(theVersion) );
1373   myWriter.SetMesh         ( meshPart ? (SMESHDS_Mesh*) meshPart : _myMeshDS   );
1374   myWriter.SetAutoDimension( theAutoDimension );
1375   myWriter.AddODOnVertices ( theAddODOnVertices );
1376   if ( !theMeshName ) 
1377     myWriter.SetMeshId     ( _id         );
1378   else {
1379     myWriter.SetMeshId     ( -1          );
1380     myWriter.SetMeshName   ( theMeshName );
1381   }
1382
1383   if ( theAutoGroups ) {
1384     myWriter.AddGroupOfNodes();
1385     myWriter.AddGroupOfEdges();
1386     myWriter.AddGroupOfFaces();
1387     myWriter.AddGroupOfVolumes();
1388   }
1389
1390   // Pass groups to writer. Provide unique group names.
1391   //set<string> aGroupNames; // Corrected for Mantis issue 0020028
1392   if ( !meshPart )
1393   {
1394     map< SMDSAbs_ElementType, set<string> > aGroupNames;
1395     char aString [256];
1396     int maxNbIter = 10000; // to guarantee cycle finish
1397     for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ ) {
1398       SMESH_Group*       aGroup   = it->second;
1399       SMESHDS_GroupBase* aGroupDS = aGroup->GetGroupDS();
1400       if ( aGroupDS ) {
1401         SMDSAbs_ElementType aType = aGroupDS->GetType();
1402         string aGroupName0 = aGroup->GetName();
1403         aGroupName0.resize(MAX_MED_GROUP_NAME_LENGTH);
1404         string aGroupName = aGroupName0;
1405         for (int i = 1; !aGroupNames[aType].insert(aGroupName).second && i < maxNbIter; i++) {
1406           sprintf(&aString[0], "GR_%d_%s", i, aGroupName0.c_str());
1407           aGroupName = aString;
1408           aGroupName.resize(MAX_MED_GROUP_NAME_LENGTH);
1409         }
1410         aGroupDS->SetStoreName( aGroupName.c_str() );
1411         myWriter.AddGroup( aGroupDS );
1412       }
1413     }
1414   }
1415   // Perform export
1416   myWriter.Perform();
1417
1418   SMESH_CATCH( SMESH::throwSalomeEx );
1419 }
1420
1421 //================================================================================
1422 /*!
1423  * \brief Export the mesh to a SAUV file
1424  */
1425 //================================================================================
1426
1427 void SMESH_Mesh::ExportSAUV(const char *file, 
1428                             const char* theMeshName, 
1429                             bool theAutoGroups)
1430   throw(SALOME_Exception)
1431 {
1432   std::string medfilename(file);
1433   medfilename += ".med";
1434   std::string cmd;
1435 #ifdef WIN32
1436   cmd = "%PYTHONBIN% ";
1437 #else
1438   cmd = "python ";
1439 #endif
1440   cmd += "-c \"";
1441   cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1442   cmd += "\"";
1443   system(cmd.c_str());
1444   ExportMED(medfilename.c_str(), theMeshName, theAutoGroups, 1);
1445 #ifdef WIN32
1446   cmd = "%PYTHONBIN% ";
1447 #else
1448   cmd = "python ";
1449 #endif
1450   cmd += "-c \"";
1451   cmd += "from medutilities import convert ; convert(r'" + medfilename + "', 'MED', 'GIBI', 1, r'" + file + "')";
1452   cmd += "\"";
1453   system(cmd.c_str());
1454 #ifdef WIN32
1455   cmd = "%PYTHONBIN% ";
1456 #else
1457   cmd = "python ";
1458 #endif
1459   cmd += "-c \"";
1460   cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1461   cmd += "\"";
1462   system(cmd.c_str());
1463 }
1464
1465 //================================================================================
1466 /*!
1467  * \brief Export the mesh to a DAT file
1468  */
1469 //================================================================================
1470
1471 void SMESH_Mesh::ExportDAT(const char *        file,
1472                            const SMESHDS_Mesh* meshPart) throw(SALOME_Exception)
1473 {
1474   Unexpect aCatch(SalomeException);
1475   DriverDAT_W_SMDS_Mesh myWriter;
1476   myWriter.SetFile( file );
1477   myWriter.SetMesh( meshPart ? (SMESHDS_Mesh*) meshPart : _myMeshDS );
1478   myWriter.SetMeshId(_id);
1479   myWriter.Perform();
1480 }
1481
1482 //================================================================================
1483 /*!
1484  * \brief Export the mesh to an UNV file
1485  */
1486 //================================================================================
1487
1488 void SMESH_Mesh::ExportUNV(const char *        file,
1489                            const SMESHDS_Mesh* meshPart) throw(SALOME_Exception)
1490 {
1491   Unexpect aCatch(SalomeException);
1492   DriverUNV_W_SMDS_Mesh myWriter;
1493   myWriter.SetFile( file );
1494   myWriter.SetMesh( meshPart ? (SMESHDS_Mesh*) meshPart : _myMeshDS );
1495   myWriter.SetMeshId(_id);
1496   //  myWriter.SetGroups(_mapGroup);
1497
1498   if ( !meshPart )
1499   {
1500     for ( map<int, SMESH_Group*>::iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ ) {
1501       SMESH_Group*       aGroup   = it->second;
1502       SMESHDS_GroupBase* aGroupDS = aGroup->GetGroupDS();
1503       if ( aGroupDS ) {
1504         string aGroupName = aGroup->GetName();
1505         aGroupDS->SetStoreName( aGroupName.c_str() );
1506         myWriter.AddGroup( aGroupDS );
1507       }
1508     }
1509   }
1510   myWriter.Perform();
1511 }
1512
1513 //================================================================================
1514 /*!
1515  * \brief Export the mesh to an STL file
1516  */
1517 //================================================================================
1518
1519 void SMESH_Mesh::ExportSTL(const char *        file,
1520                            const bool          isascii,
1521                            const SMESHDS_Mesh* meshPart) throw(SALOME_Exception)
1522 {
1523   Unexpect aCatch(SalomeException);
1524   DriverSTL_W_SMDS_Mesh myWriter;
1525   myWriter.SetFile( file );
1526   myWriter.SetIsAscii( isascii );
1527   myWriter.SetMesh( meshPart ? (SMESHDS_Mesh*) meshPart : _myMeshDS);
1528   myWriter.SetMeshId(_id);
1529   myWriter.Perform();
1530 }
1531
1532 //================================================================================
1533 /*!
1534  * \brief Export the mesh to the CGNS file
1535  */
1536 //================================================================================
1537
1538 void SMESH_Mesh::ExportCGNS(const char *        file,
1539                             const SMESHDS_Mesh* meshDS)
1540 {
1541   int res = Driver_Mesh::DRS_FAIL;
1542 #ifdef WITH_CGNS
1543   DriverCGNS_Write myWriter;
1544   myWriter.SetFile( file );
1545   myWriter.SetMesh( const_cast<SMESHDS_Mesh*>( meshDS ));
1546   myWriter.SetMeshName( SMESH_Comment("Mesh_") << meshDS->GetPersistentId());
1547   res = myWriter.Perform();
1548 #endif
1549   if ( res != Driver_Mesh::DRS_OK )
1550     throw SALOME_Exception("Export failed");
1551 }
1552
1553 //================================================================================
1554 /*!
1555  * \brief Export the mesh to a GMF file
1556  */
1557 //================================================================================
1558
1559 void SMESH_Mesh::ExportGMF(const char *        file,
1560                            const SMESHDS_Mesh* meshDS,
1561                            bool                withRequiredGroups)
1562 {
1563   DriverGMF_Write myWriter;
1564   myWriter.SetFile( file );
1565   myWriter.SetMesh( const_cast<SMESHDS_Mesh*>( meshDS ));
1566   myWriter.SetExportRequiredGroups( withRequiredGroups );
1567
1568   myWriter.Perform();
1569 }
1570
1571 //================================================================================
1572 /*!
1573  * \brief Return a ratio of "compute cost" of computed sub-meshes to the whole
1574  *        "compute cost".
1575  */
1576 //================================================================================
1577
1578 double SMESH_Mesh::GetComputeProgress() const
1579 {
1580   double totalCost = 1e-100, computedCost = 0;
1581   const SMESH_subMesh* curSM = _gen->GetCurrentSubMesh();
1582
1583   // get progress of a current algo
1584   TColStd_MapOfInteger currentSubIds; 
1585   if ( curSM )
1586     if ( SMESH_Algo* algo = curSM->GetAlgo() )
1587     {
1588       int algoNotDoneCost = 0, algoDoneCost = 0;
1589       const std::vector<SMESH_subMesh*>& smToCompute = algo->SubMeshesToCompute();
1590       for ( size_t i = 0; i < smToCompute.size(); ++i )
1591       {
1592         if ( smToCompute[i]->IsEmpty() )
1593           algoNotDoneCost += smToCompute[i]->GetComputeCost();
1594         else
1595           algoDoneCost += smToCompute[i]->GetComputeCost();
1596         currentSubIds.Add( smToCompute[i]->GetId() );
1597       }
1598       double rate = 0;
1599       try
1600       {
1601         OCC_CATCH_SIGNALS;
1602         rate = algo->GetProgress();
1603       }
1604       catch (...) {
1605 #ifdef _DEBUG_
1606         cerr << "Exception in " << algo->GetName() << "::GetProgress()" << endl;
1607 #endif
1608       }
1609       if ( 0. < rate && rate < 1.001 )
1610       {
1611         computedCost += rate * ( algoDoneCost + algoNotDoneCost );
1612       }
1613       else
1614       {
1615         rate = algo->GetProgressByTic();
1616         computedCost += algoDoneCost + rate * algoNotDoneCost;
1617       }
1618       // cout << "rate: "<<rate << " algoNotDoneCost: " << algoNotDoneCost << endl;
1619     }
1620
1621   // get cost of already treated sub-meshes
1622   if ( SMESH_subMesh* mainSM = GetSubMeshContaining( 1 ))
1623   {
1624     SMESH_subMeshIteratorPtr smIt = mainSM->getDependsOnIterator(/*includeSelf=*/true);
1625     while ( smIt->more() )
1626     {
1627       const SMESH_subMesh* sm = smIt->next();
1628       const int smCost = sm->GetComputeCost();
1629       totalCost += smCost;
1630       if ( !currentSubIds.Contains( sm->GetId() ) )
1631       {
1632         if (( !sm->IsEmpty() ) ||
1633             ( sm->GetComputeState() == SMESH_subMesh::FAILED_TO_COMPUTE &&
1634               !sm->DependsOn( curSM ) ))
1635           computedCost += smCost;
1636       }
1637     }
1638   }
1639   // cout << "Total: " << totalCost
1640   //      << " computed: " << computedCost << " progress: " << computedCost / totalCost
1641   //      << " nbElems: " << GetMeshDS()->GetMeshInfo().NbElements() << endl;
1642   return computedCost / totalCost;
1643 }
1644
1645 //================================================================================
1646 /*!
1647  * \brief Return number of nodes in the mesh
1648  */
1649 //================================================================================
1650
1651 int SMESH_Mesh::NbNodes() const throw(SALOME_Exception)
1652 {
1653   Unexpect aCatch(SalomeException);
1654   return _myMeshDS->NbNodes();
1655 }
1656
1657 //================================================================================
1658 /*!
1659  * \brief  Return number of edges of given order in the mesh
1660  */
1661 //================================================================================
1662
1663 int SMESH_Mesh::Nb0DElements() const throw(SALOME_Exception)
1664 {
1665   Unexpect aCatch(SalomeException);
1666   return _myMeshDS->GetMeshInfo().Nb0DElements();
1667 }
1668
1669 //================================================================================
1670 /*!
1671  * \brief  Return number of edges of given order in the mesh
1672  */
1673 //================================================================================
1674
1675 int SMESH_Mesh::NbEdges(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1676 {
1677   Unexpect aCatch(SalomeException);
1678   return _myMeshDS->GetMeshInfo().NbEdges(order);
1679 }
1680
1681 //================================================================================
1682 /*!
1683  * \brief Return number of faces of given order in the mesh
1684  */
1685 //================================================================================
1686
1687 int SMESH_Mesh::NbFaces(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1688 {
1689   Unexpect aCatch(SalomeException);
1690   return _myMeshDS->GetMeshInfo().NbFaces(order);
1691 }
1692
1693 //================================================================================
1694 /*!
1695  * \brief Return the number of faces in the mesh
1696  */
1697 //================================================================================
1698
1699 int SMESH_Mesh::NbTriangles(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1700 {
1701   Unexpect aCatch(SalomeException);
1702   return _myMeshDS->GetMeshInfo().NbTriangles(order);
1703 }
1704
1705 //================================================================================
1706 /*!
1707  * \brief Return number of biquadratic triangles in the mesh
1708  */
1709 //================================================================================
1710
1711 int SMESH_Mesh::NbBiQuadTriangles() const throw(SALOME_Exception)
1712 {
1713   Unexpect aCatch(SalomeException);
1714   return _myMeshDS->GetMeshInfo().NbBiQuadTriangles();
1715 }
1716
1717 //================================================================================
1718 /*!
1719  * \brief Return the number nodes faces in the mesh
1720  */
1721 //================================================================================
1722
1723 int SMESH_Mesh::NbQuadrangles(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1724 {
1725   Unexpect aCatch(SalomeException);
1726   return _myMeshDS->GetMeshInfo().NbQuadrangles(order);
1727 }
1728
1729 //================================================================================
1730 /*!
1731  * \brief Return number of biquadratic quadrangles in the mesh
1732  */
1733 //================================================================================
1734
1735 int SMESH_Mesh::NbBiQuadQuadrangles() const throw(SALOME_Exception)
1736 {
1737   Unexpect aCatch(SalomeException);
1738   return _myMeshDS->GetMeshInfo().NbBiQuadQuadrangles();
1739 }
1740
1741 //================================================================================
1742 /*!
1743  * \brief Return the number of polygonal faces in the mesh
1744  */
1745 //================================================================================
1746
1747 int SMESH_Mesh::NbPolygons() const throw(SALOME_Exception)
1748 {
1749   Unexpect aCatch(SalomeException);
1750   return _myMeshDS->GetMeshInfo().NbPolygons();
1751 }
1752
1753 //================================================================================
1754 /*!
1755  * \brief Return number of volumes of given order in the mesh
1756  */
1757 //================================================================================
1758
1759 int SMESH_Mesh::NbVolumes(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1760 {
1761   Unexpect aCatch(SalomeException);
1762   return _myMeshDS->GetMeshInfo().NbVolumes(order);
1763 }
1764
1765 //================================================================================
1766 /*!
1767  * \brief  Return number of tetrahedrons of given order in the mesh
1768  */
1769 //================================================================================
1770
1771 int SMESH_Mesh::NbTetras(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1772 {
1773   Unexpect aCatch(SalomeException);
1774   return _myMeshDS->GetMeshInfo().NbTetras(order);
1775 }
1776
1777 //================================================================================
1778 /*!
1779  * \brief  Return number of hexahedrons of given order in the mesh
1780  */
1781 //================================================================================
1782
1783 int SMESH_Mesh::NbHexas(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1784 {
1785   Unexpect aCatch(SalomeException);
1786   return _myMeshDS->GetMeshInfo().NbHexas(order);
1787 }
1788
1789 //================================================================================
1790 /*!
1791  * \brief  Return number of triquadratic hexahedrons in the mesh
1792  */
1793 //================================================================================
1794
1795 int SMESH_Mesh::NbTriQuadraticHexas() const throw(SALOME_Exception)
1796 {
1797   Unexpect aCatch(SalomeException);
1798   return _myMeshDS->GetMeshInfo().NbTriQuadHexas();
1799 }
1800
1801 //================================================================================
1802 /*!
1803  * \brief  Return number of pyramids of given order in the mesh
1804  */
1805 //================================================================================
1806
1807 int SMESH_Mesh::NbPyramids(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1808 {
1809   Unexpect aCatch(SalomeException);
1810   return _myMeshDS->GetMeshInfo().NbPyramids(order);
1811 }
1812
1813 //================================================================================
1814 /*!
1815  * \brief  Return number of prisms (penthahedrons) of given order in the mesh
1816  */
1817 //================================================================================
1818
1819 int SMESH_Mesh::NbPrisms(SMDSAbs_ElementOrder order) const throw(SALOME_Exception)
1820 {
1821   Unexpect aCatch(SalomeException);
1822   return _myMeshDS->GetMeshInfo().NbPrisms(order);
1823 }
1824
1825 //================================================================================
1826 /*!
1827  * \brief  Return number of hexagonal prisms in the mesh
1828  */
1829 //================================================================================
1830
1831 int SMESH_Mesh::NbHexagonalPrisms() const throw(SALOME_Exception)
1832 {
1833   Unexpect aCatch(SalomeException);
1834   return _myMeshDS->GetMeshInfo().NbHexPrisms();
1835 }
1836
1837 //================================================================================
1838 /*!
1839  * \brief  Return number of polyhedrons in the mesh
1840  */
1841 //================================================================================
1842
1843 int SMESH_Mesh::NbPolyhedrons() const throw(SALOME_Exception)
1844 {
1845   Unexpect aCatch(SalomeException);
1846   return _myMeshDS->GetMeshInfo().NbPolyhedrons();
1847 }
1848
1849 //================================================================================
1850 /*!
1851  * \brief  Return number of ball elements in the mesh
1852  */
1853 //================================================================================
1854
1855 int SMESH_Mesh::NbBalls() const throw(SALOME_Exception)
1856 {
1857   Unexpect aCatch(SalomeException);
1858   return _myMeshDS->GetMeshInfo().NbBalls();
1859 }
1860
1861 //================================================================================
1862 /*!
1863  * \brief  Return number of submeshes in the mesh
1864  */
1865 //================================================================================
1866
1867 int SMESH_Mesh::NbSubMesh() const throw(SALOME_Exception)
1868 {
1869   Unexpect aCatch(SalomeException);
1870   return _myMeshDS->NbSubMesh();
1871 }
1872
1873 //=======================================================================
1874 //function : IsNotConformAllowed
1875 //purpose  : check if a hypothesis alowing notconform mesh is present
1876 //=======================================================================
1877
1878 bool SMESH_Mesh::IsNotConformAllowed() const
1879 {
1880   if(MYDEBUG) MESSAGE("SMESH_Mesh::IsNotConformAllowed");
1881
1882   static SMESH_HypoFilter filter( SMESH_HypoFilter::HasName( "NotConformAllowed" ));
1883   return GetHypothesis( _myMeshDS->ShapeToMesh(), filter, false );
1884 }
1885
1886 //=======================================================================
1887 //function : IsMainShape
1888 //purpose  : 
1889 //=======================================================================
1890
1891 bool SMESH_Mesh::IsMainShape(const TopoDS_Shape& theShape) const
1892 {
1893   return theShape.IsSame(_myMeshDS->ShapeToMesh() );
1894 }
1895
1896 //=============================================================================
1897 /*!
1898  *  
1899  */
1900 //=============================================================================
1901
1902 SMESH_Group* SMESH_Mesh::AddGroup (const SMDSAbs_ElementType theType,
1903                                    const char*               theName,
1904                                    int&                      theId,
1905                                    const TopoDS_Shape&       theShape,
1906                                    const SMESH_PredicatePtr& thePredicate)
1907 {
1908   if (_mapGroup.count(_groupId))
1909     return NULL;
1910   theId = _groupId;
1911   SMESH_Group* aGroup = new SMESH_Group (theId, this, theType, theName, theShape, thePredicate);
1912   GetMeshDS()->AddGroup( aGroup->GetGroupDS() );
1913   _mapGroup[_groupId++] = aGroup;
1914   return aGroup;
1915 }
1916
1917 //================================================================================
1918 /*!
1919  * \brief Creates a group based on an existing SMESHDS group. Group ID should be unique
1920  */
1921 //================================================================================
1922
1923 SMESH_Group* SMESH_Mesh::AddGroup (SMESHDS_GroupBase* groupDS) throw(SALOME_Exception)
1924 {
1925   if ( !groupDS ) 
1926     throw SALOME_Exception(LOCALIZED ("SMESH_Mesh::AddGroup(): NULL SMESHDS_GroupBase"));
1927
1928   map <int, SMESH_Group*>::iterator i_g = _mapGroup.find( groupDS->GetID() );
1929   if ( i_g != _mapGroup.end() && i_g->second )
1930   {
1931     if ( i_g->second->GetGroupDS() == groupDS )
1932       return i_g->second;
1933     else
1934       throw SALOME_Exception(LOCALIZED ("SMESH_Mesh::AddGroup() wrong ID of SMESHDS_GroupBase"));
1935   }
1936   SMESH_Group* aGroup = new SMESH_Group (groupDS);
1937   _mapGroup[ groupDS->GetID() ] = aGroup;
1938   GetMeshDS()->AddGroup( aGroup->GetGroupDS() );
1939
1940   _groupId = 1 + _mapGroup.rbegin()->first;
1941
1942   return aGroup;
1943 }
1944
1945
1946 //================================================================================
1947 /*!
1948  * \brief Creates SMESH_Groups for not wrapped SMESHDS_Groups
1949  *  \retval bool - true if new SMESH_Groups have been created
1950  * 
1951  */
1952 //================================================================================
1953
1954 bool SMESH_Mesh::SynchronizeGroups()
1955 {
1956   int nbGroups = _mapGroup.size();
1957   const set<SMESHDS_GroupBase*>& groups = _myMeshDS->GetGroups();
1958   set<SMESHDS_GroupBase*>::const_iterator gIt = groups.begin();
1959   for ( ; gIt != groups.end(); ++gIt )
1960   {
1961     SMESHDS_GroupBase* groupDS = (SMESHDS_GroupBase*) *gIt;
1962     _groupId = groupDS->GetID();
1963     if ( !_mapGroup.count( _groupId ))
1964       _mapGroup[_groupId] = new SMESH_Group( groupDS );
1965   }
1966   if ( !_mapGroup.empty() )
1967     _groupId = _mapGroup.rbegin()->first + 1;
1968
1969   return nbGroups < _mapGroup.size();
1970 }
1971
1972 //================================================================================
1973 /*!
1974  * \brief Return iterator on all existing groups
1975  */
1976 //================================================================================
1977
1978 SMESH_Mesh::GroupIteratorPtr SMESH_Mesh::GetGroups() const
1979 {
1980   typedef map <int, SMESH_Group *> TMap;
1981   return GroupIteratorPtr( new SMDS_mapIterator<TMap>( _mapGroup ));
1982 }
1983
1984 //=============================================================================
1985 /*!
1986  * \brief Return a group by ID
1987  */
1988 //=============================================================================
1989
1990 SMESH_Group* SMESH_Mesh::GetGroup (const int theGroupID)
1991 {
1992   if (_mapGroup.find(theGroupID) == _mapGroup.end())
1993     return NULL;
1994   return _mapGroup[theGroupID];
1995 }
1996
1997
1998 //=============================================================================
1999 /*!
2000  * \brief Return IDs of all groups
2001  */
2002 //=============================================================================
2003
2004 list<int> SMESH_Mesh::GetGroupIds() const
2005 {
2006   list<int> anIds;
2007   for ( map<int, SMESH_Group*>::const_iterator it = _mapGroup.begin(); it != _mapGroup.end(); it++ )
2008     anIds.push_back( it->first );
2009   
2010   return anIds;
2011 }
2012
2013 //================================================================================
2014 /*!
2015  * \brief Set a caller of methods at level of CORBA API implementation.
2016  * The set upCaller will be deleted by SMESH_Mesh
2017  */
2018 //================================================================================
2019
2020 void SMESH_Mesh::SetCallUp( TCallUp* upCaller )
2021 {
2022   if ( _callUp ) delete _callUp;
2023   _callUp = upCaller;
2024 }
2025
2026 //=============================================================================
2027 /*!
2028  *  
2029  */
2030 //=============================================================================
2031
2032 bool SMESH_Mesh::RemoveGroup (const int theGroupID)
2033 {
2034   if (_mapGroup.find(theGroupID) == _mapGroup.end())
2035     return false;
2036   GetMeshDS()->RemoveGroup( _mapGroup[theGroupID]->GetGroupDS() );
2037   delete _mapGroup[theGroupID];
2038   _mapGroup.erase (theGroupID);
2039   if (_callUp)
2040     _callUp->RemoveGroup( theGroupID );
2041   return true;
2042 }
2043
2044 //=======================================================================
2045 //function : GetAncestors
2046 //purpose  : return list of ancestors of theSubShape in the order
2047 //           that lower dimention shapes come first.
2048 //=======================================================================
2049
2050 const TopTools_ListOfShape& SMESH_Mesh::GetAncestors(const TopoDS_Shape& theS) const
2051 {
2052   if ( _mapAncestors.Contains( theS ) )
2053     return _mapAncestors.FindFromKey( theS );
2054
2055   static TopTools_ListOfShape emptyList;
2056   return emptyList;
2057 }
2058
2059 //=======================================================================
2060 //function : Dump
2061 //purpose  : dumps contents of mesh to stream [ debug purposes ]
2062 //=======================================================================
2063
2064 ostream& SMESH_Mesh::Dump(ostream& save)
2065 {
2066   int clause = 0;
2067   save << "========================== Dump contents of mesh ==========================" << endl << endl;
2068   save << ++clause << ") Total number of nodes:   \t"    << NbNodes() << endl;
2069   save << ++clause << ") Total number of edges:   \t"    << NbEdges() << endl;
2070   save << ++clause << ") Total number of faces:   \t"    << NbFaces() << endl;
2071   save << ++clause << ") Total number of polygons:\t"    << NbPolygons() << endl;
2072   save << ++clause << ") Total number of volumes:\t"     << NbVolumes() << endl;
2073   save << ++clause << ") Total number of polyhedrons:\t" << NbPolyhedrons() << endl << endl;
2074   for ( int isQuadratic = 0; isQuadratic < 2; ++isQuadratic )
2075   {
2076     string orderStr = isQuadratic ? "quadratic" : "linear";
2077     SMDSAbs_ElementOrder order  = isQuadratic ? ORDER_QUADRATIC : ORDER_LINEAR;
2078
2079     save << ++clause << ") Total number of " << orderStr << " edges:\t" << NbEdges(order) << endl;
2080     save << ++clause << ") Total number of " << orderStr << " faces:\t" << NbFaces(order) << endl;
2081     if ( NbFaces(order) > 0 ) {
2082       int nb3 = NbTriangles(order);
2083       int nb4 = NbQuadrangles(order);
2084       save << clause << ".1) Number of " << orderStr << " triangles:  \t" << nb3 << endl;
2085       save << clause << ".2) Number of " << orderStr << " quadrangles:\t" << nb4 << endl;
2086       if ( nb3 + nb4 !=  NbFaces(order) ) {
2087         map<int,int> myFaceMap;
2088         SMDS_FaceIteratorPtr itFaces=_myMeshDS->facesIterator();
2089         while( itFaces->more( ) ) {
2090           int nbNodes = itFaces->next()->NbNodes();
2091           if ( myFaceMap.find( nbNodes ) == myFaceMap.end() )
2092             myFaceMap[ nbNodes ] = 0;
2093           myFaceMap[ nbNodes ] = myFaceMap[ nbNodes ] + 1;
2094         }
2095         save << clause << ".3) Faces in detail: " << endl;
2096         map <int,int>::iterator itF;
2097         for (itF = myFaceMap.begin(); itF != myFaceMap.end(); itF++)
2098           save << "--> nb nodes: " << itF->first << " - nb elemens:\t" << itF->second << endl;
2099       }
2100     }
2101     save << ++clause << ") Total number of " << orderStr << " volumes:\t" << NbVolumes(order) << endl;
2102     if ( NbVolumes(order) > 0 ) {
2103       int nb8 = NbHexas(order);
2104       int nb4 = NbTetras(order);
2105       int nb5 = NbPyramids(order);
2106       int nb6 = NbPrisms(order);
2107       save << clause << ".1) Number of " << orderStr << " hexahedrons:\t" << nb8 << endl;
2108       save << clause << ".2) Number of " << orderStr << " tetrahedrons:\t" << nb4 << endl;
2109       save << clause << ".3) Number of " << orderStr << " prisms:      \t" << nb6 << endl;
2110       save << clause << ".4) Number of " << orderStr << " pyramids:\t" << nb5 << endl;
2111       if ( nb8 + nb4 + nb5 + nb6 != NbVolumes(order) ) {
2112         map<int,int> myVolumesMap;
2113         SMDS_VolumeIteratorPtr itVolumes=_myMeshDS->volumesIterator();
2114         while( itVolumes->more( ) ) {
2115           int nbNodes = itVolumes->next()->NbNodes();
2116           if ( myVolumesMap.find( nbNodes ) == myVolumesMap.end() )
2117             myVolumesMap[ nbNodes ] = 0;
2118           myVolumesMap[ nbNodes ] = myVolumesMap[ nbNodes ] + 1;
2119         }
2120         save << clause << ".5) Volumes in detail: " << endl;
2121         map <int,int>::iterator itV;
2122         for (itV = myVolumesMap.begin(); itV != myVolumesMap.end(); itV++)
2123           save << "--> nb nodes: " << itV->first << " - nb elemens:\t" << itV->second << endl;
2124       }
2125     }
2126     save << endl;
2127   }
2128   save << "===========================================================================" << endl;
2129   return save;
2130 }
2131
2132 //=======================================================================
2133 //function : GetElementType
2134 //purpose  : Returns type of mesh element with certain id
2135 //=======================================================================
2136
2137 SMDSAbs_ElementType SMESH_Mesh::GetElementType( const int id, const bool iselem )
2138 {
2139   return _myMeshDS->GetElementType( id, iselem );
2140 }
2141
2142 //=============================================================================
2143 /*!
2144  *  \brief Convert group on geometry into standalone group
2145  */
2146 //=============================================================================
2147
2148 SMESH_Group* SMESH_Mesh::ConvertToStandalone ( int theGroupID )
2149 {
2150   SMESH_Group* aGroup = 0;
2151   map < int, SMESH_Group * >::iterator itg = _mapGroup.find( theGroupID );
2152   if ( itg == _mapGroup.end() )
2153     return aGroup;
2154
2155   SMESH_Group* anOldGrp = (*itg).second;
2156   SMESHDS_GroupBase* anOldGrpDS = anOldGrp->GetGroupDS();
2157   if ( !anOldGrp || !anOldGrpDS )
2158     return aGroup;
2159
2160   // create new standalone group
2161   aGroup = new SMESH_Group (theGroupID, this, anOldGrpDS->GetType(), anOldGrp->GetName() );
2162   _mapGroup[theGroupID] = aGroup;
2163
2164   SMESHDS_Group* aNewGrpDS = dynamic_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
2165   GetMeshDS()->RemoveGroup( anOldGrpDS );
2166   GetMeshDS()->AddGroup( aNewGrpDS );
2167
2168   // add elements (or nodes) into new created group
2169   SMDS_ElemIteratorPtr anItr = anOldGrpDS->GetElements();
2170   while ( anItr->more() )
2171     aNewGrpDS->Add( (anItr->next())->GetID() );
2172
2173   // set color
2174   aNewGrpDS->SetColor( anOldGrpDS->GetColor() );
2175
2176   // remove old group
2177   delete anOldGrp;
2178
2179   return aGroup;
2180 }
2181
2182 //=============================================================================
2183 /*!
2184  *  \brief remove submesh order  from Mesh
2185  */
2186 //=============================================================================
2187
2188 void SMESH_Mesh::ClearMeshOrder()
2189 {
2190   _mySubMeshOrder.clear();
2191 }
2192
2193 //=============================================================================
2194 /*!
2195  *  \brief remove submesh order  from Mesh
2196  */
2197 //=============================================================================
2198
2199 void SMESH_Mesh::SetMeshOrder(const TListOfListOfInt& theOrder )
2200 {
2201   _mySubMeshOrder = theOrder;
2202 }
2203
2204 //=============================================================================
2205 /*!
2206  *  \brief return submesh order if any
2207  */
2208 //=============================================================================
2209
2210 const TListOfListOfInt& SMESH_Mesh::GetMeshOrder() const
2211 {
2212   return _mySubMeshOrder;
2213 }
2214
2215 //=============================================================================
2216 /*!
2217  *  \brief fill _mapAncestors
2218  */
2219 //=============================================================================
2220
2221 void SMESH_Mesh::fillAncestorsMap(const TopoDS_Shape& theShape)
2222 {
2223   int desType, ancType;
2224   if ( !theShape.IsSame( GetShapeToMesh()) && theShape.ShapeType() == TopAbs_COMPOUND )
2225   {
2226     // a geom group is added. Insert it into lists of ancestors before
2227     // the first ancestor more complex than group members
2228     TopoDS_Iterator subIt( theShape );
2229     if ( !subIt.More() ) return;
2230     int memberType = subIt.Value().ShapeType();
2231     for ( desType = TopAbs_VERTEX; desType >= memberType; desType-- )
2232       for (TopExp_Explorer des( theShape, TopAbs_ShapeEnum( desType )); des.More(); des.Next())
2233       {
2234         if ( !_mapAncestors.Contains( des.Current() )) continue;// issue 0020982
2235         TopTools_ListOfShape& ancList = _mapAncestors.ChangeFromKey( des.Current() );
2236         TopTools_ListIteratorOfListOfShape ancIt (ancList);
2237         while ( ancIt.More() && ancIt.Value().ShapeType() >= memberType )
2238           ancIt.Next();
2239         if ( ancIt.More() )
2240           ancList.InsertBefore( theShape, ancIt );
2241       }
2242   }
2243   else // else added for 52457: Addition of hypotheses is 8 time longer than meshing
2244   {
2245     for ( desType = TopAbs_VERTEX; desType > TopAbs_COMPOUND; desType-- )
2246       for ( ancType = desType - 1; ancType >= TopAbs_COMPOUND; ancType-- )
2247         TopExp::MapShapesAndAncestors ( theShape,
2248                                         (TopAbs_ShapeEnum) desType,
2249                                         (TopAbs_ShapeEnum) ancType,
2250                                         _mapAncestors );
2251   }
2252   // visit COMPOUNDs inside a COMPOUND that are not reachable by TopExp_Explorer
2253   if ( theShape.ShapeType() == TopAbs_COMPOUND )
2254   {
2255     TopoDS_Iterator sIt(theShape);
2256     if ( sIt.More() && sIt.Value().ShapeType() == TopAbs_COMPOUND )
2257       for ( ; sIt.More(); sIt.Next() )
2258         if ( sIt.Value().ShapeType() == TopAbs_COMPOUND )
2259           fillAncestorsMap( sIt.Value() );
2260   }
2261 }
2262
2263 //=============================================================================
2264 /*!
2265  * \brief sort submeshes according to stored mesh order
2266  * \param theListToSort in out list to be sorted
2267  * \return FALSE if nothing sorted
2268  */
2269 //=============================================================================
2270
2271  bool SMESH_Mesh::SortByMeshOrder(std::vector<SMESH_subMesh*>& theListToSort) const
2272 {
2273   if ( !_mySubMeshOrder.size() || theListToSort.size() < 2)
2274     return true;
2275   
2276   bool res = false;
2277   vector<SMESH_subMesh*> onlyOrderedList;
2278   // collect all ordered submeshes in one list as pointers
2279   // and get their positions within theListToSort
2280   typedef vector<SMESH_subMesh*>::iterator TPosInList;
2281   map< int, TPosInList > sortedPos;
2282   TPosInList smBeg = theListToSort.begin(), smEnd = theListToSort.end();
2283   TListOfListOfInt::const_iterator listIdsIt = _mySubMeshOrder.begin();
2284   for( ; listIdsIt != _mySubMeshOrder.end(); listIdsIt++)
2285   {
2286     const TListOfInt& listOfId = *listIdsIt;
2287     // convert sm ids to sm's
2288     vector<SMESH_subMesh*> smVec;
2289     TListOfInt::const_iterator idIt = listOfId.begin();
2290     for ( ; idIt != listOfId.end(); idIt++ ) {
2291       if ( SMESH_subMesh * sm = GetSubMeshContaining( *idIt )) {
2292         if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->IsComplexSubmesh() )
2293         {
2294           SMESHDS_SubMeshIteratorPtr smdsIt = sm->GetSubMeshDS()->GetSubMeshIterator();
2295           while ( smdsIt->more() )
2296           {
2297             const SMESHDS_SubMesh* smDS = smdsIt->next();
2298             if (( sm = GetSubMeshContaining( smDS->GetID() )))
2299               smVec.push_back( sm );
2300           }
2301         }
2302         else
2303         {
2304           smVec.push_back( sm );
2305         }
2306       }
2307     }
2308     // find smVec items in theListToSort
2309     for ( size_t i = 0; i < smVec.size(); ++i )
2310     {
2311       TPosInList smPos = find( smBeg, smEnd, smVec[i] );
2312       if ( smPos != smEnd ) {
2313         onlyOrderedList.push_back( smVec[i] );
2314         sortedPos[ distance( smBeg, smPos )] = smPos;
2315       }
2316     }
2317   }
2318   if (onlyOrderedList.size() < 2)
2319     return res;
2320   res = true;
2321
2322   vector<SMESH_subMesh*>::iterator onlyBIt = onlyOrderedList.begin();
2323   vector<SMESH_subMesh*>::iterator onlyEIt = onlyOrderedList.end();
2324
2325   // iterate on ordered submeshes and insert them in detected positions
2326   map< int, TPosInList >::iterator i_pos = sortedPos.begin();
2327   for ( ; onlyBIt != onlyEIt; ++onlyBIt, ++i_pos )
2328     *(i_pos->second) = *onlyBIt;
2329
2330   return res;
2331 }
2332
2333 //================================================================================
2334 /*!
2335  * \brief Return true if given order of sub-meshes is OK
2336  */
2337 //================================================================================
2338
2339 bool SMESH_Mesh::IsOrderOK( const SMESH_subMesh* smBefore,
2340                             const SMESH_subMesh* smAfter ) const
2341 {
2342   TListOfListOfInt::const_iterator listIdsIt = _mySubMeshOrder.begin();
2343   TListOfInt::const_iterator idBef, idAft;
2344   for( ; listIdsIt != _mySubMeshOrder.end(); listIdsIt++)
2345   {
2346     const TListOfInt& listOfId = *listIdsIt;
2347     idBef = std::find( listOfId.begin(), listOfId.end(), smBefore->GetId() );
2348     if ( idBef != listOfId.end() )
2349       idAft = std::find( listOfId.begin(), listOfId.end(), smAfter->GetId() );
2350     if ( idAft != listOfId.end () )
2351       return ( std::distance( listOfId.begin(), idBef ) <
2352                std::distance( listOfId.begin(), idAft )   );
2353   }
2354   return true; // no order imposed to given submeshes
2355
2356
2357 //=============================================================================
2358 /*!
2359  * \brief sort submeshes according to stored mesh order
2360  * \param theListToSort in out list to be sorted
2361  * \return FALSE if nothing sorted
2362  */
2363 //=============================================================================
2364
2365 void SMESH_Mesh::getAncestorsSubMeshes (const TopoDS_Shape&            theSubShape,
2366                                         std::vector< SMESH_subMesh* >& theSubMeshes) const
2367 {
2368   theSubMeshes.clear();
2369   TopTools_ListIteratorOfListOfShape it( GetAncestors( theSubShape ));
2370   for (; it.More(); it.Next() )
2371     if ( SMESH_subMesh* sm = GetSubMeshContaining( it.Value() ))
2372       theSubMeshes.push_back(sm);
2373
2374   // sort submeshes according to stored mesh order
2375   SortByMeshOrder( theSubMeshes );
2376 }